three.js 817 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = { REVISION: '67dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  15. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  16. // requestAnimationFrame polyfill by Erik Möller
  17. // fixes from Paul Irish and Tino Zijdel
  18. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  19. ( function () {
  20. var lastTime = 0;
  21. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  22. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  23. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  24. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  25. }
  26. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  27. self.requestAnimationFrame = function ( callback ) {
  28. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  29. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  30. lastTime = currTime + timeToCall;
  31. return id;
  32. };
  33. }
  34. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  35. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  36. }
  37. }() );
  38. // GL STATE CONSTANTS
  39. THREE.CullFaceNone = 0;
  40. THREE.CullFaceBack = 1;
  41. THREE.CullFaceFront = 2;
  42. THREE.CullFaceFrontBack = 3;
  43. THREE.FrontFaceDirectionCW = 0;
  44. THREE.FrontFaceDirectionCCW = 1;
  45. // SHADOWING TYPES
  46. THREE.BasicShadowMap = 0;
  47. THREE.PCFShadowMap = 1;
  48. THREE.PCFSoftShadowMap = 2;
  49. // MATERIAL CONSTANTS
  50. // side
  51. THREE.FrontSide = 0;
  52. THREE.BackSide = 1;
  53. THREE.DoubleSide = 2;
  54. // shading
  55. THREE.NoShading = 0;
  56. THREE.FlatShading = 1;
  57. THREE.SmoothShading = 2;
  58. // colors
  59. THREE.NoColors = 0;
  60. THREE.FaceColors = 1;
  61. THREE.VertexColors = 2;
  62. // blending modes
  63. THREE.NoBlending = 0;
  64. THREE.NormalBlending = 1;
  65. THREE.AdditiveBlending = 2;
  66. THREE.SubtractiveBlending = 3;
  67. THREE.MultiplyBlending = 4;
  68. THREE.CustomBlending = 5;
  69. // custom blending equations
  70. // (numbers start from 100 not to clash with other
  71. // mappings to OpenGL constants defined in Texture.js)
  72. THREE.AddEquation = 100;
  73. THREE.SubtractEquation = 101;
  74. THREE.ReverseSubtractEquation = 102;
  75. // custom blending destination factors
  76. THREE.ZeroFactor = 200;
  77. THREE.OneFactor = 201;
  78. THREE.SrcColorFactor = 202;
  79. THREE.OneMinusSrcColorFactor = 203;
  80. THREE.SrcAlphaFactor = 204;
  81. THREE.OneMinusSrcAlphaFactor = 205;
  82. THREE.DstAlphaFactor = 206;
  83. THREE.OneMinusDstAlphaFactor = 207;
  84. // custom blending source factors
  85. //THREE.ZeroFactor = 200;
  86. //THREE.OneFactor = 201;
  87. //THREE.SrcAlphaFactor = 204;
  88. //THREE.OneMinusSrcAlphaFactor = 205;
  89. //THREE.DstAlphaFactor = 206;
  90. //THREE.OneMinusDstAlphaFactor = 207;
  91. THREE.DstColorFactor = 208;
  92. THREE.OneMinusDstColorFactor = 209;
  93. THREE.SrcAlphaSaturateFactor = 210;
  94. // TEXTURE CONSTANTS
  95. THREE.MultiplyOperation = 0;
  96. THREE.MixOperation = 1;
  97. THREE.AddOperation = 2;
  98. // Mapping modes
  99. THREE.UVMapping = function () {};
  100. THREE.CubeReflectionMapping = function () {};
  101. THREE.CubeRefractionMapping = function () {};
  102. THREE.SphericalReflectionMapping = function () {};
  103. THREE.SphericalRefractionMapping = function () {};
  104. // Wrapping modes
  105. THREE.RepeatWrapping = 1000;
  106. THREE.ClampToEdgeWrapping = 1001;
  107. THREE.MirroredRepeatWrapping = 1002;
  108. // Filters
  109. THREE.NearestFilter = 1003;
  110. THREE.NearestMipMapNearestFilter = 1004;
  111. THREE.NearestMipMapLinearFilter = 1005;
  112. THREE.LinearFilter = 1006;
  113. THREE.LinearMipMapNearestFilter = 1007;
  114. THREE.LinearMipMapLinearFilter = 1008;
  115. // Data types
  116. THREE.UnsignedByteType = 1009;
  117. THREE.ByteType = 1010;
  118. THREE.ShortType = 1011;
  119. THREE.UnsignedShortType = 1012;
  120. THREE.IntType = 1013;
  121. THREE.UnsignedIntType = 1014;
  122. THREE.FloatType = 1015;
  123. // Pixel types
  124. //THREE.UnsignedByteType = 1009;
  125. THREE.UnsignedShort4444Type = 1016;
  126. THREE.UnsignedShort5551Type = 1017;
  127. THREE.UnsignedShort565Type = 1018;
  128. // Pixel formats
  129. THREE.AlphaFormat = 1019;
  130. THREE.RGBFormat = 1020;
  131. THREE.RGBAFormat = 1021;
  132. THREE.LuminanceFormat = 1022;
  133. THREE.LuminanceAlphaFormat = 1023;
  134. // Compressed texture formats
  135. THREE.RGB_S3TC_DXT1_Format = 2001;
  136. THREE.RGBA_S3TC_DXT1_Format = 2002;
  137. THREE.RGBA_S3TC_DXT3_Format = 2003;
  138. THREE.RGBA_S3TC_DXT5_Format = 2004;
  139. /*
  140. // Potential future PVRTC compressed texture formats
  141. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  142. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  143. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  144. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  145. */
  146. /**
  147. * @author mrdoob / http://mrdoob.com/
  148. */
  149. THREE.Color = function ( color ) {
  150. if ( arguments.length === 3 ) {
  151. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  152. }
  153. return this.set( color )
  154. };
  155. THREE.Color.prototype = {
  156. constructor: THREE.Color,
  157. r: 1, g: 1, b: 1,
  158. set: function ( value ) {
  159. if ( value instanceof THREE.Color ) {
  160. this.copy( value );
  161. } else if ( typeof value === 'number' ) {
  162. this.setHex( value );
  163. } else if ( typeof value === 'string' ) {
  164. this.setStyle( value );
  165. }
  166. return this;
  167. },
  168. setHex: function ( hex ) {
  169. hex = Math.floor( hex );
  170. this.r = ( hex >> 16 & 255 ) / 255;
  171. this.g = ( hex >> 8 & 255 ) / 255;
  172. this.b = ( hex & 255 ) / 255;
  173. return this;
  174. },
  175. setRGB: function ( r, g, b ) {
  176. this.r = r;
  177. this.g = g;
  178. this.b = b;
  179. return this;
  180. },
  181. setHSL: function ( h, s, l ) {
  182. // h,s,l ranges are in 0.0 - 1.0
  183. if ( s === 0 ) {
  184. this.r = this.g = this.b = l;
  185. } else {
  186. var hue2rgb = function ( p, q, t ) {
  187. if ( t < 0 ) t += 1;
  188. if ( t > 1 ) t -= 1;
  189. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  190. if ( t < 1 / 2 ) return q;
  191. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  192. return p;
  193. };
  194. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  195. var q = ( 2 * l ) - p;
  196. this.r = hue2rgb( q, p, h + 1 / 3 );
  197. this.g = hue2rgb( q, p, h );
  198. this.b = hue2rgb( q, p, h - 1 / 3 );
  199. }
  200. return this;
  201. },
  202. setStyle: function ( style ) {
  203. // rgb(255,0,0)
  204. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  205. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  206. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  207. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  208. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  209. return this;
  210. }
  211. // rgb(100%,0%,0%)
  212. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  213. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  214. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  215. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  216. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  217. return this;
  218. }
  219. // #ff0000
  220. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  221. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  222. this.setHex( parseInt( color[ 1 ], 16 ) );
  223. return this;
  224. }
  225. // #f00
  226. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  227. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  228. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  229. return this;
  230. }
  231. // red
  232. if ( /^(\w+)$/i.test( style ) ) {
  233. this.setHex( THREE.ColorKeywords[ style ] );
  234. return this;
  235. }
  236. },
  237. copy: function ( color ) {
  238. this.r = color.r;
  239. this.g = color.g;
  240. this.b = color.b;
  241. return this;
  242. },
  243. copyGammaToLinear: function ( color ) {
  244. this.r = color.r * color.r;
  245. this.g = color.g * color.g;
  246. this.b = color.b * color.b;
  247. return this;
  248. },
  249. copyLinearToGamma: function ( color ) {
  250. this.r = Math.sqrt( color.r );
  251. this.g = Math.sqrt( color.g );
  252. this.b = Math.sqrt( color.b );
  253. return this;
  254. },
  255. convertGammaToLinear: function () {
  256. var r = this.r, g = this.g, b = this.b;
  257. this.r = r * r;
  258. this.g = g * g;
  259. this.b = b * b;
  260. return this;
  261. },
  262. convertLinearToGamma: function () {
  263. this.r = Math.sqrt( this.r );
  264. this.g = Math.sqrt( this.g );
  265. this.b = Math.sqrt( this.b );
  266. return this;
  267. },
  268. getHex: function () {
  269. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  270. },
  271. getHexString: function () {
  272. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  273. },
  274. getHSL: function ( optionalTarget ) {
  275. // h,s,l ranges are in 0.0 - 1.0
  276. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  277. var r = this.r, g = this.g, b = this.b;
  278. var max = Math.max( r, g, b );
  279. var min = Math.min( r, g, b );
  280. var hue, saturation;
  281. var lightness = ( min + max ) / 2.0;
  282. if ( min === max ) {
  283. hue = 0;
  284. saturation = 0;
  285. } else {
  286. var delta = max - min;
  287. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  288. switch ( max ) {
  289. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  290. case g: hue = ( b - r ) / delta + 2; break;
  291. case b: hue = ( r - g ) / delta + 4; break;
  292. }
  293. hue /= 6;
  294. }
  295. hsl.h = hue;
  296. hsl.s = saturation;
  297. hsl.l = lightness;
  298. return hsl;
  299. },
  300. getStyle: function () {
  301. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  302. },
  303. offsetHSL: function ( h, s, l ) {
  304. var hsl = this.getHSL();
  305. hsl.h += h; hsl.s += s; hsl.l += l;
  306. this.setHSL( hsl.h, hsl.s, hsl.l );
  307. return this;
  308. },
  309. add: function ( color ) {
  310. this.r += color.r;
  311. this.g += color.g;
  312. this.b += color.b;
  313. return this;
  314. },
  315. addColors: function ( color1, color2 ) {
  316. this.r = color1.r + color2.r;
  317. this.g = color1.g + color2.g;
  318. this.b = color1.b + color2.b;
  319. return this;
  320. },
  321. addScalar: function ( s ) {
  322. this.r += s;
  323. this.g += s;
  324. this.b += s;
  325. return this;
  326. },
  327. multiply: function ( color ) {
  328. this.r *= color.r;
  329. this.g *= color.g;
  330. this.b *= color.b;
  331. return this;
  332. },
  333. multiplyScalar: function ( s ) {
  334. this.r *= s;
  335. this.g *= s;
  336. this.b *= s;
  337. return this;
  338. },
  339. lerp: function ( color, alpha ) {
  340. this.r += ( color.r - this.r ) * alpha;
  341. this.g += ( color.g - this.g ) * alpha;
  342. this.b += ( color.b - this.b ) * alpha;
  343. return this;
  344. },
  345. equals: function ( c ) {
  346. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  347. },
  348. fromArray: function ( array ) {
  349. this.r = array[ 0 ];
  350. this.g = array[ 1 ];
  351. this.b = array[ 2 ];
  352. return this;
  353. },
  354. toArray: function () {
  355. return [ this.r, this.g, this.b ];
  356. },
  357. clone: function () {
  358. return new THREE.Color().setRGB( this.r, this.g, this.b );
  359. }
  360. };
  361. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  362. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  363. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  364. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  365. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  366. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  367. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  368. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  369. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  370. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  371. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  372. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  373. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  374. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  375. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  376. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  377. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  378. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  379. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  380. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  381. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  382. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  383. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  384. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  385. /**
  386. * @author mikael emtinger / http://gomo.se/
  387. * @author alteredq / http://alteredqualia.com/
  388. * @author WestLangley / http://github.com/WestLangley
  389. * @author bhouston / http://exocortex.com
  390. */
  391. THREE.Quaternion = function ( x, y, z, w ) {
  392. this._x = x || 0;
  393. this._y = y || 0;
  394. this._z = z || 0;
  395. this._w = ( w !== undefined ) ? w : 1;
  396. };
  397. THREE.Quaternion.prototype = {
  398. constructor: THREE.Quaternion,
  399. _x: 0,_y: 0, _z: 0, _w: 0,
  400. _euler: undefined,
  401. _updateEuler: function ( callback ) {
  402. if ( this._euler !== undefined ) {
  403. this._euler.setFromQuaternion( this, undefined, false );
  404. }
  405. },
  406. get x () {
  407. return this._x;
  408. },
  409. set x ( value ) {
  410. this._x = value;
  411. this._updateEuler();
  412. },
  413. get y () {
  414. return this._y;
  415. },
  416. set y ( value ) {
  417. this._y = value;
  418. this._updateEuler();
  419. },
  420. get z () {
  421. return this._z;
  422. },
  423. set z ( value ) {
  424. this._z = value;
  425. this._updateEuler();
  426. },
  427. get w () {
  428. return this._w;
  429. },
  430. set w ( value ) {
  431. this._w = value;
  432. this._updateEuler();
  433. },
  434. set: function ( x, y, z, w ) {
  435. this._x = x;
  436. this._y = y;
  437. this._z = z;
  438. this._w = w;
  439. this._updateEuler();
  440. return this;
  441. },
  442. copy: function ( quaternion ) {
  443. this._x = quaternion._x;
  444. this._y = quaternion._y;
  445. this._z = quaternion._z;
  446. this._w = quaternion._w;
  447. this._updateEuler();
  448. return this;
  449. },
  450. setFromEuler: function ( euler, update ) {
  451. if ( euler instanceof THREE.Euler === false ) {
  452. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  453. }
  454. // http://www.mathworks.com/matlabcentral/fileexchange/
  455. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  456. // content/SpinCalc.m
  457. var c1 = Math.cos( euler._x / 2 );
  458. var c2 = Math.cos( euler._y / 2 );
  459. var c3 = Math.cos( euler._z / 2 );
  460. var s1 = Math.sin( euler._x / 2 );
  461. var s2 = Math.sin( euler._y / 2 );
  462. var s3 = Math.sin( euler._z / 2 );
  463. if ( euler.order === 'XYZ' ) {
  464. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  465. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  466. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  467. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  468. } else if ( euler.order === 'YXZ' ) {
  469. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  470. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  471. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  472. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  473. } else if ( euler.order === 'ZXY' ) {
  474. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  475. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  476. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  477. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  478. } else if ( euler.order === 'ZYX' ) {
  479. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  480. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  481. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  482. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  483. } else if ( euler.order === 'YZX' ) {
  484. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  485. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  486. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  487. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  488. } else if ( euler.order === 'XZY' ) {
  489. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  490. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  491. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  492. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  493. }
  494. if ( update !== false ) this._updateEuler();
  495. return this;
  496. },
  497. setFromAxisAngle: function ( axis, angle ) {
  498. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  499. // axis have to be normalized
  500. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  501. this._x = axis.x * s;
  502. this._y = axis.y * s;
  503. this._z = axis.z * s;
  504. this._w = Math.cos( halfAngle );
  505. this._updateEuler();
  506. return this;
  507. },
  508. setFromRotationMatrix: function ( m ) {
  509. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  510. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  511. var te = m.elements,
  512. m11 = te[0], m12 = te[4], m13 = te[8],
  513. m21 = te[1], m22 = te[5], m23 = te[9],
  514. m31 = te[2], m32 = te[6], m33 = te[10],
  515. trace = m11 + m22 + m33,
  516. s;
  517. if ( trace > 0 ) {
  518. s = 0.5 / Math.sqrt( trace + 1.0 );
  519. this._w = 0.25 / s;
  520. this._x = ( m32 - m23 ) * s;
  521. this._y = ( m13 - m31 ) * s;
  522. this._z = ( m21 - m12 ) * s;
  523. } else if ( m11 > m22 && m11 > m33 ) {
  524. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  525. this._w = (m32 - m23 ) / s;
  526. this._x = 0.25 * s;
  527. this._y = (m12 + m21 ) / s;
  528. this._z = (m13 + m31 ) / s;
  529. } else if ( m22 > m33 ) {
  530. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  531. this._w = (m13 - m31 ) / s;
  532. this._x = (m12 + m21 ) / s;
  533. this._y = 0.25 * s;
  534. this._z = (m23 + m32 ) / s;
  535. } else {
  536. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  537. this._w = ( m21 - m12 ) / s;
  538. this._x = ( m13 + m31 ) / s;
  539. this._y = ( m23 + m32 ) / s;
  540. this._z = 0.25 * s;
  541. }
  542. this._updateEuler();
  543. return this;
  544. },
  545. inverse: function () {
  546. this.conjugate().normalize();
  547. return this;
  548. },
  549. conjugate: function () {
  550. this._x *= -1;
  551. this._y *= -1;
  552. this._z *= -1;
  553. this._updateEuler();
  554. return this;
  555. },
  556. lengthSq: function () {
  557. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  558. },
  559. length: function () {
  560. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  561. },
  562. normalize: function () {
  563. var l = this.length();
  564. if ( l === 0 ) {
  565. this._x = 0;
  566. this._y = 0;
  567. this._z = 0;
  568. this._w = 1;
  569. } else {
  570. l = 1 / l;
  571. this._x = this._x * l;
  572. this._y = this._y * l;
  573. this._z = this._z * l;
  574. this._w = this._w * l;
  575. }
  576. return this;
  577. },
  578. multiply: function ( q, p ) {
  579. if ( p !== undefined ) {
  580. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  581. return this.multiplyQuaternions( q, p );
  582. }
  583. return this.multiplyQuaternions( this, q );
  584. },
  585. multiplyQuaternions: function ( a, b ) {
  586. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  587. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  588. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  589. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  590. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  591. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  592. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  593. this._updateEuler();
  594. return this;
  595. },
  596. multiplyVector3: function ( vector ) {
  597. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  598. return vector.applyQuaternion( this );
  599. },
  600. slerp: function ( qb, t ) {
  601. var x = this._x, y = this._y, z = this._z, w = this._w;
  602. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  603. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  604. if ( cosHalfTheta < 0 ) {
  605. this._w = -qb._w;
  606. this._x = -qb._x;
  607. this._y = -qb._y;
  608. this._z = -qb._z;
  609. cosHalfTheta = -cosHalfTheta;
  610. } else {
  611. this.copy( qb );
  612. }
  613. if ( cosHalfTheta >= 1.0 ) {
  614. this._w = w;
  615. this._x = x;
  616. this._y = y;
  617. this._z = z;
  618. return this;
  619. }
  620. var halfTheta = Math.acos( cosHalfTheta );
  621. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  622. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  623. this._w = 0.5 * ( w + this._w );
  624. this._x = 0.5 * ( x + this._x );
  625. this._y = 0.5 * ( y + this._y );
  626. this._z = 0.5 * ( z + this._z );
  627. return this;
  628. }
  629. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  630. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  631. this._w = ( w * ratioA + this._w * ratioB );
  632. this._x = ( x * ratioA + this._x * ratioB );
  633. this._y = ( y * ratioA + this._y * ratioB );
  634. this._z = ( z * ratioA + this._z * ratioB );
  635. this._updateEuler();
  636. return this;
  637. },
  638. equals: function ( quaternion ) {
  639. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  640. },
  641. fromArray: function ( array ) {
  642. this._x = array[ 0 ];
  643. this._y = array[ 1 ];
  644. this._z = array[ 2 ];
  645. this._w = array[ 3 ];
  646. this._updateEuler();
  647. return this;
  648. },
  649. toArray: function () {
  650. return [ this._x, this._y, this._z, this._w ];
  651. },
  652. clone: function () {
  653. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  654. }
  655. };
  656. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  657. return qm.copy( qa ).slerp( qb, t );
  658. }
  659. /**
  660. * @author mrdoob / http://mrdoob.com/
  661. * @author philogb / http://blog.thejit.org/
  662. * @author egraether / http://egraether.com/
  663. * @author zz85 / http://www.lab4games.net/zz85/blog
  664. */
  665. THREE.Vector2 = function ( x, y ) {
  666. this.x = x || 0;
  667. this.y = y || 0;
  668. };
  669. THREE.Vector2.prototype = {
  670. constructor: THREE.Vector2,
  671. set: function ( x, y ) {
  672. this.x = x;
  673. this.y = y;
  674. return this;
  675. },
  676. setX: function ( x ) {
  677. this.x = x;
  678. return this;
  679. },
  680. setY: function ( y ) {
  681. this.y = y;
  682. return this;
  683. },
  684. setComponent: function ( index, value ) {
  685. switch ( index ) {
  686. case 0: this.x = value; break;
  687. case 1: this.y = value; break;
  688. default: throw new Error( "index is out of range: " + index );
  689. }
  690. },
  691. getComponent: function ( index ) {
  692. switch ( index ) {
  693. case 0: return this.x;
  694. case 1: return this.y;
  695. default: throw new Error( "index is out of range: " + index );
  696. }
  697. },
  698. copy: function ( v ) {
  699. this.x = v.x;
  700. this.y = v.y;
  701. return this;
  702. },
  703. add: function ( v, w ) {
  704. if ( w !== undefined ) {
  705. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  706. return this.addVectors( v, w );
  707. }
  708. this.x += v.x;
  709. this.y += v.y;
  710. return this;
  711. },
  712. addVectors: function ( a, b ) {
  713. this.x = a.x + b.x;
  714. this.y = a.y + b.y;
  715. return this;
  716. },
  717. addScalar: function ( s ) {
  718. this.x += s;
  719. this.y += s;
  720. return this;
  721. },
  722. sub: function ( v, w ) {
  723. if ( w !== undefined ) {
  724. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  725. return this.subVectors( v, w );
  726. }
  727. this.x -= v.x;
  728. this.y -= v.y;
  729. return this;
  730. },
  731. subVectors: function ( a, b ) {
  732. this.x = a.x - b.x;
  733. this.y = a.y - b.y;
  734. return this;
  735. },
  736. multiplyScalar: function ( s ) {
  737. this.x *= s;
  738. this.y *= s;
  739. return this;
  740. },
  741. divideScalar: function ( scalar ) {
  742. if ( scalar !== 0 ) {
  743. var invScalar = 1 / scalar;
  744. this.x *= invScalar;
  745. this.y *= invScalar;
  746. } else {
  747. this.x = 0;
  748. this.y = 0;
  749. }
  750. return this;
  751. },
  752. min: function ( v ) {
  753. if ( this.x > v.x ) {
  754. this.x = v.x;
  755. }
  756. if ( this.y > v.y ) {
  757. this.y = v.y;
  758. }
  759. return this;
  760. },
  761. max: function ( v ) {
  762. if ( this.x < v.x ) {
  763. this.x = v.x;
  764. }
  765. if ( this.y < v.y ) {
  766. this.y = v.y;
  767. }
  768. return this;
  769. },
  770. clamp: function ( min, max ) {
  771. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  772. if ( this.x < min.x ) {
  773. this.x = min.x;
  774. } else if ( this.x > max.x ) {
  775. this.x = max.x;
  776. }
  777. if ( this.y < min.y ) {
  778. this.y = min.y;
  779. } else if ( this.y > max.y ) {
  780. this.y = max.y;
  781. }
  782. return this;
  783. },
  784. clampScalar: ( function () {
  785. var min, max;
  786. return function ( minVal, maxVal ) {
  787. if ( min === undefined ) {
  788. min = new THREE.Vector2();
  789. max = new THREE.Vector2();
  790. }
  791. min.set( minVal, minVal );
  792. max.set( maxVal, maxVal );
  793. return this.clamp( min, max );
  794. };
  795. } )(),
  796. floor: function () {
  797. this.x = Math.floor( this.x );
  798. this.y = Math.floor( this.y );
  799. return this;
  800. },
  801. ceil: function () {
  802. this.x = Math.ceil( this.x );
  803. this.y = Math.ceil( this.y );
  804. return this;
  805. },
  806. round: function () {
  807. this.x = Math.round( this.x );
  808. this.y = Math.round( this.y );
  809. return this;
  810. },
  811. roundToZero: function () {
  812. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  813. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  814. return this;
  815. },
  816. negate: function () {
  817. return this.multiplyScalar( - 1 );
  818. },
  819. dot: function ( v ) {
  820. return this.x * v.x + this.y * v.y;
  821. },
  822. lengthSq: function () {
  823. return this.x * this.x + this.y * this.y;
  824. },
  825. length: function () {
  826. return Math.sqrt( this.x * this.x + this.y * this.y );
  827. },
  828. normalize: function () {
  829. return this.divideScalar( this.length() );
  830. },
  831. distanceTo: function ( v ) {
  832. return Math.sqrt( this.distanceToSquared( v ) );
  833. },
  834. distanceToSquared: function ( v ) {
  835. var dx = this.x - v.x, dy = this.y - v.y;
  836. return dx * dx + dy * dy;
  837. },
  838. setLength: function ( l ) {
  839. var oldLength = this.length();
  840. if ( oldLength !== 0 && l !== oldLength ) {
  841. this.multiplyScalar( l / oldLength );
  842. }
  843. return this;
  844. },
  845. lerp: function ( v, alpha ) {
  846. this.x += ( v.x - this.x ) * alpha;
  847. this.y += ( v.y - this.y ) * alpha;
  848. return this;
  849. },
  850. equals: function( v ) {
  851. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  852. },
  853. fromArray: function ( array ) {
  854. this.x = array[ 0 ];
  855. this.y = array[ 1 ];
  856. return this;
  857. },
  858. toArray: function () {
  859. return [ this.x, this.y ];
  860. },
  861. clone: function () {
  862. return new THREE.Vector2( this.x, this.y );
  863. }
  864. };
  865. /**
  866. * @author mrdoob / http://mrdoob.com/
  867. * @author *kile / http://kile.stravaganza.org/
  868. * @author philogb / http://blog.thejit.org/
  869. * @author mikael emtinger / http://gomo.se/
  870. * @author egraether / http://egraether.com/
  871. * @author WestLangley / http://github.com/WestLangley
  872. */
  873. THREE.Vector3 = function ( x, y, z ) {
  874. this.x = x || 0;
  875. this.y = y || 0;
  876. this.z = z || 0;
  877. };
  878. THREE.Vector3.prototype = {
  879. constructor: THREE.Vector3,
  880. set: function ( x, y, z ) {
  881. this.x = x;
  882. this.y = y;
  883. this.z = z;
  884. return this;
  885. },
  886. setX: function ( x ) {
  887. this.x = x;
  888. return this;
  889. },
  890. setY: function ( y ) {
  891. this.y = y;
  892. return this;
  893. },
  894. setZ: function ( z ) {
  895. this.z = z;
  896. return this;
  897. },
  898. setComponent: function ( index, value ) {
  899. switch ( index ) {
  900. case 0: this.x = value; break;
  901. case 1: this.y = value; break;
  902. case 2: this.z = value; break;
  903. default: throw new Error( "index is out of range: " + index );
  904. }
  905. },
  906. getComponent: function ( index ) {
  907. switch ( index ) {
  908. case 0: return this.x;
  909. case 1: return this.y;
  910. case 2: return this.z;
  911. default: throw new Error( "index is out of range: " + index );
  912. }
  913. },
  914. copy: function ( v ) {
  915. this.x = v.x;
  916. this.y = v.y;
  917. this.z = v.z;
  918. return this;
  919. },
  920. add: function ( v, w ) {
  921. if ( w !== undefined ) {
  922. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  923. return this.addVectors( v, w );
  924. }
  925. this.x += v.x;
  926. this.y += v.y;
  927. this.z += v.z;
  928. return this;
  929. },
  930. addScalar: function ( s ) {
  931. this.x += s;
  932. this.y += s;
  933. this.z += s;
  934. return this;
  935. },
  936. addVectors: function ( a, b ) {
  937. this.x = a.x + b.x;
  938. this.y = a.y + b.y;
  939. this.z = a.z + b.z;
  940. return this;
  941. },
  942. sub: function ( v, w ) {
  943. if ( w !== undefined ) {
  944. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  945. return this.subVectors( v, w );
  946. }
  947. this.x -= v.x;
  948. this.y -= v.y;
  949. this.z -= v.z;
  950. return this;
  951. },
  952. subVectors: function ( a, b ) {
  953. this.x = a.x - b.x;
  954. this.y = a.y - b.y;
  955. this.z = a.z - b.z;
  956. return this;
  957. },
  958. multiply: function ( v, w ) {
  959. if ( w !== undefined ) {
  960. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  961. return this.multiplyVectors( v, w );
  962. }
  963. this.x *= v.x;
  964. this.y *= v.y;
  965. this.z *= v.z;
  966. return this;
  967. },
  968. multiplyScalar: function ( scalar ) {
  969. this.x *= scalar;
  970. this.y *= scalar;
  971. this.z *= scalar;
  972. return this;
  973. },
  974. multiplyVectors: function ( a, b ) {
  975. this.x = a.x * b.x;
  976. this.y = a.y * b.y;
  977. this.z = a.z * b.z;
  978. return this;
  979. },
  980. applyEuler: function () {
  981. var quaternion;
  982. return function ( euler ) {
  983. if ( euler instanceof THREE.Euler === false ) {
  984. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  985. }
  986. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  987. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  988. return this;
  989. };
  990. }(),
  991. applyAxisAngle: function () {
  992. var quaternion;
  993. return function ( axis, angle ) {
  994. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  995. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  996. return this;
  997. };
  998. }(),
  999. applyMatrix3: function ( m ) {
  1000. var x = this.x;
  1001. var y = this.y;
  1002. var z = this.z;
  1003. var e = m.elements;
  1004. this.x = e[0] * x + e[3] * y + e[6] * z;
  1005. this.y = e[1] * x + e[4] * y + e[7] * z;
  1006. this.z = e[2] * x + e[5] * y + e[8] * z;
  1007. return this;
  1008. },
  1009. applyMatrix4: function ( m ) {
  1010. // input: THREE.Matrix4 affine matrix
  1011. var x = this.x, y = this.y, z = this.z;
  1012. var e = m.elements;
  1013. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  1014. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  1015. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  1016. return this;
  1017. },
  1018. applyProjection: function ( m ) {
  1019. // input: THREE.Matrix4 projection matrix
  1020. var x = this.x, y = this.y, z = this.z;
  1021. var e = m.elements;
  1022. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  1023. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  1024. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  1025. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  1026. return this;
  1027. },
  1028. applyQuaternion: function ( q ) {
  1029. var x = this.x;
  1030. var y = this.y;
  1031. var z = this.z;
  1032. var qx = q.x;
  1033. var qy = q.y;
  1034. var qz = q.z;
  1035. var qw = q.w;
  1036. // calculate quat * vector
  1037. var ix = qw * x + qy * z - qz * y;
  1038. var iy = qw * y + qz * x - qx * z;
  1039. var iz = qw * z + qx * y - qy * x;
  1040. var iw = -qx * x - qy * y - qz * z;
  1041. // calculate result * inverse quat
  1042. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1043. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1044. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1045. return this;
  1046. },
  1047. transformDirection: function ( m ) {
  1048. // input: THREE.Matrix4 affine matrix
  1049. // vector interpreted as a direction
  1050. var x = this.x, y = this.y, z = this.z;
  1051. var e = m.elements;
  1052. this.x = e[0] * x + e[4] * y + e[8] * z;
  1053. this.y = e[1] * x + e[5] * y + e[9] * z;
  1054. this.z = e[2] * x + e[6] * y + e[10] * z;
  1055. this.normalize();
  1056. return this;
  1057. },
  1058. divide: function ( v ) {
  1059. this.x /= v.x;
  1060. this.y /= v.y;
  1061. this.z /= v.z;
  1062. return this;
  1063. },
  1064. divideScalar: function ( scalar ) {
  1065. if ( scalar !== 0 ) {
  1066. var invScalar = 1 / scalar;
  1067. this.x *= invScalar;
  1068. this.y *= invScalar;
  1069. this.z *= invScalar;
  1070. } else {
  1071. this.x = 0;
  1072. this.y = 0;
  1073. this.z = 0;
  1074. }
  1075. return this;
  1076. },
  1077. min: function ( v ) {
  1078. if ( this.x > v.x ) {
  1079. this.x = v.x;
  1080. }
  1081. if ( this.y > v.y ) {
  1082. this.y = v.y;
  1083. }
  1084. if ( this.z > v.z ) {
  1085. this.z = v.z;
  1086. }
  1087. return this;
  1088. },
  1089. max: function ( v ) {
  1090. if ( this.x < v.x ) {
  1091. this.x = v.x;
  1092. }
  1093. if ( this.y < v.y ) {
  1094. this.y = v.y;
  1095. }
  1096. if ( this.z < v.z ) {
  1097. this.z = v.z;
  1098. }
  1099. return this;
  1100. },
  1101. clamp: function ( min, max ) {
  1102. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1103. if ( this.x < min.x ) {
  1104. this.x = min.x;
  1105. } else if ( this.x > max.x ) {
  1106. this.x = max.x;
  1107. }
  1108. if ( this.y < min.y ) {
  1109. this.y = min.y;
  1110. } else if ( this.y > max.y ) {
  1111. this.y = max.y;
  1112. }
  1113. if ( this.z < min.z ) {
  1114. this.z = min.z;
  1115. } else if ( this.z > max.z ) {
  1116. this.z = max.z;
  1117. }
  1118. return this;
  1119. },
  1120. clampScalar: ( function () {
  1121. var min, max;
  1122. return function ( minVal, maxVal ) {
  1123. if ( min === undefined ) {
  1124. min = new THREE.Vector3();
  1125. max = new THREE.Vector3();
  1126. }
  1127. min.set( minVal, minVal, minVal );
  1128. max.set( maxVal, maxVal, maxVal );
  1129. return this.clamp( min, max );
  1130. };
  1131. } )(),
  1132. floor: function () {
  1133. this.x = Math.floor( this.x );
  1134. this.y = Math.floor( this.y );
  1135. this.z = Math.floor( this.z );
  1136. return this;
  1137. },
  1138. ceil: function () {
  1139. this.x = Math.ceil( this.x );
  1140. this.y = Math.ceil( this.y );
  1141. this.z = Math.ceil( this.z );
  1142. return this;
  1143. },
  1144. round: function () {
  1145. this.x = Math.round( this.x );
  1146. this.y = Math.round( this.y );
  1147. this.z = Math.round( this.z );
  1148. return this;
  1149. },
  1150. roundToZero: function () {
  1151. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1152. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1153. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1154. return this;
  1155. },
  1156. negate: function () {
  1157. return this.multiplyScalar( - 1 );
  1158. },
  1159. dot: function ( v ) {
  1160. return this.x * v.x + this.y * v.y + this.z * v.z;
  1161. },
  1162. lengthSq: function () {
  1163. return this.x * this.x + this.y * this.y + this.z * this.z;
  1164. },
  1165. length: function () {
  1166. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1167. },
  1168. lengthManhattan: function () {
  1169. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1170. },
  1171. normalize: function () {
  1172. return this.divideScalar( this.length() );
  1173. },
  1174. setLength: function ( l ) {
  1175. var oldLength = this.length();
  1176. if ( oldLength !== 0 && l !== oldLength ) {
  1177. this.multiplyScalar( l / oldLength );
  1178. }
  1179. return this;
  1180. },
  1181. lerp: function ( v, alpha ) {
  1182. this.x += ( v.x - this.x ) * alpha;
  1183. this.y += ( v.y - this.y ) * alpha;
  1184. this.z += ( v.z - this.z ) * alpha;
  1185. return this;
  1186. },
  1187. cross: function ( v, w ) {
  1188. if ( w !== undefined ) {
  1189. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1190. return this.crossVectors( v, w );
  1191. }
  1192. var x = this.x, y = this.y, z = this.z;
  1193. this.x = y * v.z - z * v.y;
  1194. this.y = z * v.x - x * v.z;
  1195. this.z = x * v.y - y * v.x;
  1196. return this;
  1197. },
  1198. crossVectors: function ( a, b ) {
  1199. var ax = a.x, ay = a.y, az = a.z;
  1200. var bx = b.x, by = b.y, bz = b.z;
  1201. this.x = ay * bz - az * by;
  1202. this.y = az * bx - ax * bz;
  1203. this.z = ax * by - ay * bx;
  1204. return this;
  1205. },
  1206. projectOnVector: function () {
  1207. var v1, dot;
  1208. return function ( vector ) {
  1209. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1210. v1.copy( vector ).normalize();
  1211. dot = this.dot( v1 );
  1212. return this.copy( v1 ).multiplyScalar( dot );
  1213. };
  1214. }(),
  1215. projectOnPlane: function () {
  1216. var v1;
  1217. return function ( planeNormal ) {
  1218. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1219. v1.copy( this ).projectOnVector( planeNormal );
  1220. return this.sub( v1 );
  1221. }
  1222. }(),
  1223. reflect: function () {
  1224. // reflect incident vector off plane orthogonal to normal
  1225. // normal is assumed to have unit length
  1226. var v1;
  1227. return function ( normal ) {
  1228. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1229. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1230. }
  1231. }(),
  1232. angleTo: function ( v ) {
  1233. var theta = this.dot( v ) / ( this.length() * v.length() );
  1234. // clamp, to handle numerical problems
  1235. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1236. },
  1237. distanceTo: function ( v ) {
  1238. return Math.sqrt( this.distanceToSquared( v ) );
  1239. },
  1240. distanceToSquared: function ( v ) {
  1241. var dx = this.x - v.x;
  1242. var dy = this.y - v.y;
  1243. var dz = this.z - v.z;
  1244. return dx * dx + dy * dy + dz * dz;
  1245. },
  1246. setEulerFromRotationMatrix: function ( m, order ) {
  1247. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1248. },
  1249. setEulerFromQuaternion: function ( q, order ) {
  1250. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1251. },
  1252. getPositionFromMatrix: function ( m ) {
  1253. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1254. return this.setFromMatrixPosition( m );
  1255. },
  1256. getScaleFromMatrix: function ( m ) {
  1257. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1258. return this.setFromMatrixScale( m );
  1259. },
  1260. getColumnFromMatrix: function ( index, matrix ) {
  1261. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1262. return this.setFromMatrixColumn( index, matrix );
  1263. },
  1264. setFromMatrixPosition: function ( m ) {
  1265. this.x = m.elements[ 12 ];
  1266. this.y = m.elements[ 13 ];
  1267. this.z = m.elements[ 14 ];
  1268. return this;
  1269. },
  1270. setFromMatrixScale: function ( m ) {
  1271. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1272. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1273. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1274. this.x = sx;
  1275. this.y = sy;
  1276. this.z = sz;
  1277. return this;
  1278. },
  1279. setFromMatrixColumn: function ( index, matrix ) {
  1280. var offset = index * 4;
  1281. var me = matrix.elements;
  1282. this.x = me[ offset ];
  1283. this.y = me[ offset + 1 ];
  1284. this.z = me[ offset + 2 ];
  1285. return this;
  1286. },
  1287. equals: function ( v ) {
  1288. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1289. },
  1290. fromArray: function ( array ) {
  1291. this.x = array[ 0 ];
  1292. this.y = array[ 1 ];
  1293. this.z = array[ 2 ];
  1294. return this;
  1295. },
  1296. toArray: function () {
  1297. return [ this.x, this.y, this.z ];
  1298. },
  1299. clone: function () {
  1300. return new THREE.Vector3( this.x, this.y, this.z );
  1301. }
  1302. };
  1303. /**
  1304. * @author supereggbert / http://www.paulbrunt.co.uk/
  1305. * @author philogb / http://blog.thejit.org/
  1306. * @author mikael emtinger / http://gomo.se/
  1307. * @author egraether / http://egraether.com/
  1308. * @author WestLangley / http://github.com/WestLangley
  1309. */
  1310. THREE.Vector4 = function ( x, y, z, w ) {
  1311. this.x = x || 0;
  1312. this.y = y || 0;
  1313. this.z = z || 0;
  1314. this.w = ( w !== undefined ) ? w : 1;
  1315. };
  1316. THREE.Vector4.prototype = {
  1317. constructor: THREE.Vector4,
  1318. set: function ( x, y, z, w ) {
  1319. this.x = x;
  1320. this.y = y;
  1321. this.z = z;
  1322. this.w = w;
  1323. return this;
  1324. },
  1325. setX: function ( x ) {
  1326. this.x = x;
  1327. return this;
  1328. },
  1329. setY: function ( y ) {
  1330. this.y = y;
  1331. return this;
  1332. },
  1333. setZ: function ( z ) {
  1334. this.z = z;
  1335. return this;
  1336. },
  1337. setW: function ( w ) {
  1338. this.w = w;
  1339. return this;
  1340. },
  1341. setComponent: function ( index, value ) {
  1342. switch ( index ) {
  1343. case 0: this.x = value; break;
  1344. case 1: this.y = value; break;
  1345. case 2: this.z = value; break;
  1346. case 3: this.w = value; break;
  1347. default: throw new Error( "index is out of range: " + index );
  1348. }
  1349. },
  1350. getComponent: function ( index ) {
  1351. switch ( index ) {
  1352. case 0: return this.x;
  1353. case 1: return this.y;
  1354. case 2: return this.z;
  1355. case 3: return this.w;
  1356. default: throw new Error( "index is out of range: " + index );
  1357. }
  1358. },
  1359. copy: function ( v ) {
  1360. this.x = v.x;
  1361. this.y = v.y;
  1362. this.z = v.z;
  1363. this.w = ( v.w !== undefined ) ? v.w : 1;
  1364. return this;
  1365. },
  1366. add: function ( v, w ) {
  1367. if ( w !== undefined ) {
  1368. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1369. return this.addVectors( v, w );
  1370. }
  1371. this.x += v.x;
  1372. this.y += v.y;
  1373. this.z += v.z;
  1374. this.w += v.w;
  1375. return this;
  1376. },
  1377. addScalar: function ( s ) {
  1378. this.x += s;
  1379. this.y += s;
  1380. this.z += s;
  1381. this.w += s;
  1382. return this;
  1383. },
  1384. addVectors: function ( a, b ) {
  1385. this.x = a.x + b.x;
  1386. this.y = a.y + b.y;
  1387. this.z = a.z + b.z;
  1388. this.w = a.w + b.w;
  1389. return this;
  1390. },
  1391. sub: function ( v, w ) {
  1392. if ( w !== undefined ) {
  1393. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1394. return this.subVectors( v, w );
  1395. }
  1396. this.x -= v.x;
  1397. this.y -= v.y;
  1398. this.z -= v.z;
  1399. this.w -= v.w;
  1400. return this;
  1401. },
  1402. subVectors: function ( a, b ) {
  1403. this.x = a.x - b.x;
  1404. this.y = a.y - b.y;
  1405. this.z = a.z - b.z;
  1406. this.w = a.w - b.w;
  1407. return this;
  1408. },
  1409. multiplyScalar: function ( scalar ) {
  1410. this.x *= scalar;
  1411. this.y *= scalar;
  1412. this.z *= scalar;
  1413. this.w *= scalar;
  1414. return this;
  1415. },
  1416. applyMatrix4: function ( m ) {
  1417. var x = this.x;
  1418. var y = this.y;
  1419. var z = this.z;
  1420. var w = this.w;
  1421. var e = m.elements;
  1422. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1423. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1424. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1425. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1426. return this;
  1427. },
  1428. divideScalar: function ( scalar ) {
  1429. if ( scalar !== 0 ) {
  1430. var invScalar = 1 / scalar;
  1431. this.x *= invScalar;
  1432. this.y *= invScalar;
  1433. this.z *= invScalar;
  1434. this.w *= invScalar;
  1435. } else {
  1436. this.x = 0;
  1437. this.y = 0;
  1438. this.z = 0;
  1439. this.w = 1;
  1440. }
  1441. return this;
  1442. },
  1443. setAxisAngleFromQuaternion: function ( q ) {
  1444. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1445. // q is assumed to be normalized
  1446. this.w = 2 * Math.acos( q.w );
  1447. var s = Math.sqrt( 1 - q.w * q.w );
  1448. if ( s < 0.0001 ) {
  1449. this.x = 1;
  1450. this.y = 0;
  1451. this.z = 0;
  1452. } else {
  1453. this.x = q.x / s;
  1454. this.y = q.y / s;
  1455. this.z = q.z / s;
  1456. }
  1457. return this;
  1458. },
  1459. setAxisAngleFromRotationMatrix: function ( m ) {
  1460. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1461. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1462. var angle, x, y, z, // variables for result
  1463. epsilon = 0.01, // margin to allow for rounding errors
  1464. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1465. te = m.elements,
  1466. m11 = te[0], m12 = te[4], m13 = te[8],
  1467. m21 = te[1], m22 = te[5], m23 = te[9],
  1468. m31 = te[2], m32 = te[6], m33 = te[10];
  1469. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1470. && ( Math.abs( m13 - m31 ) < epsilon )
  1471. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1472. // singularity found
  1473. // first check for identity matrix which must have +1 for all terms
  1474. // in leading diagonal and zero in other terms
  1475. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1476. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1477. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1478. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1479. // this singularity is identity matrix so angle = 0
  1480. this.set( 1, 0, 0, 0 );
  1481. return this; // zero angle, arbitrary axis
  1482. }
  1483. // otherwise this singularity is angle = 180
  1484. angle = Math.PI;
  1485. var xx = ( m11 + 1 ) / 2;
  1486. var yy = ( m22 + 1 ) / 2;
  1487. var zz = ( m33 + 1 ) / 2;
  1488. var xy = ( m12 + m21 ) / 4;
  1489. var xz = ( m13 + m31 ) / 4;
  1490. var yz = ( m23 + m32 ) / 4;
  1491. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1492. if ( xx < epsilon ) {
  1493. x = 0;
  1494. y = 0.707106781;
  1495. z = 0.707106781;
  1496. } else {
  1497. x = Math.sqrt( xx );
  1498. y = xy / x;
  1499. z = xz / x;
  1500. }
  1501. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1502. if ( yy < epsilon ) {
  1503. x = 0.707106781;
  1504. y = 0;
  1505. z = 0.707106781;
  1506. } else {
  1507. y = Math.sqrt( yy );
  1508. x = xy / y;
  1509. z = yz / y;
  1510. }
  1511. } else { // m33 is the largest diagonal term so base result on this
  1512. if ( zz < epsilon ) {
  1513. x = 0.707106781;
  1514. y = 0.707106781;
  1515. z = 0;
  1516. } else {
  1517. z = Math.sqrt( zz );
  1518. x = xz / z;
  1519. y = yz / z;
  1520. }
  1521. }
  1522. this.set( x, y, z, angle );
  1523. return this; // return 180 deg rotation
  1524. }
  1525. // as we have reached here there are no singularities so we can handle normally
  1526. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1527. + ( m13 - m31 ) * ( m13 - m31 )
  1528. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1529. if ( Math.abs( s ) < 0.001 ) s = 1;
  1530. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1531. // caught by singularity test above, but I've left it in just in case
  1532. this.x = ( m32 - m23 ) / s;
  1533. this.y = ( m13 - m31 ) / s;
  1534. this.z = ( m21 - m12 ) / s;
  1535. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1536. return this;
  1537. },
  1538. min: function ( v ) {
  1539. if ( this.x > v.x ) {
  1540. this.x = v.x;
  1541. }
  1542. if ( this.y > v.y ) {
  1543. this.y = v.y;
  1544. }
  1545. if ( this.z > v.z ) {
  1546. this.z = v.z;
  1547. }
  1548. if ( this.w > v.w ) {
  1549. this.w = v.w;
  1550. }
  1551. return this;
  1552. },
  1553. max: function ( v ) {
  1554. if ( this.x < v.x ) {
  1555. this.x = v.x;
  1556. }
  1557. if ( this.y < v.y ) {
  1558. this.y = v.y;
  1559. }
  1560. if ( this.z < v.z ) {
  1561. this.z = v.z;
  1562. }
  1563. if ( this.w < v.w ) {
  1564. this.w = v.w;
  1565. }
  1566. return this;
  1567. },
  1568. clamp: function ( min, max ) {
  1569. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1570. if ( this.x < min.x ) {
  1571. this.x = min.x;
  1572. } else if ( this.x > max.x ) {
  1573. this.x = max.x;
  1574. }
  1575. if ( this.y < min.y ) {
  1576. this.y = min.y;
  1577. } else if ( this.y > max.y ) {
  1578. this.y = max.y;
  1579. }
  1580. if ( this.z < min.z ) {
  1581. this.z = min.z;
  1582. } else if ( this.z > max.z ) {
  1583. this.z = max.z;
  1584. }
  1585. if ( this.w < min.w ) {
  1586. this.w = min.w;
  1587. } else if ( this.w > max.w ) {
  1588. this.w = max.w;
  1589. }
  1590. return this;
  1591. },
  1592. clampScalar: ( function () {
  1593. var min, max;
  1594. return function ( minVal, maxVal ) {
  1595. if ( min === undefined ) {
  1596. min = new THREE.Vector4();
  1597. max = new THREE.Vector4();
  1598. }
  1599. min.set( minVal, minVal, minVal, minVal );
  1600. max.set( maxVal, maxVal, maxVal, maxVal );
  1601. return this.clamp( min, max );
  1602. };
  1603. } )(),
  1604. floor: function () {
  1605. this.x = Math.floor( this.x );
  1606. this.y = Math.floor( this.y );
  1607. this.z = Math.floor( this.z );
  1608. this.w = Math.floor( this.w );
  1609. return this;
  1610. },
  1611. ceil: function () {
  1612. this.x = Math.ceil( this.x );
  1613. this.y = Math.ceil( this.y );
  1614. this.z = Math.ceil( this.z );
  1615. this.w = Math.ceil( this.w );
  1616. return this;
  1617. },
  1618. round: function () {
  1619. this.x = Math.round( this.x );
  1620. this.y = Math.round( this.y );
  1621. this.z = Math.round( this.z );
  1622. this.w = Math.round( this.w );
  1623. return this;
  1624. },
  1625. roundToZero: function () {
  1626. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1627. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1628. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1629. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1630. return this;
  1631. },
  1632. negate: function () {
  1633. return this.multiplyScalar( -1 );
  1634. },
  1635. dot: function ( v ) {
  1636. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1637. },
  1638. lengthSq: function () {
  1639. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1640. },
  1641. length: function () {
  1642. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1643. },
  1644. lengthManhattan: function () {
  1645. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1646. },
  1647. normalize: function () {
  1648. return this.divideScalar( this.length() );
  1649. },
  1650. setLength: function ( l ) {
  1651. var oldLength = this.length();
  1652. if ( oldLength !== 0 && l !== oldLength ) {
  1653. this.multiplyScalar( l / oldLength );
  1654. }
  1655. return this;
  1656. },
  1657. lerp: function ( v, alpha ) {
  1658. this.x += ( v.x - this.x ) * alpha;
  1659. this.y += ( v.y - this.y ) * alpha;
  1660. this.z += ( v.z - this.z ) * alpha;
  1661. this.w += ( v.w - this.w ) * alpha;
  1662. return this;
  1663. },
  1664. equals: function ( v ) {
  1665. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1666. },
  1667. fromArray: function ( array ) {
  1668. this.x = array[ 0 ];
  1669. this.y = array[ 1 ];
  1670. this.z = array[ 2 ];
  1671. this.w = array[ 3 ];
  1672. return this;
  1673. },
  1674. toArray: function () {
  1675. return [ this.x, this.y, this.z, this.w ];
  1676. },
  1677. clone: function () {
  1678. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1679. }
  1680. };
  1681. /**
  1682. * @author mrdoob / http://mrdoob.com/
  1683. * @author WestLangley / http://github.com/WestLangley
  1684. * @author bhouston / http://exocortex.com
  1685. */
  1686. THREE.Euler = function ( x, y, z, order ) {
  1687. this._x = x || 0;
  1688. this._y = y || 0;
  1689. this._z = z || 0;
  1690. this._order = order || THREE.Euler.DefaultOrder;
  1691. };
  1692. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1693. THREE.Euler.DefaultOrder = 'XYZ';
  1694. THREE.Euler.prototype = {
  1695. constructor: THREE.Euler,
  1696. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1697. _quaternion: undefined,
  1698. _updateQuaternion: function () {
  1699. if ( this._quaternion !== undefined ) {
  1700. this._quaternion.setFromEuler( this, false );
  1701. }
  1702. },
  1703. get x () {
  1704. return this._x;
  1705. },
  1706. set x ( value ) {
  1707. this._x = value;
  1708. this._updateQuaternion();
  1709. },
  1710. get y () {
  1711. return this._y;
  1712. },
  1713. set y ( value ) {
  1714. this._y = value;
  1715. this._updateQuaternion();
  1716. },
  1717. get z () {
  1718. return this._z;
  1719. },
  1720. set z ( value ) {
  1721. this._z = value;
  1722. this._updateQuaternion();
  1723. },
  1724. get order () {
  1725. return this._order;
  1726. },
  1727. set order ( value ) {
  1728. this._order = value;
  1729. this._updateQuaternion();
  1730. },
  1731. set: function ( x, y, z, order ) {
  1732. this._x = x;
  1733. this._y = y;
  1734. this._z = z;
  1735. this._order = order || this._order;
  1736. this._updateQuaternion();
  1737. return this;
  1738. },
  1739. copy: function ( euler ) {
  1740. this._x = euler._x;
  1741. this._y = euler._y;
  1742. this._z = euler._z;
  1743. this._order = euler._order;
  1744. this._updateQuaternion();
  1745. return this;
  1746. },
  1747. setFromRotationMatrix: function ( m, order ) {
  1748. var clamp = THREE.Math.clamp;
  1749. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1750. var te = m.elements;
  1751. var m11 = te[0], m12 = te[4], m13 = te[8];
  1752. var m21 = te[1], m22 = te[5], m23 = te[9];
  1753. var m31 = te[2], m32 = te[6], m33 = te[10];
  1754. order = order || this._order;
  1755. if ( order === 'XYZ' ) {
  1756. this._y = Math.asin( clamp( m13, -1, 1 ) );
  1757. if ( Math.abs( m13 ) < 0.99999 ) {
  1758. this._x = Math.atan2( - m23, m33 );
  1759. this._z = Math.atan2( - m12, m11 );
  1760. } else {
  1761. this._x = Math.atan2( m32, m22 );
  1762. this._z = 0;
  1763. }
  1764. } else if ( order === 'YXZ' ) {
  1765. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  1766. if ( Math.abs( m23 ) < 0.99999 ) {
  1767. this._y = Math.atan2( m13, m33 );
  1768. this._z = Math.atan2( m21, m22 );
  1769. } else {
  1770. this._y = Math.atan2( - m31, m11 );
  1771. this._z = 0;
  1772. }
  1773. } else if ( order === 'ZXY' ) {
  1774. this._x = Math.asin( clamp( m32, -1, 1 ) );
  1775. if ( Math.abs( m32 ) < 0.99999 ) {
  1776. this._y = Math.atan2( - m31, m33 );
  1777. this._z = Math.atan2( - m12, m22 );
  1778. } else {
  1779. this._y = 0;
  1780. this._z = Math.atan2( m21, m11 );
  1781. }
  1782. } else if ( order === 'ZYX' ) {
  1783. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  1784. if ( Math.abs( m31 ) < 0.99999 ) {
  1785. this._x = Math.atan2( m32, m33 );
  1786. this._z = Math.atan2( m21, m11 );
  1787. } else {
  1788. this._x = 0;
  1789. this._z = Math.atan2( - m12, m22 );
  1790. }
  1791. } else if ( order === 'YZX' ) {
  1792. this._z = Math.asin( clamp( m21, -1, 1 ) );
  1793. if ( Math.abs( m21 ) < 0.99999 ) {
  1794. this._x = Math.atan2( - m23, m22 );
  1795. this._y = Math.atan2( - m31, m11 );
  1796. } else {
  1797. this._x = 0;
  1798. this._y = Math.atan2( m13, m33 );
  1799. }
  1800. } else if ( order === 'XZY' ) {
  1801. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  1802. if ( Math.abs( m12 ) < 0.99999 ) {
  1803. this._x = Math.atan2( m32, m22 );
  1804. this._y = Math.atan2( m13, m11 );
  1805. } else {
  1806. this._x = Math.atan2( - m23, m33 );
  1807. this._y = 0;
  1808. }
  1809. } else {
  1810. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1811. }
  1812. this._order = order;
  1813. this._updateQuaternion();
  1814. return this;
  1815. },
  1816. setFromQuaternion: function ( q, order, update ) {
  1817. var clamp = THREE.Math.clamp;
  1818. // q is assumed to be normalized
  1819. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1820. var sqx = q.x * q.x;
  1821. var sqy = q.y * q.y;
  1822. var sqz = q.z * q.z;
  1823. var sqw = q.w * q.w;
  1824. order = order || this._order;
  1825. if ( order === 'XYZ' ) {
  1826. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1827. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), -1, 1 ) );
  1828. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1829. } else if ( order === 'YXZ' ) {
  1830. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ), -1, 1 ) );
  1831. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1832. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1833. } else if ( order === 'ZXY' ) {
  1834. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ), -1, 1 ) );
  1835. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1836. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1837. } else if ( order === 'ZYX' ) {
  1838. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1839. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ), -1, 1 ) );
  1840. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1841. } else if ( order === 'YZX' ) {
  1842. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1843. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1844. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ), -1, 1 ) );
  1845. } else if ( order === 'XZY' ) {
  1846. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1847. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1848. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ), -1, 1 ) );
  1849. } else {
  1850. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1851. }
  1852. this._order = order;
  1853. if ( update !== false ) this._updateQuaternion();
  1854. return this;
  1855. },
  1856. reorder: function () {
  1857. // WARNING: this discards revolution information -bhouston
  1858. var q = new THREE.Quaternion();
  1859. return function ( newOrder ) {
  1860. q.setFromEuler( this );
  1861. this.setFromQuaternion( q, newOrder );
  1862. };
  1863. }(),
  1864. fromArray: function ( array ) {
  1865. this._x = array[ 0 ];
  1866. this._y = array[ 1 ];
  1867. this._z = array[ 2 ];
  1868. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1869. this._updateQuaternion();
  1870. return this;
  1871. },
  1872. toArray: function () {
  1873. return [ this._x, this._y, this._z, this._order ];
  1874. },
  1875. equals: function ( euler ) {
  1876. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1877. },
  1878. clone: function () {
  1879. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1880. }
  1881. };
  1882. /**
  1883. * @author bhouston / http://exocortex.com
  1884. */
  1885. THREE.Line3 = function ( start, end ) {
  1886. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1887. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1888. };
  1889. THREE.Line3.prototype = {
  1890. constructor: THREE.Line3,
  1891. set: function ( start, end ) {
  1892. this.start.copy( start );
  1893. this.end.copy( end );
  1894. return this;
  1895. },
  1896. copy: function ( line ) {
  1897. this.start.copy( line.start );
  1898. this.end.copy( line.end );
  1899. return this;
  1900. },
  1901. center: function ( optionalTarget ) {
  1902. var result = optionalTarget || new THREE.Vector3();
  1903. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1904. },
  1905. delta: function ( optionalTarget ) {
  1906. var result = optionalTarget || new THREE.Vector3();
  1907. return result.subVectors( this.end, this.start );
  1908. },
  1909. distanceSq: function () {
  1910. return this.start.distanceToSquared( this.end );
  1911. },
  1912. distance: function () {
  1913. return this.start.distanceTo( this.end );
  1914. },
  1915. at: function ( t, optionalTarget ) {
  1916. var result = optionalTarget || new THREE.Vector3();
  1917. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1918. },
  1919. closestPointToPointParameter: function() {
  1920. var startP = new THREE.Vector3();
  1921. var startEnd = new THREE.Vector3();
  1922. return function ( point, clampToLine ) {
  1923. startP.subVectors( point, this.start );
  1924. startEnd.subVectors( this.end, this.start );
  1925. var startEnd2 = startEnd.dot( startEnd );
  1926. var startEnd_startP = startEnd.dot( startP );
  1927. var t = startEnd_startP / startEnd2;
  1928. if ( clampToLine ) {
  1929. t = THREE.Math.clamp( t, 0, 1 );
  1930. }
  1931. return t;
  1932. };
  1933. }(),
  1934. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1935. var t = this.closestPointToPointParameter( point, clampToLine );
  1936. var result = optionalTarget || new THREE.Vector3();
  1937. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1938. },
  1939. applyMatrix4: function ( matrix ) {
  1940. this.start.applyMatrix4( matrix );
  1941. this.end.applyMatrix4( matrix );
  1942. return this;
  1943. },
  1944. equals: function ( line ) {
  1945. return line.start.equals( this.start ) && line.end.equals( this.end );
  1946. },
  1947. clone: function () {
  1948. return new THREE.Line3().copy( this );
  1949. }
  1950. };
  1951. /**
  1952. * @author bhouston / http://exocortex.com
  1953. */
  1954. THREE.Box2 = function ( min, max ) {
  1955. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1956. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1957. };
  1958. THREE.Box2.prototype = {
  1959. constructor: THREE.Box2,
  1960. set: function ( min, max ) {
  1961. this.min.copy( min );
  1962. this.max.copy( max );
  1963. return this;
  1964. },
  1965. setFromPoints: function ( points ) {
  1966. if ( points.length > 0 ) {
  1967. var point = points[ 0 ];
  1968. this.min.copy( point );
  1969. this.max.copy( point );
  1970. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1971. point = points[ i ];
  1972. if ( point.x < this.min.x ) {
  1973. this.min.x = point.x;
  1974. } else if ( point.x > this.max.x ) {
  1975. this.max.x = point.x;
  1976. }
  1977. if ( point.y < this.min.y ) {
  1978. this.min.y = point.y;
  1979. } else if ( point.y > this.max.y ) {
  1980. this.max.y = point.y;
  1981. }
  1982. }
  1983. } else {
  1984. this.makeEmpty();
  1985. }
  1986. return this;
  1987. },
  1988. setFromCenterAndSize: function () {
  1989. var v1 = new THREE.Vector2();
  1990. return function ( center, size ) {
  1991. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1992. this.min.copy( center ).sub( halfSize );
  1993. this.max.copy( center ).add( halfSize );
  1994. return this;
  1995. };
  1996. }(),
  1997. copy: function ( box ) {
  1998. this.min.copy( box.min );
  1999. this.max.copy( box.max );
  2000. return this;
  2001. },
  2002. makeEmpty: function () {
  2003. this.min.x = this.min.y = Infinity;
  2004. this.max.x = this.max.y = -Infinity;
  2005. return this;
  2006. },
  2007. empty: function () {
  2008. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2009. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2010. },
  2011. center: function ( optionalTarget ) {
  2012. var result = optionalTarget || new THREE.Vector2();
  2013. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2014. },
  2015. size: function ( optionalTarget ) {
  2016. var result = optionalTarget || new THREE.Vector2();
  2017. return result.subVectors( this.max, this.min );
  2018. },
  2019. expandByPoint: function ( point ) {
  2020. this.min.min( point );
  2021. this.max.max( point );
  2022. return this;
  2023. },
  2024. expandByVector: function ( vector ) {
  2025. this.min.sub( vector );
  2026. this.max.add( vector );
  2027. return this;
  2028. },
  2029. expandByScalar: function ( scalar ) {
  2030. this.min.addScalar( -scalar );
  2031. this.max.addScalar( scalar );
  2032. return this;
  2033. },
  2034. containsPoint: function ( point ) {
  2035. if ( point.x < this.min.x || point.x > this.max.x ||
  2036. point.y < this.min.y || point.y > this.max.y ) {
  2037. return false;
  2038. }
  2039. return true;
  2040. },
  2041. containsBox: function ( box ) {
  2042. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2043. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2044. return true;
  2045. }
  2046. return false;
  2047. },
  2048. getParameter: function ( point, optionalTarget ) {
  2049. // This can potentially have a divide by zero if the box
  2050. // has a size dimension of 0.
  2051. var result = optionalTarget || new THREE.Vector2();
  2052. return result.set(
  2053. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2054. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2055. );
  2056. },
  2057. isIntersectionBox: function ( box ) {
  2058. // using 6 splitting planes to rule out intersections.
  2059. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2060. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2061. return false;
  2062. }
  2063. return true;
  2064. },
  2065. clampPoint: function ( point, optionalTarget ) {
  2066. var result = optionalTarget || new THREE.Vector2();
  2067. return result.copy( point ).clamp( this.min, this.max );
  2068. },
  2069. distanceToPoint: function () {
  2070. var v1 = new THREE.Vector2();
  2071. return function ( point ) {
  2072. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2073. return clampedPoint.sub( point ).length();
  2074. };
  2075. }(),
  2076. intersect: function ( box ) {
  2077. this.min.max( box.min );
  2078. this.max.min( box.max );
  2079. return this;
  2080. },
  2081. union: function ( box ) {
  2082. this.min.min( box.min );
  2083. this.max.max( box.max );
  2084. return this;
  2085. },
  2086. translate: function ( offset ) {
  2087. this.min.add( offset );
  2088. this.max.add( offset );
  2089. return this;
  2090. },
  2091. equals: function ( box ) {
  2092. return box.min.equals( this.min ) && box.max.equals( this.max );
  2093. },
  2094. clone: function () {
  2095. return new THREE.Box2().copy( this );
  2096. }
  2097. };
  2098. /**
  2099. * @author bhouston / http://exocortex.com
  2100. * @author WestLangley / http://github.com/WestLangley
  2101. */
  2102. THREE.Box3 = function ( min, max ) {
  2103. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2104. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2105. };
  2106. THREE.Box3.prototype = {
  2107. constructor: THREE.Box3,
  2108. set: function ( min, max ) {
  2109. this.min.copy( min );
  2110. this.max.copy( max );
  2111. return this;
  2112. },
  2113. addPoint: function ( point ) {
  2114. if ( point.x < this.min.x ) {
  2115. this.min.x = point.x;
  2116. } else if ( point.x > this.max.x ) {
  2117. this.max.x = point.x;
  2118. }
  2119. if ( point.y < this.min.y ) {
  2120. this.min.y = point.y;
  2121. } else if ( point.y > this.max.y ) {
  2122. this.max.y = point.y;
  2123. }
  2124. if ( point.z < this.min.z ) {
  2125. this.min.z = point.z;
  2126. } else if ( point.z > this.max.z ) {
  2127. this.max.z = point.z;
  2128. }
  2129. },
  2130. setFromPoints: function ( points ) {
  2131. if ( points.length > 0 ) {
  2132. var point = points[ 0 ];
  2133. this.min.copy( point );
  2134. this.max.copy( point );
  2135. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2136. this.addPoint( points[ i ] )
  2137. }
  2138. } else {
  2139. this.makeEmpty();
  2140. }
  2141. return this;
  2142. },
  2143. setFromCenterAndSize: function() {
  2144. var v1 = new THREE.Vector3();
  2145. return function ( center, size ) {
  2146. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2147. this.min.copy( center ).sub( halfSize );
  2148. this.max.copy( center ).add( halfSize );
  2149. return this;
  2150. };
  2151. }(),
  2152. setFromObject: function() {
  2153. // Computes the world-axis-aligned bounding box of an object (including its children),
  2154. // accounting for both the object's, and childrens', world transforms
  2155. var v1 = new THREE.Vector3();
  2156. return function( object ) {
  2157. var scope = this;
  2158. object.updateMatrixWorld( true );
  2159. this.makeEmpty();
  2160. object.traverse( function ( node ) {
  2161. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2162. var vertices = node.geometry.vertices;
  2163. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2164. v1.copy( vertices[ i ] );
  2165. v1.applyMatrix4( node.matrixWorld );
  2166. scope.expandByPoint( v1 );
  2167. }
  2168. }
  2169. } );
  2170. return this;
  2171. };
  2172. }(),
  2173. copy: function ( box ) {
  2174. this.min.copy( box.min );
  2175. this.max.copy( box.max );
  2176. return this;
  2177. },
  2178. makeEmpty: function () {
  2179. this.min.x = this.min.y = this.min.z = Infinity;
  2180. this.max.x = this.max.y = this.max.z = -Infinity;
  2181. return this;
  2182. },
  2183. empty: function () {
  2184. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2185. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2186. },
  2187. center: function ( optionalTarget ) {
  2188. var result = optionalTarget || new THREE.Vector3();
  2189. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2190. },
  2191. size: function ( optionalTarget ) {
  2192. var result = optionalTarget || new THREE.Vector3();
  2193. return result.subVectors( this.max, this.min );
  2194. },
  2195. expandByPoint: function ( point ) {
  2196. this.min.min( point );
  2197. this.max.max( point );
  2198. return this;
  2199. },
  2200. expandByVector: function ( vector ) {
  2201. this.min.sub( vector );
  2202. this.max.add( vector );
  2203. return this;
  2204. },
  2205. expandByScalar: function ( scalar ) {
  2206. this.min.addScalar( -scalar );
  2207. this.max.addScalar( scalar );
  2208. return this;
  2209. },
  2210. containsPoint: function ( point ) {
  2211. if ( point.x < this.min.x || point.x > this.max.x ||
  2212. point.y < this.min.y || point.y > this.max.y ||
  2213. point.z < this.min.z || point.z > this.max.z ) {
  2214. return false;
  2215. }
  2216. return true;
  2217. },
  2218. containsBox: function ( box ) {
  2219. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2220. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2221. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2222. return true;
  2223. }
  2224. return false;
  2225. },
  2226. getParameter: function ( point, optionalTarget ) {
  2227. // This can potentially have a divide by zero if the box
  2228. // has a size dimension of 0.
  2229. var result = optionalTarget || new THREE.Vector3();
  2230. return result.set(
  2231. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2232. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2233. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2234. );
  2235. },
  2236. isIntersectionBox: function ( box ) {
  2237. // using 6 splitting planes to rule out intersections.
  2238. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2239. box.max.y < this.min.y || box.min.y > this.max.y ||
  2240. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2241. return false;
  2242. }
  2243. return true;
  2244. },
  2245. clampPoint: function ( point, optionalTarget ) {
  2246. var result = optionalTarget || new THREE.Vector3();
  2247. return result.copy( point ).clamp( this.min, this.max );
  2248. },
  2249. distanceToPoint: function() {
  2250. var v1 = new THREE.Vector3();
  2251. return function ( point ) {
  2252. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2253. return clampedPoint.sub( point ).length();
  2254. };
  2255. }(),
  2256. getBoundingSphere: function() {
  2257. var v1 = new THREE.Vector3();
  2258. return function ( optionalTarget ) {
  2259. var result = optionalTarget || new THREE.Sphere();
  2260. result.center = this.center();
  2261. result.radius = this.size( v1 ).length() * 0.5;
  2262. return result;
  2263. };
  2264. }(),
  2265. intersect: function ( box ) {
  2266. this.min.max( box.min );
  2267. this.max.min( box.max );
  2268. return this;
  2269. },
  2270. union: function ( box ) {
  2271. this.min.min( box.min );
  2272. this.max.max( box.max );
  2273. return this;
  2274. },
  2275. applyMatrix4: function() {
  2276. var points = [
  2277. new THREE.Vector3(),
  2278. new THREE.Vector3(),
  2279. new THREE.Vector3(),
  2280. new THREE.Vector3(),
  2281. new THREE.Vector3(),
  2282. new THREE.Vector3(),
  2283. new THREE.Vector3(),
  2284. new THREE.Vector3()
  2285. ];
  2286. return function ( matrix ) {
  2287. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2288. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2289. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2290. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2291. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2292. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2293. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2294. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2295. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2296. this.makeEmpty();
  2297. this.setFromPoints( points );
  2298. return this;
  2299. };
  2300. }(),
  2301. translate: function ( offset ) {
  2302. this.min.add( offset );
  2303. this.max.add( offset );
  2304. return this;
  2305. },
  2306. equals: function ( box ) {
  2307. return box.min.equals( this.min ) && box.max.equals( this.max );
  2308. },
  2309. clone: function () {
  2310. return new THREE.Box3().copy( this );
  2311. }
  2312. };
  2313. /**
  2314. * @author alteredq / http://alteredqualia.com/
  2315. * @author WestLangley / http://github.com/WestLangley
  2316. * @author bhouston / http://exocortex.com
  2317. */
  2318. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2319. this.elements = new Float32Array(9);
  2320. this.set(
  2321. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2322. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2323. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2324. );
  2325. };
  2326. THREE.Matrix3.prototype = {
  2327. constructor: THREE.Matrix3,
  2328. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2329. var te = this.elements;
  2330. te[0] = n11; te[3] = n12; te[6] = n13;
  2331. te[1] = n21; te[4] = n22; te[7] = n23;
  2332. te[2] = n31; te[5] = n32; te[8] = n33;
  2333. return this;
  2334. },
  2335. identity: function () {
  2336. this.set(
  2337. 1, 0, 0,
  2338. 0, 1, 0,
  2339. 0, 0, 1
  2340. );
  2341. return this;
  2342. },
  2343. copy: function ( m ) {
  2344. var me = m.elements;
  2345. this.set(
  2346. me[0], me[3], me[6],
  2347. me[1], me[4], me[7],
  2348. me[2], me[5], me[8]
  2349. );
  2350. return this;
  2351. },
  2352. multiplyVector3: function ( vector ) {
  2353. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2354. return vector.applyMatrix3( this );
  2355. },
  2356. multiplyVector3Array: function ( a ) {
  2357. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2358. return this.applyToVector3Array( a );
  2359. },
  2360. applyToVector3Array: function() {
  2361. var v1 = new THREE.Vector3();
  2362. return function ( a ) {
  2363. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2364. v1.x = a[ i ];
  2365. v1.y = a[ i + 1 ];
  2366. v1.z = a[ i + 2 ];
  2367. v1.applyMatrix3( this );
  2368. a[ i ] = v1.x;
  2369. a[ i + 1 ] = v1.y;
  2370. a[ i + 2 ] = v1.z;
  2371. }
  2372. return a;
  2373. };
  2374. }(),
  2375. multiplyScalar: function ( s ) {
  2376. var te = this.elements;
  2377. te[0] *= s; te[3] *= s; te[6] *= s;
  2378. te[1] *= s; te[4] *= s; te[7] *= s;
  2379. te[2] *= s; te[5] *= s; te[8] *= s;
  2380. return this;
  2381. },
  2382. determinant: function () {
  2383. var te = this.elements;
  2384. var a = te[0], b = te[1], c = te[2],
  2385. d = te[3], e = te[4], f = te[5],
  2386. g = te[6], h = te[7], i = te[8];
  2387. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2388. },
  2389. getInverse: function ( matrix, throwOnInvertible ) {
  2390. // input: THREE.Matrix4
  2391. // ( based on http://code.google.com/p/webgl-mjs/ )
  2392. var me = matrix.elements;
  2393. var te = this.elements;
  2394. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2395. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2396. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2397. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2398. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2399. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2400. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2401. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2402. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2403. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2404. // no inverse
  2405. if ( det === 0 ) {
  2406. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2407. if ( throwOnInvertible || false ) {
  2408. throw new Error( msg );
  2409. } else {
  2410. console.warn( msg );
  2411. }
  2412. this.identity();
  2413. return this;
  2414. }
  2415. this.multiplyScalar( 1.0 / det );
  2416. return this;
  2417. },
  2418. transpose: function () {
  2419. var tmp, m = this.elements;
  2420. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2421. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2422. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2423. return this;
  2424. },
  2425. getNormalMatrix: function ( m ) {
  2426. // input: THREE.Matrix4
  2427. this.getInverse( m ).transpose();
  2428. return this;
  2429. },
  2430. transposeIntoArray: function ( r ) {
  2431. var m = this.elements;
  2432. r[ 0 ] = m[ 0 ];
  2433. r[ 1 ] = m[ 3 ];
  2434. r[ 2 ] = m[ 6 ];
  2435. r[ 3 ] = m[ 1 ];
  2436. r[ 4 ] = m[ 4 ];
  2437. r[ 5 ] = m[ 7 ];
  2438. r[ 6 ] = m[ 2 ];
  2439. r[ 7 ] = m[ 5 ];
  2440. r[ 8 ] = m[ 8 ];
  2441. return this;
  2442. },
  2443. fromArray: function ( array ) {
  2444. this.elements.set( array );
  2445. return this;
  2446. },
  2447. toArray: function () {
  2448. var te = this.elements;
  2449. return [
  2450. te[ 0 ], te[ 1 ], te[ 2 ],
  2451. te[ 3 ], te[ 4 ], te[ 5 ],
  2452. te[ 6 ], te[ 7 ], te[ 8 ]
  2453. ];
  2454. },
  2455. clone: function () {
  2456. var te = this.elements;
  2457. return new THREE.Matrix3(
  2458. te[0], te[3], te[6],
  2459. te[1], te[4], te[7],
  2460. te[2], te[5], te[8]
  2461. );
  2462. }
  2463. };
  2464. /**
  2465. * @author mrdoob / http://mrdoob.com/
  2466. * @author supereggbert / http://www.paulbrunt.co.uk/
  2467. * @author philogb / http://blog.thejit.org/
  2468. * @author jordi_ros / http://plattsoft.com
  2469. * @author D1plo1d / http://github.com/D1plo1d
  2470. * @author alteredq / http://alteredqualia.com/
  2471. * @author mikael emtinger / http://gomo.se/
  2472. * @author timknip / http://www.floorplanner.com/
  2473. * @author bhouston / http://exocortex.com
  2474. * @author WestLangley / http://github.com/WestLangley
  2475. */
  2476. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2477. this.elements = new Float32Array( 16 );
  2478. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2479. // we should not support semi specification of Matrix4, it is just weird.
  2480. var te = this.elements;
  2481. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2482. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2483. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2484. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2485. };
  2486. THREE.Matrix4.prototype = {
  2487. constructor: THREE.Matrix4,
  2488. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2489. var te = this.elements;
  2490. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2491. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2492. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2493. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2494. return this;
  2495. },
  2496. identity: function () {
  2497. this.set(
  2498. 1, 0, 0, 0,
  2499. 0, 1, 0, 0,
  2500. 0, 0, 1, 0,
  2501. 0, 0, 0, 1
  2502. );
  2503. return this;
  2504. },
  2505. copy: function ( m ) {
  2506. this.elements.set( m.elements );
  2507. return this;
  2508. },
  2509. extractPosition: function ( m ) {
  2510. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2511. return this.copyPosition( m );
  2512. },
  2513. copyPosition: function ( m ) {
  2514. var te = this.elements;
  2515. var me = m.elements;
  2516. te[12] = me[12];
  2517. te[13] = me[13];
  2518. te[14] = me[14];
  2519. return this;
  2520. },
  2521. extractRotation: function () {
  2522. var v1 = new THREE.Vector3();
  2523. return function ( m ) {
  2524. var te = this.elements;
  2525. var me = m.elements;
  2526. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2527. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2528. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2529. te[0] = me[0] * scaleX;
  2530. te[1] = me[1] * scaleX;
  2531. te[2] = me[2] * scaleX;
  2532. te[4] = me[4] * scaleY;
  2533. te[5] = me[5] * scaleY;
  2534. te[6] = me[6] * scaleY;
  2535. te[8] = me[8] * scaleZ;
  2536. te[9] = me[9] * scaleZ;
  2537. te[10] = me[10] * scaleZ;
  2538. return this;
  2539. };
  2540. }(),
  2541. makeRotationFromEuler: function ( euler ) {
  2542. if ( euler instanceof THREE.Euler === false ) {
  2543. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2544. }
  2545. var te = this.elements;
  2546. var x = euler.x, y = euler.y, z = euler.z;
  2547. var a = Math.cos( x ), b = Math.sin( x );
  2548. var c = Math.cos( y ), d = Math.sin( y );
  2549. var e = Math.cos( z ), f = Math.sin( z );
  2550. if ( euler.order === 'XYZ' ) {
  2551. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2552. te[0] = c * e;
  2553. te[4] = - c * f;
  2554. te[8] = d;
  2555. te[1] = af + be * d;
  2556. te[5] = ae - bf * d;
  2557. te[9] = - b * c;
  2558. te[2] = bf - ae * d;
  2559. te[6] = be + af * d;
  2560. te[10] = a * c;
  2561. } else if ( euler.order === 'YXZ' ) {
  2562. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2563. te[0] = ce + df * b;
  2564. te[4] = de * b - cf;
  2565. te[8] = a * d;
  2566. te[1] = a * f;
  2567. te[5] = a * e;
  2568. te[9] = - b;
  2569. te[2] = cf * b - de;
  2570. te[6] = df + ce * b;
  2571. te[10] = a * c;
  2572. } else if ( euler.order === 'ZXY' ) {
  2573. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2574. te[0] = ce - df * b;
  2575. te[4] = - a * f;
  2576. te[8] = de + cf * b;
  2577. te[1] = cf + de * b;
  2578. te[5] = a * e;
  2579. te[9] = df - ce * b;
  2580. te[2] = - a * d;
  2581. te[6] = b;
  2582. te[10] = a * c;
  2583. } else if ( euler.order === 'ZYX' ) {
  2584. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2585. te[0] = c * e;
  2586. te[4] = be * d - af;
  2587. te[8] = ae * d + bf;
  2588. te[1] = c * f;
  2589. te[5] = bf * d + ae;
  2590. te[9] = af * d - be;
  2591. te[2] = - d;
  2592. te[6] = b * c;
  2593. te[10] = a * c;
  2594. } else if ( euler.order === 'YZX' ) {
  2595. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2596. te[0] = c * e;
  2597. te[4] = bd - ac * f;
  2598. te[8] = bc * f + ad;
  2599. te[1] = f;
  2600. te[5] = a * e;
  2601. te[9] = - b * e;
  2602. te[2] = - d * e;
  2603. te[6] = ad * f + bc;
  2604. te[10] = ac - bd * f;
  2605. } else if ( euler.order === 'XZY' ) {
  2606. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2607. te[0] = c * e;
  2608. te[4] = - f;
  2609. te[8] = d * e;
  2610. te[1] = ac * f + bd;
  2611. te[5] = a * e;
  2612. te[9] = ad * f - bc;
  2613. te[2] = bc * f - ad;
  2614. te[6] = b * e;
  2615. te[10] = bd * f + ac;
  2616. }
  2617. // last column
  2618. te[3] = 0;
  2619. te[7] = 0;
  2620. te[11] = 0;
  2621. // bottom row
  2622. te[12] = 0;
  2623. te[13] = 0;
  2624. te[14] = 0;
  2625. te[15] = 1;
  2626. return this;
  2627. },
  2628. setRotationFromQuaternion: function ( q ) {
  2629. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2630. return this.makeRotationFromQuaternion( q );
  2631. },
  2632. makeRotationFromQuaternion: function ( q ) {
  2633. var te = this.elements;
  2634. var x = q.x, y = q.y, z = q.z, w = q.w;
  2635. var x2 = x + x, y2 = y + y, z2 = z + z;
  2636. var xx = x * x2, xy = x * y2, xz = x * z2;
  2637. var yy = y * y2, yz = y * z2, zz = z * z2;
  2638. var wx = w * x2, wy = w * y2, wz = w * z2;
  2639. te[0] = 1 - ( yy + zz );
  2640. te[4] = xy - wz;
  2641. te[8] = xz + wy;
  2642. te[1] = xy + wz;
  2643. te[5] = 1 - ( xx + zz );
  2644. te[9] = yz - wx;
  2645. te[2] = xz - wy;
  2646. te[6] = yz + wx;
  2647. te[10] = 1 - ( xx + yy );
  2648. // last column
  2649. te[3] = 0;
  2650. te[7] = 0;
  2651. te[11] = 0;
  2652. // bottom row
  2653. te[12] = 0;
  2654. te[13] = 0;
  2655. te[14] = 0;
  2656. te[15] = 1;
  2657. return this;
  2658. },
  2659. lookAt: function() {
  2660. var x = new THREE.Vector3();
  2661. var y = new THREE.Vector3();
  2662. var z = new THREE.Vector3();
  2663. return function ( eye, target, up ) {
  2664. var te = this.elements;
  2665. z.subVectors( eye, target ).normalize();
  2666. if ( z.length() === 0 ) {
  2667. z.z = 1;
  2668. }
  2669. x.crossVectors( up, z ).normalize();
  2670. if ( x.length() === 0 ) {
  2671. z.x += 0.0001;
  2672. x.crossVectors( up, z ).normalize();
  2673. }
  2674. y.crossVectors( z, x );
  2675. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2676. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2677. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2678. return this;
  2679. };
  2680. }(),
  2681. multiply: function ( m, n ) {
  2682. if ( n !== undefined ) {
  2683. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2684. return this.multiplyMatrices( m, n );
  2685. }
  2686. return this.multiplyMatrices( this, m );
  2687. },
  2688. multiplyMatrices: function ( a, b ) {
  2689. var ae = a.elements;
  2690. var be = b.elements;
  2691. var te = this.elements;
  2692. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2693. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2694. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2695. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2696. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2697. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2698. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2699. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2700. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2701. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2702. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2703. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2704. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2705. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2706. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2707. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2708. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2709. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2710. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2711. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2712. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2713. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2714. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2715. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2716. return this;
  2717. },
  2718. multiplyToArray: function ( a, b, r ) {
  2719. var te = this.elements;
  2720. this.multiplyMatrices( a, b );
  2721. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2722. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2723. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2724. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2725. return this;
  2726. },
  2727. multiplyScalar: function ( s ) {
  2728. var te = this.elements;
  2729. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2730. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2731. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2732. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2733. return this;
  2734. },
  2735. multiplyVector3: function ( vector ) {
  2736. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2737. return vector.applyProjection( this );
  2738. },
  2739. multiplyVector4: function ( vector ) {
  2740. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2741. return vector.applyMatrix4( this );
  2742. },
  2743. multiplyVector3Array: function ( a ) {
  2744. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2745. return this.applyToVector3Array( a );
  2746. },
  2747. applyToVector3Array: function() {
  2748. var v1 = new THREE.Vector3();
  2749. return function ( a ) {
  2750. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2751. v1.x = a[ i ];
  2752. v1.y = a[ i + 1 ];
  2753. v1.z = a[ i + 2 ];
  2754. v1.applyMatrix4( this );
  2755. a[ i ] = v1.x;
  2756. a[ i + 1 ] = v1.y;
  2757. a[ i + 2 ] = v1.z;
  2758. }
  2759. return a;
  2760. };
  2761. }(),
  2762. rotateAxis: function ( v ) {
  2763. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2764. v.transformDirection( this );
  2765. },
  2766. crossVector: function ( vector ) {
  2767. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2768. return vector.applyMatrix4( this );
  2769. },
  2770. determinant: function () {
  2771. var te = this.elements;
  2772. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2773. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2774. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2775. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2776. //TODO: make this more efficient
  2777. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2778. return (
  2779. n41 * (
  2780. +n14 * n23 * n32
  2781. -n13 * n24 * n32
  2782. -n14 * n22 * n33
  2783. +n12 * n24 * n33
  2784. +n13 * n22 * n34
  2785. -n12 * n23 * n34
  2786. ) +
  2787. n42 * (
  2788. +n11 * n23 * n34
  2789. -n11 * n24 * n33
  2790. +n14 * n21 * n33
  2791. -n13 * n21 * n34
  2792. +n13 * n24 * n31
  2793. -n14 * n23 * n31
  2794. ) +
  2795. n43 * (
  2796. +n11 * n24 * n32
  2797. -n11 * n22 * n34
  2798. -n14 * n21 * n32
  2799. +n12 * n21 * n34
  2800. +n14 * n22 * n31
  2801. -n12 * n24 * n31
  2802. ) +
  2803. n44 * (
  2804. -n13 * n22 * n31
  2805. -n11 * n23 * n32
  2806. +n11 * n22 * n33
  2807. +n13 * n21 * n32
  2808. -n12 * n21 * n33
  2809. +n12 * n23 * n31
  2810. )
  2811. );
  2812. },
  2813. transpose: function () {
  2814. var te = this.elements;
  2815. var tmp;
  2816. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2817. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2818. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2819. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2820. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2821. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2822. return this;
  2823. },
  2824. flattenToArray: function ( flat ) {
  2825. var te = this.elements;
  2826. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2827. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2828. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2829. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2830. return flat;
  2831. },
  2832. flattenToArrayOffset: function( flat, offset ) {
  2833. var te = this.elements;
  2834. flat[ offset ] = te[0];
  2835. flat[ offset + 1 ] = te[1];
  2836. flat[ offset + 2 ] = te[2];
  2837. flat[ offset + 3 ] = te[3];
  2838. flat[ offset + 4 ] = te[4];
  2839. flat[ offset + 5 ] = te[5];
  2840. flat[ offset + 6 ] = te[6];
  2841. flat[ offset + 7 ] = te[7];
  2842. flat[ offset + 8 ] = te[8];
  2843. flat[ offset + 9 ] = te[9];
  2844. flat[ offset + 10 ] = te[10];
  2845. flat[ offset + 11 ] = te[11];
  2846. flat[ offset + 12 ] = te[12];
  2847. flat[ offset + 13 ] = te[13];
  2848. flat[ offset + 14 ] = te[14];
  2849. flat[ offset + 15 ] = te[15];
  2850. return flat;
  2851. },
  2852. getPosition: function() {
  2853. var v1 = new THREE.Vector3();
  2854. return function () {
  2855. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2856. var te = this.elements;
  2857. return v1.set( te[12], te[13], te[14] );
  2858. };
  2859. }(),
  2860. setPosition: function ( v ) {
  2861. var te = this.elements;
  2862. te[12] = v.x;
  2863. te[13] = v.y;
  2864. te[14] = v.z;
  2865. return this;
  2866. },
  2867. getInverse: function ( m, throwOnInvertible ) {
  2868. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2869. var te = this.elements;
  2870. var me = m.elements;
  2871. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2872. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2873. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2874. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2875. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2876. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2877. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2878. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2879. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2880. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2881. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2882. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2883. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2884. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2885. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2886. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2887. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2888. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2889. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2890. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2891. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2892. if ( det == 0 ) {
  2893. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2894. if ( throwOnInvertible || false ) {
  2895. throw new Error( msg );
  2896. } else {
  2897. console.warn( msg );
  2898. }
  2899. this.identity();
  2900. return this;
  2901. }
  2902. this.multiplyScalar( 1 / det );
  2903. return this;
  2904. },
  2905. translate: function ( v ) {
  2906. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2907. },
  2908. rotateX: function ( angle ) {
  2909. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2910. },
  2911. rotateY: function ( angle ) {
  2912. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2913. },
  2914. rotateZ: function ( angle ) {
  2915. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2916. },
  2917. rotateByAxis: function ( axis, angle ) {
  2918. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2919. },
  2920. scale: function ( v ) {
  2921. var te = this.elements;
  2922. var x = v.x, y = v.y, z = v.z;
  2923. te[0] *= x; te[4] *= y; te[8] *= z;
  2924. te[1] *= x; te[5] *= y; te[9] *= z;
  2925. te[2] *= x; te[6] *= y; te[10] *= z;
  2926. te[3] *= x; te[7] *= y; te[11] *= z;
  2927. return this;
  2928. },
  2929. getMaxScaleOnAxis: function () {
  2930. var te = this.elements;
  2931. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2932. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2933. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2934. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2935. },
  2936. makeTranslation: function ( x, y, z ) {
  2937. this.set(
  2938. 1, 0, 0, x,
  2939. 0, 1, 0, y,
  2940. 0, 0, 1, z,
  2941. 0, 0, 0, 1
  2942. );
  2943. return this;
  2944. },
  2945. makeRotationX: function ( theta ) {
  2946. var c = Math.cos( theta ), s = Math.sin( theta );
  2947. this.set(
  2948. 1, 0, 0, 0,
  2949. 0, c, -s, 0,
  2950. 0, s, c, 0,
  2951. 0, 0, 0, 1
  2952. );
  2953. return this;
  2954. },
  2955. makeRotationY: function ( theta ) {
  2956. var c = Math.cos( theta ), s = Math.sin( theta );
  2957. this.set(
  2958. c, 0, s, 0,
  2959. 0, 1, 0, 0,
  2960. -s, 0, c, 0,
  2961. 0, 0, 0, 1
  2962. );
  2963. return this;
  2964. },
  2965. makeRotationZ: function ( theta ) {
  2966. var c = Math.cos( theta ), s = Math.sin( theta );
  2967. this.set(
  2968. c, -s, 0, 0,
  2969. s, c, 0, 0,
  2970. 0, 0, 1, 0,
  2971. 0, 0, 0, 1
  2972. );
  2973. return this;
  2974. },
  2975. makeRotationAxis: function ( axis, angle ) {
  2976. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2977. var c = Math.cos( angle );
  2978. var s = Math.sin( angle );
  2979. var t = 1 - c;
  2980. var x = axis.x, y = axis.y, z = axis.z;
  2981. var tx = t * x, ty = t * y;
  2982. this.set(
  2983. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2984. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2985. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2986. 0, 0, 0, 1
  2987. );
  2988. return this;
  2989. },
  2990. makeScale: function ( x, y, z ) {
  2991. this.set(
  2992. x, 0, 0, 0,
  2993. 0, y, 0, 0,
  2994. 0, 0, z, 0,
  2995. 0, 0, 0, 1
  2996. );
  2997. return this;
  2998. },
  2999. compose: function ( position, quaternion, scale ) {
  3000. this.makeRotationFromQuaternion( quaternion );
  3001. this.scale( scale );
  3002. this.setPosition( position );
  3003. return this;
  3004. },
  3005. decompose: function () {
  3006. var vector = new THREE.Vector3();
  3007. var matrix = new THREE.Matrix4();
  3008. return function ( position, quaternion, scale ) {
  3009. var te = this.elements;
  3010. var sx = vector.set( te[0], te[1], te[2] ).length();
  3011. var sy = vector.set( te[4], te[5], te[6] ).length();
  3012. var sz = vector.set( te[8], te[9], te[10] ).length();
  3013. // if determine is negative, we need to invert one scale
  3014. var det = this.determinant();
  3015. if( det < 0 ) {
  3016. sx = -sx;
  3017. }
  3018. position.x = te[12];
  3019. position.y = te[13];
  3020. position.z = te[14];
  3021. // scale the rotation part
  3022. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3023. var invSX = 1 / sx;
  3024. var invSY = 1 / sy;
  3025. var invSZ = 1 / sz;
  3026. matrix.elements[0] *= invSX;
  3027. matrix.elements[1] *= invSX;
  3028. matrix.elements[2] *= invSX;
  3029. matrix.elements[4] *= invSY;
  3030. matrix.elements[5] *= invSY;
  3031. matrix.elements[6] *= invSY;
  3032. matrix.elements[8] *= invSZ;
  3033. matrix.elements[9] *= invSZ;
  3034. matrix.elements[10] *= invSZ;
  3035. quaternion.setFromRotationMatrix( matrix );
  3036. scale.x = sx;
  3037. scale.y = sy;
  3038. scale.z = sz;
  3039. return this;
  3040. };
  3041. }(),
  3042. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3043. var te = this.elements;
  3044. var x = 2 * near / ( right - left );
  3045. var y = 2 * near / ( top - bottom );
  3046. var a = ( right + left ) / ( right - left );
  3047. var b = ( top + bottom ) / ( top - bottom );
  3048. var c = - ( far + near ) / ( far - near );
  3049. var d = - 2 * far * near / ( far - near );
  3050. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  3051. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  3052. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  3053. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  3054. return this;
  3055. },
  3056. makePerspective: function ( fov, aspect, near, far ) {
  3057. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3058. var ymin = - ymax;
  3059. var xmin = ymin * aspect;
  3060. var xmax = ymax * aspect;
  3061. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3062. },
  3063. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3064. var te = this.elements;
  3065. var w = right - left;
  3066. var h = top - bottom;
  3067. var p = far - near;
  3068. var x = ( right + left ) / w;
  3069. var y = ( top + bottom ) / h;
  3070. var z = ( far + near ) / p;
  3071. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  3072. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  3073. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  3074. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  3075. return this;
  3076. },
  3077. fromArray: function ( array ) {
  3078. this.elements.set( array );
  3079. return this;
  3080. },
  3081. toArray: function () {
  3082. var te = this.elements;
  3083. return [
  3084. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3085. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3086. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3087. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3088. ];
  3089. },
  3090. clone: function () {
  3091. var te = this.elements;
  3092. return new THREE.Matrix4(
  3093. te[0], te[4], te[8], te[12],
  3094. te[1], te[5], te[9], te[13],
  3095. te[2], te[6], te[10], te[14],
  3096. te[3], te[7], te[11], te[15]
  3097. );
  3098. }
  3099. };
  3100. /**
  3101. * @author bhouston / http://exocortex.com
  3102. */
  3103. THREE.Ray = function ( origin, direction ) {
  3104. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3105. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3106. };
  3107. THREE.Ray.prototype = {
  3108. constructor: THREE.Ray,
  3109. set: function ( origin, direction ) {
  3110. this.origin.copy( origin );
  3111. this.direction.copy( direction );
  3112. return this;
  3113. },
  3114. copy: function ( ray ) {
  3115. this.origin.copy( ray.origin );
  3116. this.direction.copy( ray.direction );
  3117. return this;
  3118. },
  3119. at: function ( t, optionalTarget ) {
  3120. var result = optionalTarget || new THREE.Vector3();
  3121. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3122. },
  3123. recast: function () {
  3124. var v1 = new THREE.Vector3();
  3125. return function ( t ) {
  3126. this.origin.copy( this.at( t, v1 ) );
  3127. return this;
  3128. };
  3129. }(),
  3130. closestPointToPoint: function ( point, optionalTarget ) {
  3131. var result = optionalTarget || new THREE.Vector3();
  3132. result.subVectors( point, this.origin );
  3133. var directionDistance = result.dot( this.direction );
  3134. if ( directionDistance < 0 ) {
  3135. return result.copy( this.origin );
  3136. }
  3137. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3138. },
  3139. distanceToPoint: function () {
  3140. var v1 = new THREE.Vector3();
  3141. return function ( point ) {
  3142. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3143. // point behind the ray
  3144. if ( directionDistance < 0 ) {
  3145. return this.origin.distanceTo( point );
  3146. }
  3147. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3148. return v1.distanceTo( point );
  3149. };
  3150. }(),
  3151. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3152. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3153. // It returns the min distance between the ray and the segment
  3154. // defined by v0 and v1
  3155. // It can also set two optional targets :
  3156. // - The closest point on the ray
  3157. // - The closest point on the segment
  3158. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3159. var segDir = v1.clone().sub( v0 ).normalize();
  3160. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3161. var diff = this.origin.clone().sub( segCenter );
  3162. var a01 = - this.direction.dot( segDir );
  3163. var b0 = diff.dot( this.direction );
  3164. var b1 = - diff.dot( segDir );
  3165. var c = diff.lengthSq();
  3166. var det = Math.abs( 1 - a01 * a01 );
  3167. var s0, s1, sqrDist, extDet;
  3168. if ( det >= 0 ) {
  3169. // The ray and segment are not parallel.
  3170. s0 = a01 * b1 - b0;
  3171. s1 = a01 * b0 - b1;
  3172. extDet = segExtent * det;
  3173. if ( s0 >= 0 ) {
  3174. if ( s1 >= - extDet ) {
  3175. if ( s1 <= extDet ) {
  3176. // region 0
  3177. // Minimum at interior points of ray and segment.
  3178. var invDet = 1 / det;
  3179. s0 *= invDet;
  3180. s1 *= invDet;
  3181. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3182. } else {
  3183. // region 1
  3184. s1 = segExtent;
  3185. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3186. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3187. }
  3188. } else {
  3189. // region 5
  3190. s1 = - segExtent;
  3191. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3192. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3193. }
  3194. } else {
  3195. if ( s1 <= - extDet) {
  3196. // region 4
  3197. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3198. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3199. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3200. } else if ( s1 <= extDet ) {
  3201. // region 3
  3202. s0 = 0;
  3203. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3204. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3205. } else {
  3206. // region 2
  3207. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3208. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3209. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3210. }
  3211. }
  3212. } else {
  3213. // Ray and segment are parallel.
  3214. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3215. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3216. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3217. }
  3218. if ( optionalPointOnRay ) {
  3219. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3220. }
  3221. if ( optionalPointOnSegment ) {
  3222. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3223. }
  3224. return sqrDist;
  3225. },
  3226. isIntersectionSphere: function ( sphere ) {
  3227. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3228. },
  3229. isIntersectionPlane: function ( plane ) {
  3230. // check if the ray lies on the plane first
  3231. var distToPoint = plane.distanceToPoint( this.origin );
  3232. if ( distToPoint === 0 ) {
  3233. return true;
  3234. }
  3235. var denominator = plane.normal.dot( this.direction );
  3236. if ( denominator * distToPoint < 0 ) {
  3237. return true
  3238. }
  3239. // ray origin is behind the plane (and is pointing behind it)
  3240. return false;
  3241. },
  3242. distanceToPlane: function ( plane ) {
  3243. var denominator = plane.normal.dot( this.direction );
  3244. if ( denominator == 0 ) {
  3245. // line is coplanar, return origin
  3246. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3247. return 0;
  3248. }
  3249. // Null is preferable to undefined since undefined means.... it is undefined
  3250. return null;
  3251. }
  3252. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3253. // Return if the ray never intersects the plane
  3254. return t >= 0 ? t : null;
  3255. },
  3256. intersectPlane: function ( plane, optionalTarget ) {
  3257. var t = this.distanceToPlane( plane );
  3258. if ( t === null ) {
  3259. return null;
  3260. }
  3261. return this.at( t, optionalTarget );
  3262. },
  3263. isIntersectionBox: function () {
  3264. var v = new THREE.Vector3();
  3265. return function ( box ) {
  3266. return this.intersectBox( box, v ) !== null;
  3267. }
  3268. }(),
  3269. intersectBox: function ( box , optionalTarget ) {
  3270. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3271. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3272. var invdirx = 1/this.direction.x,
  3273. invdiry = 1/this.direction.y,
  3274. invdirz = 1/this.direction.z;
  3275. var origin = this.origin;
  3276. if (invdirx >= 0) {
  3277. tmin = (box.min.x - origin.x) * invdirx;
  3278. tmax = (box.max.x - origin.x) * invdirx;
  3279. } else {
  3280. tmin = (box.max.x - origin.x) * invdirx;
  3281. tmax = (box.min.x - origin.x) * invdirx;
  3282. }
  3283. if (invdiry >= 0) {
  3284. tymin = (box.min.y - origin.y) * invdiry;
  3285. tymax = (box.max.y - origin.y) * invdiry;
  3286. } else {
  3287. tymin = (box.max.y - origin.y) * invdiry;
  3288. tymax = (box.min.y - origin.y) * invdiry;
  3289. }
  3290. if ((tmin > tymax) || (tymin > tmax)) return null;
  3291. // These lines also handle the case where tmin or tmax is NaN
  3292. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3293. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3294. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3295. if (invdirz >= 0) {
  3296. tzmin = (box.min.z - origin.z) * invdirz;
  3297. tzmax = (box.max.z - origin.z) * invdirz;
  3298. } else {
  3299. tzmin = (box.max.z - origin.z) * invdirz;
  3300. tzmax = (box.min.z - origin.z) * invdirz;
  3301. }
  3302. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3303. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3304. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3305. //return point closest to the ray (positive side)
  3306. if ( tmax < 0 ) return null;
  3307. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3308. },
  3309. intersectTriangle: function() {
  3310. // Compute the offset origin, edges, and normal.
  3311. var diff = new THREE.Vector3();
  3312. var edge1 = new THREE.Vector3();
  3313. var edge2 = new THREE.Vector3();
  3314. var normal = new THREE.Vector3();
  3315. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3316. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3317. edge1.subVectors( b, a );
  3318. edge2.subVectors( c, a );
  3319. normal.crossVectors( edge1, edge2 );
  3320. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3321. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3322. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3323. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3324. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3325. var DdN = this.direction.dot( normal );
  3326. var sign;
  3327. if ( DdN > 0 ) {
  3328. if ( backfaceCulling ) return null;
  3329. sign = 1;
  3330. } else if ( DdN < 0 ) {
  3331. sign = - 1;
  3332. DdN = - DdN;
  3333. } else {
  3334. return null;
  3335. }
  3336. diff.subVectors( this.origin, a );
  3337. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3338. // b1 < 0, no intersection
  3339. if ( DdQxE2 < 0 ) {
  3340. return null;
  3341. }
  3342. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3343. // b2 < 0, no intersection
  3344. if ( DdE1xQ < 0 ) {
  3345. return null;
  3346. }
  3347. // b1+b2 > 1, no intersection
  3348. if ( DdQxE2 + DdE1xQ > DdN ) {
  3349. return null;
  3350. }
  3351. // Line intersects triangle, check if ray does.
  3352. var QdN = - sign * diff.dot( normal );
  3353. // t < 0, no intersection
  3354. if ( QdN < 0 ) {
  3355. return null;
  3356. }
  3357. // Ray intersects triangle.
  3358. return this.at( QdN / DdN, optionalTarget );
  3359. }
  3360. }(),
  3361. applyMatrix4: function ( matrix4 ) {
  3362. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3363. this.origin.applyMatrix4( matrix4 );
  3364. this.direction.sub( this.origin );
  3365. this.direction.normalize();
  3366. return this;
  3367. },
  3368. equals: function ( ray ) {
  3369. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3370. },
  3371. clone: function () {
  3372. return new THREE.Ray().copy( this );
  3373. }
  3374. };
  3375. /**
  3376. * @author bhouston / http://exocortex.com
  3377. * @author mrdoob / http://mrdoob.com/
  3378. */
  3379. THREE.Sphere = function ( center, radius ) {
  3380. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3381. this.radius = ( radius !== undefined ) ? radius : 0;
  3382. };
  3383. THREE.Sphere.prototype = {
  3384. constructor: THREE.Sphere,
  3385. set: function ( center, radius ) {
  3386. this.center.copy( center );
  3387. this.radius = radius;
  3388. return this;
  3389. },
  3390. setFromPoints: function () {
  3391. var box = new THREE.Box3();
  3392. return function ( points, optionalCenter ) {
  3393. var center = this.center;
  3394. if ( optionalCenter !== undefined ) {
  3395. center.copy( optionalCenter );
  3396. } else {
  3397. box.setFromPoints( points ).center( center );
  3398. }
  3399. var maxRadiusSq = 0;
  3400. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3401. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3402. }
  3403. this.radius = Math.sqrt( maxRadiusSq );
  3404. return this;
  3405. };
  3406. }(),
  3407. copy: function ( sphere ) {
  3408. this.center.copy( sphere.center );
  3409. this.radius = sphere.radius;
  3410. return this;
  3411. },
  3412. empty: function () {
  3413. return ( this.radius <= 0 );
  3414. },
  3415. containsPoint: function ( point ) {
  3416. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3417. },
  3418. distanceToPoint: function ( point ) {
  3419. return ( point.distanceTo( this.center ) - this.radius );
  3420. },
  3421. intersectsSphere: function ( sphere ) {
  3422. var radiusSum = this.radius + sphere.radius;
  3423. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3424. },
  3425. clampPoint: function ( point, optionalTarget ) {
  3426. var deltaLengthSq = this.center.distanceToSquared( point );
  3427. var result = optionalTarget || new THREE.Vector3();
  3428. result.copy( point );
  3429. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3430. result.sub( this.center ).normalize();
  3431. result.multiplyScalar( this.radius ).add( this.center );
  3432. }
  3433. return result;
  3434. },
  3435. getBoundingBox: function ( optionalTarget ) {
  3436. var box = optionalTarget || new THREE.Box3();
  3437. box.set( this.center, this.center );
  3438. box.expandByScalar( this.radius );
  3439. return box;
  3440. },
  3441. applyMatrix4: function ( matrix ) {
  3442. this.center.applyMatrix4( matrix );
  3443. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3444. return this;
  3445. },
  3446. translate: function ( offset ) {
  3447. this.center.add( offset );
  3448. return this;
  3449. },
  3450. equals: function ( sphere ) {
  3451. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3452. },
  3453. clone: function () {
  3454. return new THREE.Sphere().copy( this );
  3455. }
  3456. };
  3457. /**
  3458. * @author mrdoob / http://mrdoob.com/
  3459. * @author alteredq / http://alteredqualia.com/
  3460. * @author bhouston / http://exocortex.com
  3461. */
  3462. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3463. this.planes = [
  3464. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3465. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3466. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3467. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3468. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3469. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3470. ];
  3471. };
  3472. THREE.Frustum.prototype = {
  3473. constructor: THREE.Frustum,
  3474. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3475. var planes = this.planes;
  3476. planes[0].copy( p0 );
  3477. planes[1].copy( p1 );
  3478. planes[2].copy( p2 );
  3479. planes[3].copy( p3 );
  3480. planes[4].copy( p4 );
  3481. planes[5].copy( p5 );
  3482. return this;
  3483. },
  3484. copy: function ( frustum ) {
  3485. var planes = this.planes;
  3486. for( var i = 0; i < 6; i ++ ) {
  3487. planes[i].copy( frustum.planes[i] );
  3488. }
  3489. return this;
  3490. },
  3491. setFromMatrix: function ( m ) {
  3492. var planes = this.planes;
  3493. var me = m.elements;
  3494. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3495. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3496. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3497. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3498. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3499. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3500. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3501. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3502. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3503. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3504. return this;
  3505. },
  3506. intersectsObject: function () {
  3507. var sphere = new THREE.Sphere();
  3508. return function ( object ) {
  3509. var geometry = object.geometry;
  3510. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3511. sphere.copy( geometry.boundingSphere );
  3512. sphere.applyMatrix4( object.matrixWorld );
  3513. return this.intersectsSphere( sphere );
  3514. };
  3515. }(),
  3516. intersectsSphere: function ( sphere ) {
  3517. var planes = this.planes;
  3518. var center = sphere.center;
  3519. var negRadius = -sphere.radius;
  3520. for ( var i = 0; i < 6; i ++ ) {
  3521. var distance = planes[ i ].distanceToPoint( center );
  3522. if ( distance < negRadius ) {
  3523. return false;
  3524. }
  3525. }
  3526. return true;
  3527. },
  3528. intersectsBox : function() {
  3529. var p1 = new THREE.Vector3(),
  3530. p2 = new THREE.Vector3();
  3531. return function( box ) {
  3532. var planes = this.planes;
  3533. for ( var i = 0; i < 6 ; i ++ ) {
  3534. var plane = planes[i];
  3535. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3536. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3537. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3538. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3539. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3540. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3541. var d1 = plane.distanceToPoint( p1 );
  3542. var d2 = plane.distanceToPoint( p2 );
  3543. // if both outside plane, no intersection
  3544. if ( d1 < 0 && d2 < 0 ) {
  3545. return false;
  3546. }
  3547. }
  3548. return true;
  3549. };
  3550. }(),
  3551. containsPoint: function ( point ) {
  3552. var planes = this.planes;
  3553. for ( var i = 0; i < 6; i ++ ) {
  3554. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3555. return false;
  3556. }
  3557. }
  3558. return true;
  3559. },
  3560. clone: function () {
  3561. return new THREE.Frustum().copy( this );
  3562. }
  3563. };
  3564. /**
  3565. * @author bhouston / http://exocortex.com
  3566. */
  3567. THREE.Plane = function ( normal, constant ) {
  3568. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3569. this.constant = ( constant !== undefined ) ? constant : 0;
  3570. };
  3571. THREE.Plane.prototype = {
  3572. constructor: THREE.Plane,
  3573. set: function ( normal, constant ) {
  3574. this.normal.copy( normal );
  3575. this.constant = constant;
  3576. return this;
  3577. },
  3578. setComponents: function ( x, y, z, w ) {
  3579. this.normal.set( x, y, z );
  3580. this.constant = w;
  3581. return this;
  3582. },
  3583. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3584. this.normal.copy( normal );
  3585. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3586. return this;
  3587. },
  3588. setFromCoplanarPoints: function() {
  3589. var v1 = new THREE.Vector3();
  3590. var v2 = new THREE.Vector3();
  3591. return function ( a, b, c ) {
  3592. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3593. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3594. this.setFromNormalAndCoplanarPoint( normal, a );
  3595. return this;
  3596. };
  3597. }(),
  3598. copy: function ( plane ) {
  3599. this.normal.copy( plane.normal );
  3600. this.constant = plane.constant;
  3601. return this;
  3602. },
  3603. normalize: function () {
  3604. // Note: will lead to a divide by zero if the plane is invalid.
  3605. var inverseNormalLength = 1.0 / this.normal.length();
  3606. this.normal.multiplyScalar( inverseNormalLength );
  3607. this.constant *= inverseNormalLength;
  3608. return this;
  3609. },
  3610. negate: function () {
  3611. this.constant *= -1;
  3612. this.normal.negate();
  3613. return this;
  3614. },
  3615. distanceToPoint: function ( point ) {
  3616. return this.normal.dot( point ) + this.constant;
  3617. },
  3618. distanceToSphere: function ( sphere ) {
  3619. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3620. },
  3621. projectPoint: function ( point, optionalTarget ) {
  3622. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3623. },
  3624. orthoPoint: function ( point, optionalTarget ) {
  3625. var perpendicularMagnitude = this.distanceToPoint( point );
  3626. var result = optionalTarget || new THREE.Vector3();
  3627. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3628. },
  3629. isIntersectionLine: function ( line ) {
  3630. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3631. var startSign = this.distanceToPoint( line.start );
  3632. var endSign = this.distanceToPoint( line.end );
  3633. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3634. },
  3635. intersectLine: function() {
  3636. var v1 = new THREE.Vector3();
  3637. return function ( line, optionalTarget ) {
  3638. var result = optionalTarget || new THREE.Vector3();
  3639. var direction = line.delta( v1 );
  3640. var denominator = this.normal.dot( direction );
  3641. if ( denominator == 0 ) {
  3642. // line is coplanar, return origin
  3643. if( this.distanceToPoint( line.start ) == 0 ) {
  3644. return result.copy( line.start );
  3645. }
  3646. // Unsure if this is the correct method to handle this case.
  3647. return undefined;
  3648. }
  3649. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3650. if( t < 0 || t > 1 ) {
  3651. return undefined;
  3652. }
  3653. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3654. };
  3655. }(),
  3656. coplanarPoint: function ( optionalTarget ) {
  3657. var result = optionalTarget || new THREE.Vector3();
  3658. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3659. },
  3660. applyMatrix4: function() {
  3661. var v1 = new THREE.Vector3();
  3662. var v2 = new THREE.Vector3();
  3663. var m1 = new THREE.Matrix3();
  3664. return function ( matrix, optionalNormalMatrix ) {
  3665. // compute new normal based on theory here:
  3666. // http://www.songho.ca/opengl/gl_normaltransform.html
  3667. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3668. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3669. var newCoplanarPoint = this.coplanarPoint( v2 );
  3670. newCoplanarPoint.applyMatrix4( matrix );
  3671. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3672. return this;
  3673. };
  3674. }(),
  3675. translate: function ( offset ) {
  3676. this.constant = this.constant - offset.dot( this.normal );
  3677. return this;
  3678. },
  3679. equals: function ( plane ) {
  3680. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3681. },
  3682. clone: function () {
  3683. return new THREE.Plane().copy( this );
  3684. }
  3685. };
  3686. /**
  3687. * @author alteredq / http://alteredqualia.com/
  3688. * @author mrdoob / http://mrdoob.com/
  3689. */
  3690. THREE.Math = {
  3691. PI2: Math.PI * 2,
  3692. generateUUID: function () {
  3693. // http://www.broofa.com/Tools/Math.uuid.htm
  3694. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3695. var uuid = new Array(36);
  3696. var rnd = 0, r;
  3697. return function () {
  3698. for ( var i = 0; i < 36; i ++ ) {
  3699. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3700. uuid[ i ] = '-';
  3701. } else if ( i == 14 ) {
  3702. uuid[ i ] = '4';
  3703. } else {
  3704. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3705. r = rnd & 0xf;
  3706. rnd = rnd >> 4;
  3707. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3708. }
  3709. }
  3710. return uuid.join('');
  3711. };
  3712. }(),
  3713. // Clamp value to range <a, b>
  3714. clamp: function ( x, a, b ) {
  3715. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3716. },
  3717. // Clamp value to range <a, inf)
  3718. clampBottom: function ( x, a ) {
  3719. return x < a ? a : x;
  3720. },
  3721. // Linear mapping from range <a1, a2> to range <b1, b2>
  3722. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3723. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3724. },
  3725. // http://en.wikipedia.org/wiki/Smoothstep
  3726. smoothstep: function ( x, min, max ) {
  3727. if ( x <= min ) return 0;
  3728. if ( x >= max ) return 1;
  3729. x = ( x - min )/( max - min );
  3730. return x*x*(3 - 2*x);
  3731. },
  3732. smootherstep: function ( x, min, max ) {
  3733. if ( x <= min ) return 0;
  3734. if ( x >= max ) return 1;
  3735. x = ( x - min )/( max - min );
  3736. return x*x*x*(x*(x*6 - 15) + 10);
  3737. },
  3738. // Random float from <0, 1> with 16 bits of randomness
  3739. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3740. random16: function () {
  3741. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3742. },
  3743. // Random integer from <low, high> interval
  3744. randInt: function ( low, high ) {
  3745. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3746. },
  3747. // Random float from <low, high> interval
  3748. randFloat: function ( low, high ) {
  3749. return low + Math.random() * ( high - low );
  3750. },
  3751. // Random float from <-range/2, range/2> interval
  3752. randFloatSpread: function ( range ) {
  3753. return range * ( 0.5 - Math.random() );
  3754. },
  3755. sign: function ( x ) {
  3756. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3757. },
  3758. degToRad: function() {
  3759. var degreeToRadiansFactor = Math.PI / 180;
  3760. return function ( degrees ) {
  3761. return degrees * degreeToRadiansFactor;
  3762. };
  3763. }(),
  3764. radToDeg: function() {
  3765. var radianToDegreesFactor = 180 / Math.PI;
  3766. return function ( radians ) {
  3767. return radians * radianToDegreesFactor;
  3768. };
  3769. }(),
  3770. isPowerOfTwo: function ( value ) {
  3771. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3772. }
  3773. };
  3774. /**
  3775. * Spline from Tween.js, slightly optimized (and trashed)
  3776. * http://sole.github.com/tween.js/examples/05_spline.html
  3777. *
  3778. * @author mrdoob / http://mrdoob.com/
  3779. * @author alteredq / http://alteredqualia.com/
  3780. */
  3781. THREE.Spline = function ( points ) {
  3782. this.points = points;
  3783. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3784. point, intPoint, weight, w2, w3,
  3785. pa, pb, pc, pd;
  3786. this.initFromArray = function( a ) {
  3787. this.points = [];
  3788. for ( var i = 0; i < a.length; i++ ) {
  3789. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3790. }
  3791. };
  3792. this.getPoint = function ( k ) {
  3793. point = ( this.points.length - 1 ) * k;
  3794. intPoint = Math.floor( point );
  3795. weight = point - intPoint;
  3796. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3797. c[ 1 ] = intPoint;
  3798. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3799. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3800. pa = this.points[ c[ 0 ] ];
  3801. pb = this.points[ c[ 1 ] ];
  3802. pc = this.points[ c[ 2 ] ];
  3803. pd = this.points[ c[ 3 ] ];
  3804. w2 = weight * weight;
  3805. w3 = weight * w2;
  3806. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3807. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3808. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3809. return v3;
  3810. };
  3811. this.getControlPointsArray = function () {
  3812. var i, p, l = this.points.length,
  3813. coords = [];
  3814. for ( i = 0; i < l; i ++ ) {
  3815. p = this.points[ i ];
  3816. coords[ i ] = [ p.x, p.y, p.z ];
  3817. }
  3818. return coords;
  3819. };
  3820. // approximate length by summing linear segments
  3821. this.getLength = function ( nSubDivisions ) {
  3822. var i, index, nSamples, position,
  3823. point = 0, intPoint = 0, oldIntPoint = 0,
  3824. oldPosition = new THREE.Vector3(),
  3825. tmpVec = new THREE.Vector3(),
  3826. chunkLengths = [],
  3827. totalLength = 0;
  3828. // first point has 0 length
  3829. chunkLengths[ 0 ] = 0;
  3830. if ( !nSubDivisions ) nSubDivisions = 100;
  3831. nSamples = this.points.length * nSubDivisions;
  3832. oldPosition.copy( this.points[ 0 ] );
  3833. for ( i = 1; i < nSamples; i ++ ) {
  3834. index = i / nSamples;
  3835. position = this.getPoint( index );
  3836. tmpVec.copy( position );
  3837. totalLength += tmpVec.distanceTo( oldPosition );
  3838. oldPosition.copy( position );
  3839. point = ( this.points.length - 1 ) * index;
  3840. intPoint = Math.floor( point );
  3841. if ( intPoint != oldIntPoint ) {
  3842. chunkLengths[ intPoint ] = totalLength;
  3843. oldIntPoint = intPoint;
  3844. }
  3845. }
  3846. // last point ends with total length
  3847. chunkLengths[ chunkLengths.length ] = totalLength;
  3848. return { chunks: chunkLengths, total: totalLength };
  3849. };
  3850. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3851. var i, j,
  3852. index, indexCurrent, indexNext,
  3853. linearDistance, realDistance,
  3854. sampling, position,
  3855. newpoints = [],
  3856. tmpVec = new THREE.Vector3(),
  3857. sl = this.getLength();
  3858. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3859. for ( i = 1; i < this.points.length; i++ ) {
  3860. //tmpVec.copy( this.points[ i - 1 ] );
  3861. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3862. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3863. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3864. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3865. indexNext = i / ( this.points.length - 1 );
  3866. for ( j = 1; j < sampling - 1; j++ ) {
  3867. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3868. position = this.getPoint( index );
  3869. newpoints.push( tmpVec.copy( position ).clone() );
  3870. }
  3871. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3872. }
  3873. this.points = newpoints;
  3874. };
  3875. // Catmull-Rom
  3876. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3877. var v0 = ( p2 - p0 ) * 0.5,
  3878. v1 = ( p3 - p1 ) * 0.5;
  3879. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3880. };
  3881. };
  3882. /**
  3883. * @author bhouston / http://exocortex.com
  3884. * @author mrdoob / http://mrdoob.com/
  3885. */
  3886. THREE.Triangle = function ( a, b, c ) {
  3887. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3888. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3889. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3890. };
  3891. THREE.Triangle.normal = function() {
  3892. var v0 = new THREE.Vector3();
  3893. return function ( a, b, c, optionalTarget ) {
  3894. var result = optionalTarget || new THREE.Vector3();
  3895. result.subVectors( c, b );
  3896. v0.subVectors( a, b );
  3897. result.cross( v0 );
  3898. var resultLengthSq = result.lengthSq();
  3899. if( resultLengthSq > 0 ) {
  3900. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3901. }
  3902. return result.set( 0, 0, 0 );
  3903. };
  3904. }();
  3905. // static/instance method to calculate barycoordinates
  3906. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3907. THREE.Triangle.barycoordFromPoint = function() {
  3908. var v0 = new THREE.Vector3();
  3909. var v1 = new THREE.Vector3();
  3910. var v2 = new THREE.Vector3();
  3911. return function ( point, a, b, c, optionalTarget ) {
  3912. v0.subVectors( c, a );
  3913. v1.subVectors( b, a );
  3914. v2.subVectors( point, a );
  3915. var dot00 = v0.dot( v0 );
  3916. var dot01 = v0.dot( v1 );
  3917. var dot02 = v0.dot( v2 );
  3918. var dot11 = v1.dot( v1 );
  3919. var dot12 = v1.dot( v2 );
  3920. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3921. var result = optionalTarget || new THREE.Vector3();
  3922. // colinear or singular triangle
  3923. if( denom == 0 ) {
  3924. // arbitrary location outside of triangle?
  3925. // not sure if this is the best idea, maybe should be returning undefined
  3926. return result.set( -2, -1, -1 );
  3927. }
  3928. var invDenom = 1 / denom;
  3929. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3930. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3931. // barycoordinates must always sum to 1
  3932. return result.set( 1 - u - v, v, u );
  3933. };
  3934. }();
  3935. THREE.Triangle.containsPoint = function() {
  3936. var v1 = new THREE.Vector3();
  3937. return function ( point, a, b, c ) {
  3938. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3939. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3940. };
  3941. }();
  3942. THREE.Triangle.prototype = {
  3943. constructor: THREE.Triangle,
  3944. set: function ( a, b, c ) {
  3945. this.a.copy( a );
  3946. this.b.copy( b );
  3947. this.c.copy( c );
  3948. return this;
  3949. },
  3950. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3951. this.a.copy( points[i0] );
  3952. this.b.copy( points[i1] );
  3953. this.c.copy( points[i2] );
  3954. return this;
  3955. },
  3956. copy: function ( triangle ) {
  3957. this.a.copy( triangle.a );
  3958. this.b.copy( triangle.b );
  3959. this.c.copy( triangle.c );
  3960. return this;
  3961. },
  3962. area: function() {
  3963. var v0 = new THREE.Vector3();
  3964. var v1 = new THREE.Vector3();
  3965. return function () {
  3966. v0.subVectors( this.c, this.b );
  3967. v1.subVectors( this.a, this.b );
  3968. return v0.cross( v1 ).length() * 0.5;
  3969. };
  3970. }(),
  3971. midpoint: function ( optionalTarget ) {
  3972. var result = optionalTarget || new THREE.Vector3();
  3973. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3974. },
  3975. normal: function ( optionalTarget ) {
  3976. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3977. },
  3978. plane: function ( optionalTarget ) {
  3979. var result = optionalTarget || new THREE.Plane();
  3980. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3981. },
  3982. barycoordFromPoint: function ( point, optionalTarget ) {
  3983. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3984. },
  3985. containsPoint: function ( point ) {
  3986. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3987. },
  3988. equals: function ( triangle ) {
  3989. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3990. },
  3991. clone: function () {
  3992. return new THREE.Triangle().copy( this );
  3993. }
  3994. };
  3995. /**
  3996. * @author mrdoob / http://mrdoob.com/
  3997. */
  3998. THREE.Vertex = function ( v ) {
  3999. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  4000. return v;
  4001. };
  4002. /**
  4003. * @author mrdoob / http://mrdoob.com/
  4004. */
  4005. THREE.UV = function ( u, v ) {
  4006. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  4007. return new THREE.Vector2( u, v );
  4008. };
  4009. /**
  4010. * @author alteredq / http://alteredqualia.com/
  4011. */
  4012. THREE.Clock = function ( autoStart ) {
  4013. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4014. this.startTime = 0;
  4015. this.oldTime = 0;
  4016. this.elapsedTime = 0;
  4017. this.running = false;
  4018. };
  4019. THREE.Clock.prototype = {
  4020. constructor: THREE.Clock,
  4021. start: function () {
  4022. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4023. ? self.performance.now()
  4024. : Date.now();
  4025. this.oldTime = this.startTime;
  4026. this.running = true;
  4027. },
  4028. stop: function () {
  4029. this.getElapsedTime();
  4030. this.running = false;
  4031. },
  4032. getElapsedTime: function () {
  4033. this.getDelta();
  4034. return this.elapsedTime;
  4035. },
  4036. getDelta: function () {
  4037. var diff = 0;
  4038. if ( this.autoStart && ! this.running ) {
  4039. this.start();
  4040. }
  4041. if ( this.running ) {
  4042. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4043. ? self.performance.now()
  4044. : Date.now();
  4045. diff = 0.001 * ( newTime - this.oldTime );
  4046. this.oldTime = newTime;
  4047. this.elapsedTime += diff;
  4048. }
  4049. return diff;
  4050. }
  4051. };
  4052. /**
  4053. * https://github.com/mrdoob/eventdispatcher.js/
  4054. */
  4055. THREE.EventDispatcher = function () {}
  4056. THREE.EventDispatcher.prototype = {
  4057. constructor: THREE.EventDispatcher,
  4058. apply: function ( object ) {
  4059. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4060. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4061. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4062. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4063. },
  4064. addEventListener: function ( type, listener ) {
  4065. if ( this._listeners === undefined ) this._listeners = {};
  4066. var listeners = this._listeners;
  4067. if ( listeners[ type ] === undefined ) {
  4068. listeners[ type ] = [];
  4069. }
  4070. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4071. listeners[ type ].push( listener );
  4072. }
  4073. },
  4074. hasEventListener: function ( type, listener ) {
  4075. if ( this._listeners === undefined ) return false;
  4076. var listeners = this._listeners;
  4077. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4078. return true;
  4079. }
  4080. return false;
  4081. },
  4082. removeEventListener: function ( type, listener ) {
  4083. if ( this._listeners === undefined ) return;
  4084. var listeners = this._listeners;
  4085. var listenerArray = listeners[ type ];
  4086. if ( listenerArray !== undefined ) {
  4087. var index = listenerArray.indexOf( listener );
  4088. if ( index !== - 1 ) {
  4089. listenerArray.splice( index, 1 );
  4090. }
  4091. }
  4092. },
  4093. dispatchEvent: function () {
  4094. var array = [];
  4095. return function ( event ) {
  4096. if ( this._listeners === undefined ) return;
  4097. var listeners = this._listeners;
  4098. var listenerArray = listeners[ event.type ];
  4099. if ( listenerArray !== undefined ) {
  4100. event.target = this;
  4101. var length = listenerArray.length;
  4102. for ( var i = 0; i < length; i ++ ) {
  4103. array[ i ] = listenerArray[ i ];
  4104. }
  4105. for ( var i = 0; i < length; i ++ ) {
  4106. array[ i ].call( this, event );
  4107. }
  4108. }
  4109. };
  4110. }()
  4111. };
  4112. /**
  4113. * @author mrdoob / http://mrdoob.com/
  4114. * @author bhouston / http://exocortex.com/
  4115. * @author stephomi / http://stephaneginier.com/
  4116. */
  4117. ( function ( THREE ) {
  4118. THREE.Raycaster = function ( origin, direction, near, far ) {
  4119. this.ray = new THREE.Ray( origin, direction );
  4120. // direction is assumed to be normalized (for accurate distance calculations)
  4121. this.near = near || 0;
  4122. this.far = far || Infinity;
  4123. };
  4124. var sphere = new THREE.Sphere();
  4125. var localRay = new THREE.Ray();
  4126. var facePlane = new THREE.Plane();
  4127. var intersectPoint = new THREE.Vector3();
  4128. var matrixPosition = new THREE.Vector3();
  4129. var inverseMatrix = new THREE.Matrix4();
  4130. var descSort = function ( a, b ) {
  4131. return a.distance - b.distance;
  4132. };
  4133. var vA = new THREE.Vector3();
  4134. var vB = new THREE.Vector3();
  4135. var vC = new THREE.Vector3();
  4136. var intersectObject = function ( object, raycaster, intersects ) {
  4137. if ( object instanceof THREE.Sprite ) {
  4138. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4139. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4140. if ( distance > object.scale.x ) {
  4141. return intersects;
  4142. }
  4143. intersects.push( {
  4144. distance: distance,
  4145. point: object.position,
  4146. face: null,
  4147. object: object
  4148. } );
  4149. } else if ( object instanceof THREE.LOD ) {
  4150. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4151. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4152. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4153. } else if ( object instanceof THREE.Mesh ) {
  4154. var geometry = object.geometry;
  4155. // Checking boundingSphere distance to ray
  4156. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4157. sphere.copy( geometry.boundingSphere );
  4158. sphere.applyMatrix4( object.matrixWorld );
  4159. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4160. return intersects;
  4161. }
  4162. // Check boundingBox before continuing
  4163. inverseMatrix.getInverse( object.matrixWorld );
  4164. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4165. if ( geometry.boundingBox !== null ) {
  4166. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4167. return intersects;
  4168. }
  4169. }
  4170. if ( geometry instanceof THREE.BufferGeometry ) {
  4171. var material = object.material;
  4172. if ( material === undefined ) return intersects;
  4173. var attributes = geometry.attributes;
  4174. var a, b, c;
  4175. var precision = raycaster.precision;
  4176. if ( attributes.index !== undefined ) {
  4177. var offsets = geometry.offsets;
  4178. var indices = attributes.index.array;
  4179. var positions = attributes.position.array;
  4180. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  4181. var start = offsets[ oi ].start;
  4182. var count = offsets[ oi ].count;
  4183. var index = offsets[ oi ].index;
  4184. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4185. a = index + indices[ i ];
  4186. b = index + indices[ i + 1 ];
  4187. c = index + indices[ i + 2 ];
  4188. vA.set(
  4189. positions[ a * 3 ],
  4190. positions[ a * 3 + 1 ],
  4191. positions[ a * 3 + 2 ]
  4192. );
  4193. vB.set(
  4194. positions[ b * 3 ],
  4195. positions[ b * 3 + 1 ],
  4196. positions[ b * 3 + 2 ]
  4197. );
  4198. vC.set(
  4199. positions[ c * 3 ],
  4200. positions[ c * 3 + 1 ],
  4201. positions[ c * 3 + 2 ]
  4202. );
  4203. if ( material.side === THREE.BackSide ) {
  4204. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4205. } else {
  4206. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4207. }
  4208. if ( intersectionPoint === null ) continue;
  4209. intersectionPoint.applyMatrix4( object.matrixWorld );
  4210. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4211. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4212. intersects.push( {
  4213. distance: distance,
  4214. point: intersectionPoint,
  4215. indices: [a, b, c],
  4216. face: null,
  4217. faceIndex: null,
  4218. object: object
  4219. } );
  4220. }
  4221. }
  4222. } else {
  4223. var offsets = geometry.offsets;
  4224. var positions = attributes.position.array;
  4225. for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {
  4226. a = i;
  4227. b = i + 1;
  4228. c = i + 2;
  4229. vA.set(
  4230. positions[ a * 3 ],
  4231. positions[ a * 3 + 1 ],
  4232. positions[ a * 3 + 2 ]
  4233. );
  4234. vB.set(
  4235. positions[ b * 3 ],
  4236. positions[ b * 3 + 1 ],
  4237. positions[ b * 3 + 2 ]
  4238. );
  4239. vC.set(
  4240. positions[ c * 3 ],
  4241. positions[ c * 3 + 1 ],
  4242. positions[ c * 3 + 2 ]
  4243. );
  4244. if ( material.side === THREE.BackSide ) {
  4245. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4246. } else {
  4247. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4248. }
  4249. if ( intersectionPoint === null ) continue;
  4250. intersectionPoint.applyMatrix4( object.matrixWorld );
  4251. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4252. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4253. intersects.push( {
  4254. distance: distance,
  4255. point: intersectionPoint,
  4256. indices: [a, b, c],
  4257. face: null,
  4258. faceIndex: null,
  4259. object: object
  4260. } );
  4261. }
  4262. }
  4263. } else if ( geometry instanceof THREE.Geometry ) {
  4264. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4265. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4266. var a, b, c, d;
  4267. var precision = raycaster.precision;
  4268. var vertices = geometry.vertices;
  4269. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4270. var face = geometry.faces[ f ];
  4271. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4272. if ( material === undefined ) continue;
  4273. a = vertices[ face.a ];
  4274. b = vertices[ face.b ];
  4275. c = vertices[ face.c ];
  4276. if ( material.morphTargets === true ) {
  4277. var morphTargets = geometry.morphTargets;
  4278. var morphInfluences = object.morphTargetInfluences;
  4279. vA.set( 0, 0, 0 );
  4280. vB.set( 0, 0, 0 );
  4281. vC.set( 0, 0, 0 );
  4282. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4283. var influence = morphInfluences[ t ];
  4284. if ( influence === 0 ) continue;
  4285. var targets = morphTargets[ t ].vertices;
  4286. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4287. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4288. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4289. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4290. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4291. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4292. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4293. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4294. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4295. }
  4296. vA.add( a );
  4297. vB.add( b );
  4298. vC.add( c );
  4299. a = vA;
  4300. b = vB;
  4301. c = vC;
  4302. }
  4303. if ( material.side === THREE.BackSide ) {
  4304. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4305. } else {
  4306. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4307. }
  4308. if ( intersectionPoint === null ) continue;
  4309. intersectionPoint.applyMatrix4( object.matrixWorld );
  4310. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4311. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4312. intersects.push( {
  4313. distance: distance,
  4314. point: intersectionPoint,
  4315. face: face,
  4316. faceIndex: f,
  4317. object: object
  4318. } );
  4319. }
  4320. }
  4321. } else if ( object instanceof THREE.Line ) {
  4322. var precision = raycaster.linePrecision;
  4323. var precisionSq = precision * precision;
  4324. var geometry = object.geometry;
  4325. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4326. // Checking boundingSphere distance to ray
  4327. sphere.copy( geometry.boundingSphere );
  4328. sphere.applyMatrix4( object.matrixWorld );
  4329. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4330. return intersects;
  4331. }
  4332. inverseMatrix.getInverse( object.matrixWorld );
  4333. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4334. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4335. } else */ if ( geometry instanceof THREE.Geometry ) {
  4336. var vertices = geometry.vertices;
  4337. var nbVertices = vertices.length;
  4338. var interSegment = new THREE.Vector3();
  4339. var interRay = new THREE.Vector3();
  4340. var step = object.type === THREE.LineStrip ? 1 : 2;
  4341. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4342. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4343. if ( distSq > precisionSq ) continue;
  4344. var distance = localRay.origin.distanceTo( interRay );
  4345. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4346. intersects.push( {
  4347. distance: distance,
  4348. // What do we want? intersection point on the ray or on the segment??
  4349. // point: raycaster.ray.at( distance ),
  4350. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4351. face: null,
  4352. faceIndex: null,
  4353. object: object
  4354. } );
  4355. }
  4356. }
  4357. }
  4358. };
  4359. var intersectDescendants = function ( object, raycaster, intersects ) {
  4360. var descendants = object.getDescendants();
  4361. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4362. intersectObject( descendants[ i ], raycaster, intersects );
  4363. }
  4364. };
  4365. //
  4366. THREE.Raycaster.prototype.precision = 0.0001;
  4367. THREE.Raycaster.prototype.linePrecision = 1;
  4368. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4369. this.ray.set( origin, direction );
  4370. // direction is assumed to be normalized (for accurate distance calculations)
  4371. };
  4372. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4373. var intersects = [];
  4374. if ( recursive === true ) {
  4375. intersectDescendants( object, this, intersects );
  4376. }
  4377. intersectObject( object, this, intersects );
  4378. intersects.sort( descSort );
  4379. return intersects;
  4380. };
  4381. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4382. var intersects = [];
  4383. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4384. intersectObject( objects[ i ], this, intersects );
  4385. if ( recursive === true ) {
  4386. intersectDescendants( objects[ i ], this, intersects );
  4387. }
  4388. }
  4389. intersects.sort( descSort );
  4390. return intersects;
  4391. };
  4392. }( THREE ) );
  4393. /**
  4394. * @author mrdoob / http://mrdoob.com/
  4395. * @author mikael emtinger / http://gomo.se/
  4396. * @author alteredq / http://alteredqualia.com/
  4397. * @author WestLangley / http://github.com/WestLangley
  4398. */
  4399. THREE.Object3D = function () {
  4400. this.id = THREE.Object3DIdCount ++;
  4401. this.uuid = THREE.Math.generateUUID();
  4402. this.name = '';
  4403. this.parent = undefined;
  4404. this.children = [];
  4405. this.up = new THREE.Vector3( 0, 1, 0 );
  4406. this.position = new THREE.Vector3();
  4407. this._rotation = new THREE.Euler();
  4408. this._quaternion = new THREE.Quaternion();
  4409. this.scale = new THREE.Vector3( 1, 1, 1 );
  4410. // keep rotation and quaternion in sync
  4411. this._rotation._quaternion = this.quaternion;
  4412. this._quaternion._euler = this.rotation;
  4413. this.renderDepth = null;
  4414. this.rotationAutoUpdate = true;
  4415. this.matrix = new THREE.Matrix4();
  4416. this.matrixWorld = new THREE.Matrix4();
  4417. this.matrixAutoUpdate = true;
  4418. this.matrixWorldNeedsUpdate = true;
  4419. this.visible = true;
  4420. this.castShadow = false;
  4421. this.receiveShadow = false;
  4422. this.frustumCulled = true;
  4423. this.userData = {};
  4424. };
  4425. THREE.Object3D.prototype = {
  4426. constructor: THREE.Object3D,
  4427. get rotation () {
  4428. return this._rotation;
  4429. },
  4430. set rotation ( value ) {
  4431. this._rotation = value;
  4432. this._rotation._quaternion = this._quaternion;
  4433. this._quaternion._euler = this._rotation;
  4434. this._rotation._updateQuaternion();
  4435. },
  4436. get quaternion () {
  4437. return this._quaternion;
  4438. },
  4439. set quaternion ( value ) {
  4440. this._quaternion = value;
  4441. this._quaternion._euler = this._rotation;
  4442. this._rotation._quaternion = this._quaternion;
  4443. this._quaternion._updateEuler();
  4444. },
  4445. get eulerOrder () {
  4446. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4447. return this.rotation.order;
  4448. },
  4449. set eulerOrder ( value ) {
  4450. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4451. this.rotation.order = value;
  4452. },
  4453. get useQuaternion () {
  4454. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4455. },
  4456. set useQuaternion ( value ) {
  4457. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4458. },
  4459. applyMatrix: function ( matrix ) {
  4460. this.matrix.multiplyMatrices( matrix, this.matrix );
  4461. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4462. },
  4463. setRotationFromAxisAngle: function ( axis, angle ) {
  4464. // assumes axis is normalized
  4465. this.quaternion.setFromAxisAngle( axis, angle );
  4466. },
  4467. setRotationFromEuler: function ( euler ) {
  4468. this.quaternion.setFromEuler( euler, true );
  4469. },
  4470. setRotationFromMatrix: function ( m ) {
  4471. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4472. this.quaternion.setFromRotationMatrix( m );
  4473. },
  4474. setRotationFromQuaternion: function ( q ) {
  4475. // assumes q is normalized
  4476. this.quaternion.copy( q );
  4477. },
  4478. rotateOnAxis: function() {
  4479. // rotate object on axis in object space
  4480. // axis is assumed to be normalized
  4481. var q1 = new THREE.Quaternion();
  4482. return function ( axis, angle ) {
  4483. q1.setFromAxisAngle( axis, angle );
  4484. this.quaternion.multiply( q1 );
  4485. return this;
  4486. }
  4487. }(),
  4488. rotateX: function () {
  4489. var v1 = new THREE.Vector3( 1, 0, 0 );
  4490. return function ( angle ) {
  4491. return this.rotateOnAxis( v1, angle );
  4492. };
  4493. }(),
  4494. rotateY: function () {
  4495. var v1 = new THREE.Vector3( 0, 1, 0 );
  4496. return function ( angle ) {
  4497. return this.rotateOnAxis( v1, angle );
  4498. };
  4499. }(),
  4500. rotateZ: function () {
  4501. var v1 = new THREE.Vector3( 0, 0, 1 );
  4502. return function ( angle ) {
  4503. return this.rotateOnAxis( v1, angle );
  4504. };
  4505. }(),
  4506. translateOnAxis: function () {
  4507. // translate object by distance along axis in object space
  4508. // axis is assumed to be normalized
  4509. var v1 = new THREE.Vector3();
  4510. return function ( axis, distance ) {
  4511. v1.copy( axis );
  4512. v1.applyQuaternion( this.quaternion );
  4513. this.position.add( v1.multiplyScalar( distance ) );
  4514. return this;
  4515. }
  4516. }(),
  4517. translate: function ( distance, axis ) {
  4518. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4519. return this.translateOnAxis( axis, distance );
  4520. },
  4521. translateX: function () {
  4522. var v1 = new THREE.Vector3( 1, 0, 0 );
  4523. return function ( distance ) {
  4524. return this.translateOnAxis( v1, distance );
  4525. };
  4526. }(),
  4527. translateY: function () {
  4528. var v1 = new THREE.Vector3( 0, 1, 0 );
  4529. return function ( distance ) {
  4530. return this.translateOnAxis( v1, distance );
  4531. };
  4532. }(),
  4533. translateZ: function () {
  4534. var v1 = new THREE.Vector3( 0, 0, 1 );
  4535. return function ( distance ) {
  4536. return this.translateOnAxis( v1, distance );
  4537. };
  4538. }(),
  4539. localToWorld: function ( vector ) {
  4540. return vector.applyMatrix4( this.matrixWorld );
  4541. },
  4542. worldToLocal: function () {
  4543. var m1 = new THREE.Matrix4();
  4544. return function ( vector ) {
  4545. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4546. };
  4547. }(),
  4548. lookAt: function () {
  4549. // This routine does not support objects with rotated and/or translated parent(s)
  4550. var m1 = new THREE.Matrix4();
  4551. return function ( vector ) {
  4552. m1.lookAt( vector, this.position, this.up );
  4553. this.quaternion.setFromRotationMatrix( m1 );
  4554. };
  4555. }(),
  4556. add: function ( object ) {
  4557. if ( object === this ) {
  4558. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4559. return;
  4560. }
  4561. if ( object instanceof THREE.Object3D ) {
  4562. if ( object.parent !== undefined ) {
  4563. object.parent.remove( object );
  4564. }
  4565. object.parent = this;
  4566. object.dispatchEvent( { type: 'added' } );
  4567. this.children.push( object );
  4568. // add to scene
  4569. var scene = this;
  4570. while ( scene.parent !== undefined ) {
  4571. scene = scene.parent;
  4572. }
  4573. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4574. scene.__addObject( object );
  4575. }
  4576. }
  4577. },
  4578. remove: function ( object ) {
  4579. var index = this.children.indexOf( object );
  4580. if ( index !== - 1 ) {
  4581. object.parent = undefined;
  4582. object.dispatchEvent( { type: 'removed' } );
  4583. this.children.splice( index, 1 );
  4584. // remove from scene
  4585. var scene = this;
  4586. while ( scene.parent !== undefined ) {
  4587. scene = scene.parent;
  4588. }
  4589. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4590. scene.__removeObject( object );
  4591. }
  4592. }
  4593. },
  4594. traverse: function ( callback ) {
  4595. callback( this );
  4596. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4597. this.children[ i ].traverse( callback );
  4598. }
  4599. },
  4600. getObjectById: function ( id, recursive ) {
  4601. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4602. var child = this.children[ i ];
  4603. if ( child.id === id ) {
  4604. return child;
  4605. }
  4606. if ( recursive === true ) {
  4607. child = child.getObjectById( id, recursive );
  4608. if ( child !== undefined ) {
  4609. return child;
  4610. }
  4611. }
  4612. }
  4613. return undefined;
  4614. },
  4615. getObjectByName: function ( name, recursive ) {
  4616. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4617. var child = this.children[ i ];
  4618. if ( child.name === name ) {
  4619. return child;
  4620. }
  4621. if ( recursive === true ) {
  4622. child = child.getObjectByName( name, recursive );
  4623. if ( child !== undefined ) {
  4624. return child;
  4625. }
  4626. }
  4627. }
  4628. return undefined;
  4629. },
  4630. getChildByName: function ( name, recursive ) {
  4631. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4632. return this.getObjectByName( name, recursive );
  4633. },
  4634. getDescendants: function ( array ) {
  4635. if ( array === undefined ) array = [];
  4636. Array.prototype.push.apply( array, this.children );
  4637. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4638. this.children[ i ].getDescendants( array );
  4639. }
  4640. return array;
  4641. },
  4642. updateMatrix: function () {
  4643. this.matrix.compose( this.position, this.quaternion, this.scale );
  4644. this.matrixWorldNeedsUpdate = true;
  4645. },
  4646. updateMatrixWorld: function ( force ) {
  4647. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4648. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4649. if ( this.parent === undefined ) {
  4650. this.matrixWorld.copy( this.matrix );
  4651. } else {
  4652. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4653. }
  4654. this.matrixWorldNeedsUpdate = false;
  4655. force = true;
  4656. }
  4657. // update children
  4658. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4659. this.children[ i ].updateMatrixWorld( force );
  4660. }
  4661. },
  4662. clone: function ( object, recursive ) {
  4663. if ( object === undefined ) object = new THREE.Object3D();
  4664. if ( recursive === undefined ) recursive = true;
  4665. object.name = this.name;
  4666. object.up.copy( this.up );
  4667. object.position.copy( this.position );
  4668. object.quaternion.copy( this.quaternion );
  4669. object.scale.copy( this.scale );
  4670. object.renderDepth = this.renderDepth;
  4671. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4672. object.matrix.copy( this.matrix );
  4673. object.matrixWorld.copy( this.matrixWorld );
  4674. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4675. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4676. object.visible = this.visible;
  4677. object.castShadow = this.castShadow;
  4678. object.receiveShadow = this.receiveShadow;
  4679. object.frustumCulled = this.frustumCulled;
  4680. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4681. if ( recursive === true ) {
  4682. for ( var i = 0; i < this.children.length; i ++ ) {
  4683. var child = this.children[ i ];
  4684. object.add( child.clone() );
  4685. }
  4686. }
  4687. return object;
  4688. }
  4689. };
  4690. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4691. THREE.Object3DIdCount = 0;
  4692. /**
  4693. * @author mrdoob / http://mrdoob.com/
  4694. * @author supereggbert / http://www.paulbrunt.co.uk/
  4695. * @author julianwa / https://github.com/julianwa
  4696. */
  4697. THREE.Projector = function () {
  4698. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4699. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4700. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4701. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4702. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4703. _renderData = { objects: [], lights: [], elements: [] },
  4704. _vA = new THREE.Vector3(),
  4705. _vB = new THREE.Vector3(),
  4706. _vC = new THREE.Vector3(),
  4707. _vector3 = new THREE.Vector3(),
  4708. _vector4 = new THREE.Vector4(),
  4709. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4710. _boundingBox = new THREE.Box3(),
  4711. _points3 = new Array( 3 ),
  4712. _points4 = new Array( 4 ),
  4713. _viewMatrix = new THREE.Matrix4(),
  4714. _viewProjectionMatrix = new THREE.Matrix4(),
  4715. _modelMatrix,
  4716. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4717. _normalMatrix = new THREE.Matrix3(),
  4718. _frustum = new THREE.Frustum(),
  4719. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4720. _clippedVertex2PositionScreen = new THREE.Vector4();
  4721. this.projectVector = function ( vector, camera ) {
  4722. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4723. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4724. return vector.applyProjection( _viewProjectionMatrix );
  4725. };
  4726. this.unprojectVector = function () {
  4727. var projectionMatrixInverse = new THREE.Matrix4();
  4728. return function ( vector, camera ) {
  4729. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4730. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4731. return vector.applyProjection( _viewProjectionMatrix );
  4732. };
  4733. }();
  4734. this.pickingRay = function ( vector, camera ) {
  4735. // set two vectors with opposing z values
  4736. vector.z = -1.0;
  4737. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4738. this.unprojectVector( vector, camera );
  4739. this.unprojectVector( end, camera );
  4740. // find direction from vector to end
  4741. end.sub( vector ).normalize();
  4742. return new THREE.Raycaster( vector, end );
  4743. };
  4744. var projectObject = function ( object ) {
  4745. if ( object.visible === false ) return;
  4746. if ( object instanceof THREE.Light ) {
  4747. _renderData.lights.push( object );
  4748. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4749. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4750. _object = getNextObjectInPool();
  4751. _object.id = object.id;
  4752. _object.object = object;
  4753. if ( object.renderDepth !== null ) {
  4754. _object.z = object.renderDepth;
  4755. } else {
  4756. _vector3.setFromMatrixPosition( object.matrixWorld );
  4757. _vector3.applyProjection( _viewProjectionMatrix );
  4758. _object.z = _vector3.z;
  4759. }
  4760. _renderData.objects.push( _object );
  4761. }
  4762. }
  4763. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4764. projectObject( object.children[ i ] );
  4765. }
  4766. };
  4767. var projectGraph = function ( root, sortObjects ) {
  4768. _objectCount = 0;
  4769. _renderData.objects.length = 0;
  4770. _renderData.lights.length = 0;
  4771. projectObject( root );
  4772. if ( sortObjects === true ) {
  4773. _renderData.objects.sort( painterSort );
  4774. }
  4775. };
  4776. var RenderList = function () {
  4777. var normals = [];
  4778. var object = null;
  4779. var normalMatrix = new THREE.Matrix3();
  4780. var setObject = function ( value ) {
  4781. object = value;
  4782. normalMatrix.getNormalMatrix( object.matrixWorld );
  4783. normals.length = 0;
  4784. };
  4785. var projectVertex = function ( vertex ) {
  4786. var position = vertex.position;
  4787. var positionWorld = vertex.positionWorld;
  4788. var positionScreen = vertex.positionScreen;
  4789. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4790. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4791. var invW = 1 / positionScreen.w;
  4792. positionScreen.x *= invW;
  4793. positionScreen.y *= invW;
  4794. positionScreen.z *= invW;
  4795. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4796. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4797. positionScreen.z >= -1 && positionScreen.z <= 1;
  4798. };
  4799. var pushVertex = function ( x, y, z ) {
  4800. _vertex = getNextVertexInPool();
  4801. _vertex.position.set( x, y, z );
  4802. projectVertex( _vertex );
  4803. };
  4804. var pushNormal = function ( x, y, z ) {
  4805. normals.push( x, y, z );
  4806. };
  4807. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4808. _points3[ 0 ] = v1.positionScreen;
  4809. _points3[ 1 ] = v2.positionScreen;
  4810. _points3[ 2 ] = v3.positionScreen;
  4811. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4812. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4813. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4814. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4815. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4816. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4817. }
  4818. return false;
  4819. };
  4820. var pushLine = function ( a, b ) {
  4821. var v1 = _vertexPool[ a ];
  4822. var v2 = _vertexPool[ b ];
  4823. _line = getNextLineInPool();
  4824. _line.id = object.id;
  4825. _line.v1.copy( v1 );
  4826. _line.v2.copy( v2 );
  4827. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4828. _line.material = object.material;
  4829. _renderData.elements.push( _line );
  4830. };
  4831. var pushTriangle = function ( a, b, c ) {
  4832. var v1 = _vertexPool[ a ];
  4833. var v2 = _vertexPool[ b ];
  4834. var v3 = _vertexPool[ c ];
  4835. if ( checkTriangleVisibility( v1, v2, v3 ) === true ) {
  4836. _face = getNextFaceInPool();
  4837. _face.id = object.id;
  4838. _face.v1.copy( v1 );
  4839. _face.v2.copy( v2 );
  4840. _face.v3.copy( v3 );
  4841. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4842. for ( var i = 0; i < 3; i ++ ) {
  4843. var offset = arguments[ i ] * 3;
  4844. var normal = _face.vertexNormalsModel[ i ];
  4845. normal.set( normals[ offset + 0 ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4846. normal.applyMatrix3( normalMatrix ).normalize();
  4847. }
  4848. _face.vertexNormalsLength = 3;
  4849. _face.material = object.material;
  4850. _renderData.elements.push( _face );
  4851. }
  4852. };
  4853. return {
  4854. setObject: setObject,
  4855. projectVertex: projectVertex,
  4856. checkTriangleVisibility: checkTriangleVisibility,
  4857. pushVertex: pushVertex,
  4858. pushNormal: pushNormal,
  4859. pushLine: pushLine,
  4860. pushTriangle: pushTriangle
  4861. }
  4862. };
  4863. var renderList = new RenderList();
  4864. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4865. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4866. isFaceMaterial, objectMaterials;
  4867. _faceCount = 0;
  4868. _lineCount = 0;
  4869. _spriteCount = 0;
  4870. _renderData.elements.length = 0;
  4871. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4872. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4873. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4874. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4875. _frustum.setFromMatrix( _viewProjectionMatrix );
  4876. projectGraph( scene, sortObjects );
  4877. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4878. object = _renderData.objects[ o ].object;
  4879. geometry = object.geometry;
  4880. renderList.setObject( object );
  4881. _modelMatrix = object.matrixWorld;
  4882. _vertexCount = 0;
  4883. if ( object instanceof THREE.Mesh ) {
  4884. if ( geometry instanceof THREE.BufferGeometry ) {
  4885. var attributes = geometry.attributes;
  4886. var offsets = geometry.offsets;
  4887. if ( attributes.position === undefined ) continue;
  4888. var positions = attributes.position.array;
  4889. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4890. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4891. }
  4892. var normals = attributes.normal.array;
  4893. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4894. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4895. }
  4896. if ( attributes.index !== undefined ) {
  4897. var indices = attributes.index.array;
  4898. if ( offsets.length > 0 ) {
  4899. for ( var o = 0; o < offsets.length; o ++ ) {
  4900. var offset = offsets[ o ];
  4901. var index = offset.index;
  4902. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4903. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4904. }
  4905. }
  4906. } else {
  4907. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4908. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4909. }
  4910. }
  4911. } else {
  4912. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4913. renderList.pushTriangle( i, i + 1, i + 2 );
  4914. }
  4915. }
  4916. } else if ( geometry instanceof THREE.Geometry ) {
  4917. vertices = geometry.vertices;
  4918. faces = geometry.faces;
  4919. faceVertexUvs = geometry.faceVertexUvs;
  4920. _normalMatrix.getNormalMatrix( _modelMatrix );
  4921. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4922. objectMaterials = isFaceMaterial === true ? object.material : null;
  4923. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4924. var vertex = vertices[ v ];
  4925. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4926. }
  4927. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4928. face = faces[ f ];
  4929. var material = isFaceMaterial === true
  4930. ? objectMaterials.materials[ face.materialIndex ]
  4931. : object.material;
  4932. if ( material === undefined ) continue;
  4933. var side = material.side;
  4934. var v1 = _vertexPool[ face.a ];
  4935. var v2 = _vertexPool[ face.b ];
  4936. var v3 = _vertexPool[ face.c ];
  4937. if ( material.morphTargets === true ) {
  4938. var morphTargets = geometry.morphTargets;
  4939. var morphInfluences = object.morphTargetInfluences;
  4940. var v1p = v1.position;
  4941. var v2p = v2.position;
  4942. var v3p = v3.position;
  4943. _vA.set( 0, 0, 0 );
  4944. _vB.set( 0, 0, 0 );
  4945. _vC.set( 0, 0, 0 );
  4946. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4947. var influence = morphInfluences[ t ];
  4948. if ( influence === 0 ) continue;
  4949. var targets = morphTargets[ t ].vertices;
  4950. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4951. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4952. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4953. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  4954. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  4955. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  4956. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  4957. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  4958. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  4959. }
  4960. v1.position.add( _vA );
  4961. v2.position.add( _vB );
  4962. v3.position.add( _vC );
  4963. renderList.projectVertex( v1 );
  4964. renderList.projectVertex( v2 );
  4965. renderList.projectVertex( v3 );
  4966. }
  4967. var visible = renderList.checkTriangleVisibility( v1, v2, v3 );
  4968. if ( ( visible === false && side === THREE.FrontSide ) ||
  4969. ( visible === true && side === THREE.BackSide ) ) continue;
  4970. _face = getNextFaceInPool();
  4971. _face.id = object.id;
  4972. _face.v1.copy( v1 );
  4973. _face.v2.copy( v2 );
  4974. _face.v3.copy( v3 );
  4975. _face.normalModel.copy( face.normal );
  4976. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4977. _face.normalModel.negate();
  4978. }
  4979. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4980. faceVertexNormals = face.vertexNormals;
  4981. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4982. var normalModel = _face.vertexNormalsModel[ n ];
  4983. normalModel.copy( faceVertexNormals[ n ] );
  4984. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4985. normalModel.negate();
  4986. }
  4987. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4988. }
  4989. _face.vertexNormalsLength = faceVertexNormals.length;
  4990. for ( var c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4991. uvs = faceVertexUvs[ c ][ f ];
  4992. if ( uvs === undefined ) continue;
  4993. for ( var u = 0, ul = uvs.length; u < ul; u ++ ) {
  4994. _face.uvs[ c ][ u ] = uvs[ u ];
  4995. }
  4996. }
  4997. _face.color = face.color;
  4998. _face.material = material;
  4999. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  5000. _renderData.elements.push( _face );
  5001. }
  5002. }
  5003. } else if ( object instanceof THREE.Line ) {
  5004. if ( geometry instanceof THREE.BufferGeometry ) {
  5005. var attributes = geometry.attributes;
  5006. if ( attributes.position !== undefined ) {
  5007. var positions = attributes.position.array;
  5008. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  5009. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5010. }
  5011. if ( attributes.index !== undefined ) {
  5012. var indices = attributes.index.array;
  5013. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  5014. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  5015. }
  5016. } else {
  5017. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  5018. renderList.pushLine( i, i + 1 );
  5019. }
  5020. }
  5021. }
  5022. } else if ( geometry instanceof THREE.Geometry ) {
  5023. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  5024. vertices = object.geometry.vertices;
  5025. if ( vertices.length === 0 ) continue;
  5026. v1 = getNextVertexInPool();
  5027. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  5028. // Handle LineStrip and LinePieces
  5029. var step = object.type === THREE.LinePieces ? 2 : 1;
  5030. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  5031. v1 = getNextVertexInPool();
  5032. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  5033. if ( ( v + 1 ) % step > 0 ) continue;
  5034. v2 = _vertexPool[ _vertexCount - 2 ];
  5035. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  5036. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  5037. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  5038. // Perform the perspective divide
  5039. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  5040. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  5041. _line = getNextLineInPool();
  5042. _line.id = object.id;
  5043. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  5044. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  5045. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  5046. _line.material = object.material;
  5047. if ( object.material.vertexColors === THREE.VertexColors ) {
  5048. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  5049. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  5050. }
  5051. _renderData.elements.push( _line );
  5052. }
  5053. }
  5054. }
  5055. } else if ( object instanceof THREE.Sprite ) {
  5056. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  5057. _vector4.applyMatrix4( _viewProjectionMatrix );
  5058. var invW = 1 / _vector4.w;
  5059. _vector4.z *= invW;
  5060. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  5061. _sprite = getNextSpriteInPool();
  5062. _sprite.id = object.id;
  5063. _sprite.x = _vector4.x * invW;
  5064. _sprite.y = _vector4.y * invW;
  5065. _sprite.z = _vector4.z;
  5066. _sprite.object = object;
  5067. _sprite.rotation = object.rotation;
  5068. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  5069. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  5070. _sprite.material = object.material;
  5071. _renderData.elements.push( _sprite );
  5072. }
  5073. }
  5074. }
  5075. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  5076. return _renderData;
  5077. };
  5078. // Pools
  5079. function getNextObjectInPool() {
  5080. if ( _objectCount === _objectPoolLength ) {
  5081. var object = new THREE.RenderableObject();
  5082. _objectPool.push( object );
  5083. _objectPoolLength ++;
  5084. _objectCount ++;
  5085. return object;
  5086. }
  5087. return _objectPool[ _objectCount ++ ];
  5088. }
  5089. function getNextVertexInPool() {
  5090. if ( _vertexCount === _vertexPoolLength ) {
  5091. var vertex = new THREE.RenderableVertex();
  5092. _vertexPool.push( vertex );
  5093. _vertexPoolLength ++;
  5094. _vertexCount ++;
  5095. return vertex;
  5096. }
  5097. return _vertexPool[ _vertexCount ++ ];
  5098. }
  5099. function getNextFaceInPool() {
  5100. if ( _faceCount === _facePoolLength ) {
  5101. var face = new THREE.RenderableFace();
  5102. _facePool.push( face );
  5103. _facePoolLength ++;
  5104. _faceCount ++;
  5105. return face;
  5106. }
  5107. return _facePool[ _faceCount ++ ];
  5108. }
  5109. function getNextLineInPool() {
  5110. if ( _lineCount === _linePoolLength ) {
  5111. var line = new THREE.RenderableLine();
  5112. _linePool.push( line );
  5113. _linePoolLength ++;
  5114. _lineCount ++
  5115. return line;
  5116. }
  5117. return _linePool[ _lineCount ++ ];
  5118. }
  5119. function getNextSpriteInPool() {
  5120. if ( _spriteCount === _spritePoolLength ) {
  5121. var sprite = new THREE.RenderableSprite();
  5122. _spritePool.push( sprite );
  5123. _spritePoolLength ++;
  5124. _spriteCount ++
  5125. return sprite;
  5126. }
  5127. return _spritePool[ _spriteCount ++ ];
  5128. }
  5129. //
  5130. function painterSort( a, b ) {
  5131. if ( a.z !== b.z ) {
  5132. return b.z - a.z;
  5133. } else if ( a.id !== b.id ) {
  5134. return a.id - b.id;
  5135. } else {
  5136. return 0;
  5137. }
  5138. }
  5139. function clipLine( s1, s2 ) {
  5140. var alpha1 = 0, alpha2 = 1,
  5141. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5142. // Z = -1 and Z = +1, respectively.
  5143. bc1near = s1.z + s1.w,
  5144. bc2near = s2.z + s2.w,
  5145. bc1far = - s1.z + s1.w,
  5146. bc2far = - s2.z + s2.w;
  5147. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5148. // Both vertices lie entirely within all clip planes.
  5149. return true;
  5150. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5151. // Both vertices lie entirely outside one of the clip planes.
  5152. return false;
  5153. } else {
  5154. // The line segment spans at least one clip plane.
  5155. if ( bc1near < 0 ) {
  5156. // v1 lies outside the near plane, v2 inside
  5157. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5158. } else if ( bc2near < 0 ) {
  5159. // v2 lies outside the near plane, v1 inside
  5160. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5161. }
  5162. if ( bc1far < 0 ) {
  5163. // v1 lies outside the far plane, v2 inside
  5164. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5165. } else if ( bc2far < 0 ) {
  5166. // v2 lies outside the far plane, v2 inside
  5167. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5168. }
  5169. if ( alpha2 < alpha1 ) {
  5170. // The line segment spans two boundaries, but is outside both of them.
  5171. // (This can't happen when we're only clipping against just near/far but good
  5172. // to leave the check here for future usage if other clip planes are added.)
  5173. return false;
  5174. } else {
  5175. // Update the s1 and s2 vertices to match the clipped line segment.
  5176. s1.lerp( s2, alpha1 );
  5177. s2.lerp( s1, 1 - alpha2 );
  5178. return true;
  5179. }
  5180. }
  5181. }
  5182. };
  5183. /**
  5184. * @author mrdoob / http://mrdoob.com/
  5185. * @author alteredq / http://alteredqualia.com/
  5186. */
  5187. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5188. this.a = a;
  5189. this.b = b;
  5190. this.c = c;
  5191. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5192. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5193. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5194. this.vertexColors = color instanceof Array ? color : [];
  5195. this.vertexTangents = [];
  5196. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5197. };
  5198. THREE.Face3.prototype = {
  5199. constructor: THREE.Face3,
  5200. clone: function () {
  5201. var face = new THREE.Face3( this.a, this.b, this.c );
  5202. face.normal.copy( this.normal );
  5203. face.color.copy( this.color );
  5204. face.materialIndex = this.materialIndex;
  5205. var i, il;
  5206. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5207. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5208. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5209. return face;
  5210. }
  5211. };
  5212. /**
  5213. * @author mrdoob / http://mrdoob.com/
  5214. */
  5215. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5216. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5217. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5218. };
  5219. /**
  5220. * @author alteredq / http://alteredqualia.com/
  5221. */
  5222. THREE.BufferGeometry = function () {
  5223. this.id = THREE.GeometryIdCount ++;
  5224. this.uuid = THREE.Math.generateUUID();
  5225. this.name = '';
  5226. this.attributes = {};
  5227. this.offsets = [];
  5228. this.boundingBox = null;
  5229. this.boundingSphere = null;
  5230. };
  5231. THREE.BufferGeometry.prototype = {
  5232. constructor: THREE.BufferGeometry,
  5233. addAttribute: function ( name, array, itemSize ) {
  5234. if ( arguments.length === 4 ) {
  5235. console.warn( 'DEPRECATED: BufferGeometry.addAttribute() now accepts only 3 arguments ( name, array, itemSize )' );
  5236. this.attributes[ arguments[ 0 ] ] = {
  5237. array: new arguments[ 1 ]( arguments[ 2 ] * arguments[ 3 ] ),
  5238. itemSize: arguments[ 3 ]
  5239. };
  5240. } else {
  5241. this.attributes[ name ] = {
  5242. array: array,
  5243. itemSize: itemSize
  5244. };
  5245. }
  5246. },
  5247. getAttribute: function ( name ) {
  5248. return this.attributes[ name ];
  5249. },
  5250. addDrawCall: function ( start, count, indexOffset ) {
  5251. this.offsets.push( {
  5252. start: start,
  5253. count: count,
  5254. index: indexOffset !== undefined ? indexOffset : 0
  5255. } );
  5256. },
  5257. applyMatrix: function ( matrix ) {
  5258. var position = this.attributes.position;
  5259. if ( position !== undefined ) {
  5260. matrix.applyToVector3Array( position.array );
  5261. position.needsUpdate = true;
  5262. }
  5263. var normal = this.attributes.normal;
  5264. if ( normal !== undefined ) {
  5265. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5266. normalMatrix.applyToVector3Array( normal.array );
  5267. normal.needsUpdate = true;
  5268. }
  5269. },
  5270. computeBoundingBox: function () {
  5271. if ( this.boundingBox === null ) {
  5272. this.boundingBox = new THREE.Box3();
  5273. }
  5274. var positions = this.attributes[ "position" ].array;
  5275. if ( positions ) {
  5276. var bb = this.boundingBox;
  5277. if( positions.length >= 3 ) {
  5278. bb.min.x = bb.max.x = positions[ 0 ];
  5279. bb.min.y = bb.max.y = positions[ 1 ];
  5280. bb.min.z = bb.max.z = positions[ 2 ];
  5281. }
  5282. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5283. var x = positions[ i ];
  5284. var y = positions[ i + 1 ];
  5285. var z = positions[ i + 2 ];
  5286. // bounding box
  5287. if ( x < bb.min.x ) {
  5288. bb.min.x = x;
  5289. } else if ( x > bb.max.x ) {
  5290. bb.max.x = x;
  5291. }
  5292. if ( y < bb.min.y ) {
  5293. bb.min.y = y;
  5294. } else if ( y > bb.max.y ) {
  5295. bb.max.y = y;
  5296. }
  5297. if ( z < bb.min.z ) {
  5298. bb.min.z = z;
  5299. } else if ( z > bb.max.z ) {
  5300. bb.max.z = z;
  5301. }
  5302. }
  5303. }
  5304. if ( positions === undefined || positions.length === 0 ) {
  5305. this.boundingBox.min.set( 0, 0, 0 );
  5306. this.boundingBox.max.set( 0, 0, 0 );
  5307. }
  5308. },
  5309. computeBoundingSphere: function () {
  5310. var box = new THREE.Box3();
  5311. var vector = new THREE.Vector3();
  5312. return function () {
  5313. if ( this.boundingSphere === null ) {
  5314. this.boundingSphere = new THREE.Sphere();
  5315. }
  5316. var positions = this.attributes[ "position" ].array;
  5317. if ( positions ) {
  5318. box.makeEmpty();
  5319. var center = this.boundingSphere.center;
  5320. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5321. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5322. box.addPoint( vector );
  5323. }
  5324. box.center( center );
  5325. var maxRadiusSq = 0;
  5326. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5327. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5328. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5329. }
  5330. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5331. }
  5332. }
  5333. }(),
  5334. computeVertexNormals: function () {
  5335. if ( this.attributes[ "position" ] ) {
  5336. var i, il;
  5337. var j, jl;
  5338. var nVertexElements = this.attributes[ "position" ].array.length;
  5339. if ( this.attributes[ "normal" ] === undefined ) {
  5340. this.attributes[ "normal" ] = {
  5341. itemSize: 3,
  5342. array: new Float32Array( nVertexElements )
  5343. };
  5344. } else {
  5345. // reset existing normals to zero
  5346. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5347. this.attributes[ "normal" ].array[ i ] = 0;
  5348. }
  5349. }
  5350. var positions = this.attributes[ "position" ].array;
  5351. var normals = this.attributes[ "normal" ].array;
  5352. var vA, vB, vC, x, y, z,
  5353. pA = new THREE.Vector3(),
  5354. pB = new THREE.Vector3(),
  5355. pC = new THREE.Vector3(),
  5356. cb = new THREE.Vector3(),
  5357. ab = new THREE.Vector3();
  5358. // indexed elements
  5359. if ( this.attributes[ "index" ] ) {
  5360. var indices = this.attributes[ "index" ].array;
  5361. var offsets = this.offsets;
  5362. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5363. var start = offsets[ j ].start;
  5364. var count = offsets[ j ].count;
  5365. var index = offsets[ j ].index;
  5366. for ( i = start, il = start + count; i < il; i += 3 ) {
  5367. vA = index + indices[ i ];
  5368. vB = index + indices[ i + 1 ];
  5369. vC = index + indices[ i + 2 ];
  5370. x = positions[ vA * 3 ];
  5371. y = positions[ vA * 3 + 1 ];
  5372. z = positions[ vA * 3 + 2 ];
  5373. pA.set( x, y, z );
  5374. x = positions[ vB * 3 ];
  5375. y = positions[ vB * 3 + 1 ];
  5376. z = positions[ vB * 3 + 2 ];
  5377. pB.set( x, y, z );
  5378. x = positions[ vC * 3 ];
  5379. y = positions[ vC * 3 + 1 ];
  5380. z = positions[ vC * 3 + 2 ];
  5381. pC.set( x, y, z );
  5382. cb.subVectors( pC, pB );
  5383. ab.subVectors( pA, pB );
  5384. cb.cross( ab );
  5385. normals[ vA * 3 ] += cb.x;
  5386. normals[ vA * 3 + 1 ] += cb.y;
  5387. normals[ vA * 3 + 2 ] += cb.z;
  5388. normals[ vB * 3 ] += cb.x;
  5389. normals[ vB * 3 + 1 ] += cb.y;
  5390. normals[ vB * 3 + 2 ] += cb.z;
  5391. normals[ vC * 3 ] += cb.x;
  5392. normals[ vC * 3 + 1 ] += cb.y;
  5393. normals[ vC * 3 + 2 ] += cb.z;
  5394. }
  5395. }
  5396. // non-indexed elements (unconnected triangle soup)
  5397. } else {
  5398. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5399. x = positions[ i ];
  5400. y = positions[ i + 1 ];
  5401. z = positions[ i + 2 ];
  5402. pA.set( x, y, z );
  5403. x = positions[ i + 3 ];
  5404. y = positions[ i + 4 ];
  5405. z = positions[ i + 5 ];
  5406. pB.set( x, y, z );
  5407. x = positions[ i + 6 ];
  5408. y = positions[ i + 7 ];
  5409. z = positions[ i + 8 ];
  5410. pC.set( x, y, z );
  5411. cb.subVectors( pC, pB );
  5412. ab.subVectors( pA, pB );
  5413. cb.cross( ab );
  5414. normals[ i ] = cb.x;
  5415. normals[ i + 1 ] = cb.y;
  5416. normals[ i + 2 ] = cb.z;
  5417. normals[ i + 3 ] = cb.x;
  5418. normals[ i + 4 ] = cb.y;
  5419. normals[ i + 5 ] = cb.z;
  5420. normals[ i + 6 ] = cb.x;
  5421. normals[ i + 7 ] = cb.y;
  5422. normals[ i + 8 ] = cb.z;
  5423. }
  5424. }
  5425. this.normalizeNormals();
  5426. this.normalsNeedUpdate = true;
  5427. }
  5428. },
  5429. normalizeNormals: function () {
  5430. var normals = this.attributes[ "normal" ].array;
  5431. var x, y, z, n;
  5432. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5433. x = normals[ i ];
  5434. y = normals[ i + 1 ];
  5435. z = normals[ i + 2 ];
  5436. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5437. normals[ i ] *= n;
  5438. normals[ i + 1 ] *= n;
  5439. normals[ i + 2 ] *= n;
  5440. }
  5441. },
  5442. computeTangents: function () {
  5443. // based on http://www.terathon.com/code/tangent.html
  5444. // (per vertex tangents)
  5445. if ( this.attributes[ "index" ] === undefined ||
  5446. this.attributes[ "position" ] === undefined ||
  5447. this.attributes[ "normal" ] === undefined ||
  5448. this.attributes[ "uv" ] === undefined ) {
  5449. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5450. return;
  5451. }
  5452. var indices = this.attributes[ "index" ].array;
  5453. var positions = this.attributes[ "position" ].array;
  5454. var normals = this.attributes[ "normal" ].array;
  5455. var uvs = this.attributes[ "uv" ].array;
  5456. var nVertices = positions.length / 3;
  5457. if ( this.attributes[ "tangent" ] === undefined ) {
  5458. var nTangentElements = 4 * nVertices;
  5459. this.attributes[ "tangent" ] = {
  5460. itemSize: 4,
  5461. array: new Float32Array( nTangentElements )
  5462. };
  5463. }
  5464. var tangents = this.attributes[ "tangent" ].array;
  5465. var tan1 = [], tan2 = [];
  5466. for ( var k = 0; k < nVertices; k ++ ) {
  5467. tan1[ k ] = new THREE.Vector3();
  5468. tan2[ k ] = new THREE.Vector3();
  5469. }
  5470. var xA, yA, zA,
  5471. xB, yB, zB,
  5472. xC, yC, zC,
  5473. uA, vA,
  5474. uB, vB,
  5475. uC, vC,
  5476. x1, x2, y1, y2, z1, z2,
  5477. s1, s2, t1, t2, r;
  5478. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5479. function handleTriangle( a, b, c ) {
  5480. xA = positions[ a * 3 ];
  5481. yA = positions[ a * 3 + 1 ];
  5482. zA = positions[ a * 3 + 2 ];
  5483. xB = positions[ b * 3 ];
  5484. yB = positions[ b * 3 + 1 ];
  5485. zB = positions[ b * 3 + 2 ];
  5486. xC = positions[ c * 3 ];
  5487. yC = positions[ c * 3 + 1 ];
  5488. zC = positions[ c * 3 + 2 ];
  5489. uA = uvs[ a * 2 ];
  5490. vA = uvs[ a * 2 + 1 ];
  5491. uB = uvs[ b * 2 ];
  5492. vB = uvs[ b * 2 + 1 ];
  5493. uC = uvs[ c * 2 ];
  5494. vC = uvs[ c * 2 + 1 ];
  5495. x1 = xB - xA;
  5496. x2 = xC - xA;
  5497. y1 = yB - yA;
  5498. y2 = yC - yA;
  5499. z1 = zB - zA;
  5500. z2 = zC - zA;
  5501. s1 = uB - uA;
  5502. s2 = uC - uA;
  5503. t1 = vB - vA;
  5504. t2 = vC - vA;
  5505. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5506. sdir.set(
  5507. ( t2 * x1 - t1 * x2 ) * r,
  5508. ( t2 * y1 - t1 * y2 ) * r,
  5509. ( t2 * z1 - t1 * z2 ) * r
  5510. );
  5511. tdir.set(
  5512. ( s1 * x2 - s2 * x1 ) * r,
  5513. ( s1 * y2 - s2 * y1 ) * r,
  5514. ( s1 * z2 - s2 * z1 ) * r
  5515. );
  5516. tan1[ a ].add( sdir );
  5517. tan1[ b ].add( sdir );
  5518. tan1[ c ].add( sdir );
  5519. tan2[ a ].add( tdir );
  5520. tan2[ b ].add( tdir );
  5521. tan2[ c ].add( tdir );
  5522. }
  5523. var i, il;
  5524. var j, jl;
  5525. var iA, iB, iC;
  5526. var offsets = this.offsets;
  5527. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5528. var start = offsets[ j ].start;
  5529. var count = offsets[ j ].count;
  5530. var index = offsets[ j ].index;
  5531. for ( i = start, il = start + count; i < il; i += 3 ) {
  5532. iA = index + indices[ i ];
  5533. iB = index + indices[ i + 1 ];
  5534. iC = index + indices[ i + 2 ];
  5535. handleTriangle( iA, iB, iC );
  5536. }
  5537. }
  5538. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5539. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5540. var w, t, test;
  5541. function handleVertex( v ) {
  5542. n.x = normals[ v * 3 ];
  5543. n.y = normals[ v * 3 + 1 ];
  5544. n.z = normals[ v * 3 + 2 ];
  5545. n2.copy( n );
  5546. t = tan1[ v ];
  5547. // Gram-Schmidt orthogonalize
  5548. tmp.copy( t );
  5549. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5550. // Calculate handedness
  5551. tmp2.crossVectors( n2, t );
  5552. test = tmp2.dot( tan2[ v ] );
  5553. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5554. tangents[ v * 4 ] = tmp.x;
  5555. tangents[ v * 4 + 1 ] = tmp.y;
  5556. tangents[ v * 4 + 2 ] = tmp.z;
  5557. tangents[ v * 4 + 3 ] = w;
  5558. }
  5559. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5560. var start = offsets[ j ].start;
  5561. var count = offsets[ j ].count;
  5562. var index = offsets[ j ].index;
  5563. for ( i = start, il = start + count; i < il; i += 3 ) {
  5564. iA = index + indices[ i ];
  5565. iB = index + indices[ i + 1 ];
  5566. iC = index + indices[ i + 2 ];
  5567. handleVertex( iA );
  5568. handleVertex( iB );
  5569. handleVertex( iC );
  5570. }
  5571. }
  5572. },
  5573. /*
  5574. computeOffsets
  5575. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5576. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5577. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5578. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5579. */
  5580. computeOffsets: function(indexBufferSize) {
  5581. var size = indexBufferSize;
  5582. if(indexBufferSize === undefined)
  5583. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5584. var s = Date.now();
  5585. var indices = this.attributes['index'].array;
  5586. var vertices = this.attributes['position'].array;
  5587. var verticesCount = (vertices.length/3);
  5588. var facesCount = (indices.length/3);
  5589. /*
  5590. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5591. console.log("Faces to process: "+(indices.length/3));
  5592. console.log("Reordering "+verticesCount+" vertices.");
  5593. */
  5594. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5595. var indexPtr = 0;
  5596. var vertexPtr = 0;
  5597. var offsets = [ { start:0, count:0, index:0 } ];
  5598. var offset = offsets[0];
  5599. var duplicatedVertices = 0;
  5600. var newVerticeMaps = 0;
  5601. var faceVertices = new Int32Array(6);
  5602. var vertexMap = new Int32Array( vertices.length );
  5603. var revVertexMap = new Int32Array( vertices.length );
  5604. for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; }
  5605. /*
  5606. Traverse every face and reorder vertices in the proper offsets of 65k.
  5607. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5608. */
  5609. for(var findex = 0; findex < facesCount; findex++) {
  5610. newVerticeMaps = 0;
  5611. for(var vo = 0; vo < 3; vo++) {
  5612. var vid = indices[ findex*3 + vo ];
  5613. if(vertexMap[vid] == -1) {
  5614. //Unmapped vertice
  5615. faceVertices[vo*2] = vid;
  5616. faceVertices[vo*2+1] = -1;
  5617. newVerticeMaps++;
  5618. } else if(vertexMap[vid] < offset.index) {
  5619. //Reused vertices from previous block (duplicate)
  5620. faceVertices[vo*2] = vid;
  5621. faceVertices[vo*2+1] = -1;
  5622. duplicatedVertices++;
  5623. } else {
  5624. //Reused vertice in the current block
  5625. faceVertices[vo*2] = vid;
  5626. faceVertices[vo*2+1] = vertexMap[vid];
  5627. }
  5628. }
  5629. var faceMax = vertexPtr + newVerticeMaps;
  5630. if(faceMax > (offset.index + size)) {
  5631. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5632. offsets.push(new_offset);
  5633. offset = new_offset;
  5634. //Re-evaluate reused vertices in light of new offset.
  5635. for(var v = 0; v < 6; v+=2) {
  5636. var new_vid = faceVertices[v+1];
  5637. if(new_vid > -1 && new_vid < offset.index)
  5638. faceVertices[v+1] = -1;
  5639. }
  5640. }
  5641. //Reindex the face.
  5642. for(var v = 0; v < 6; v+=2) {
  5643. var vid = faceVertices[v];
  5644. var new_vid = faceVertices[v+1];
  5645. if(new_vid === -1)
  5646. new_vid = vertexPtr++;
  5647. vertexMap[vid] = new_vid;
  5648. revVertexMap[new_vid] = vid;
  5649. sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit
  5650. offset.count++;
  5651. }
  5652. }
  5653. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5654. this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr);
  5655. this.offsets = offsets;
  5656. /*
  5657. var orderTime = Date.now();
  5658. console.log("Reorder time: "+(orderTime-s)+"ms");
  5659. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5660. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5661. console.log("Draw offsets: "+offsets.length);
  5662. */
  5663. return offsets;
  5664. },
  5665. /*
  5666. reoderBuffers:
  5667. Reorder attributes based on a new indexBuffer and indexMap.
  5668. indexBuffer - Uint16Array of the new ordered indices.
  5669. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5670. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5671. */
  5672. reorderBuffers: function(indexBuffer, indexMap, vertexCount) {
  5673. /* Create a copy of all attributes for reordering. */
  5674. var sortedAttributes = {};
  5675. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5676. for( var attr in this.attributes ) {
  5677. if(attr == 'index')
  5678. continue;
  5679. var sourceArray = this.attributes[attr].array;
  5680. for ( var i = 0, il = types.length; i < il; i++ ) {
  5681. var type = types[i];
  5682. if (sourceArray instanceof type) {
  5683. sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
  5684. break;
  5685. }
  5686. }
  5687. }
  5688. /* Move attribute positions based on the new index map */
  5689. for(var new_vid = 0; new_vid < vertexCount; new_vid++) {
  5690. var vid = indexMap[new_vid];
  5691. for ( var attr in this.attributes ) {
  5692. if(attr == 'index')
  5693. continue;
  5694. var attrArray = this.attributes[attr].array;
  5695. var attrSize = this.attributes[attr].itemSize;
  5696. var sortedAttr = sortedAttributes[attr];
  5697. for(var k = 0; k < attrSize; k++)
  5698. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5699. }
  5700. }
  5701. /* Carry the new sorted buffers locally */
  5702. this.attributes['index'].array = indexBuffer;
  5703. for ( var attr in this.attributes ) {
  5704. if(attr == 'index')
  5705. continue;
  5706. this.attributes[attr].array = sortedAttributes[attr];
  5707. this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount;
  5708. }
  5709. },
  5710. clone: function () {
  5711. var geometry = new THREE.BufferGeometry();
  5712. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5713. for ( var attr in this.attributes ) {
  5714. var sourceAttr = this.attributes[ attr ];
  5715. var sourceArray = sourceAttr.array;
  5716. var attribute = {
  5717. itemSize: sourceAttr.itemSize,
  5718. array: null
  5719. };
  5720. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5721. var type = types[ i ];
  5722. if ( sourceArray instanceof type ) {
  5723. attribute.array = new type( sourceArray );
  5724. break;
  5725. }
  5726. }
  5727. geometry.attributes[ attr ] = attribute;
  5728. }
  5729. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5730. var offset = this.offsets[ i ];
  5731. geometry.offsets.push( {
  5732. start: offset.start,
  5733. index: offset.index,
  5734. count: offset.count
  5735. } );
  5736. }
  5737. return geometry;
  5738. },
  5739. dispose: function () {
  5740. this.dispatchEvent( { type: 'dispose' } );
  5741. }
  5742. };
  5743. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5744. /**
  5745. * @author mrdoob / http://mrdoob.com/
  5746. * @author kile / http://kile.stravaganza.org/
  5747. * @author alteredq / http://alteredqualia.com/
  5748. * @author mikael emtinger / http://gomo.se/
  5749. * @author zz85 / http://www.lab4games.net/zz85/blog
  5750. * @author bhouston / http://exocortex.com
  5751. */
  5752. THREE.Geometry = function () {
  5753. this.id = THREE.GeometryIdCount ++;
  5754. this.uuid = THREE.Math.generateUUID();
  5755. this.name = '';
  5756. this.vertices = [];
  5757. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  5758. this.faces = [];
  5759. this.faceVertexUvs = [[]];
  5760. this.morphTargets = [];
  5761. this.morphColors = [];
  5762. this.morphNormals = [];
  5763. this.skinWeights = [];
  5764. this.skinIndices = [];
  5765. this.lineDistances = [];
  5766. this.boundingBox = null;
  5767. this.boundingSphere = null;
  5768. this.hasTangents = false;
  5769. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5770. // update flags
  5771. this.verticesNeedUpdate = false;
  5772. this.elementsNeedUpdate = false;
  5773. this.uvsNeedUpdate = false;
  5774. this.normalsNeedUpdate = false;
  5775. this.tangentsNeedUpdate = false;
  5776. this.colorsNeedUpdate = false;
  5777. this.lineDistancesNeedUpdate = false;
  5778. this.buffersNeedUpdate = false;
  5779. };
  5780. THREE.Geometry.prototype = {
  5781. constructor: THREE.Geometry,
  5782. applyMatrix: function ( matrix ) {
  5783. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5784. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5785. var vertex = this.vertices[ i ];
  5786. vertex.applyMatrix4( matrix );
  5787. }
  5788. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5789. var face = this.faces[ i ];
  5790. face.normal.applyMatrix3( normalMatrix ).normalize();
  5791. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5792. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5793. }
  5794. }
  5795. if ( this.boundingBox instanceof THREE.Box3 ) {
  5796. this.computeBoundingBox();
  5797. }
  5798. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5799. this.computeBoundingSphere();
  5800. }
  5801. },
  5802. computeFaceNormals: function () {
  5803. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5804. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5805. var face = this.faces[ f ];
  5806. var vA = this.vertices[ face.a ];
  5807. var vB = this.vertices[ face.b ];
  5808. var vC = this.vertices[ face.c ];
  5809. cb.subVectors( vC, vB );
  5810. ab.subVectors( vA, vB );
  5811. cb.cross( ab );
  5812. cb.normalize();
  5813. face.normal.copy( cb );
  5814. }
  5815. },
  5816. computeVertexNormals: function ( areaWeighted ) {
  5817. var v, vl, f, fl, face, vertices;
  5818. vertices = new Array( this.vertices.length );
  5819. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5820. vertices[ v ] = new THREE.Vector3();
  5821. }
  5822. if ( areaWeighted ) {
  5823. // vertex normals weighted by triangle areas
  5824. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5825. var vA, vB, vC, vD;
  5826. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5827. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5828. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5829. face = this.faces[ f ];
  5830. vA = this.vertices[ face.a ];
  5831. vB = this.vertices[ face.b ];
  5832. vC = this.vertices[ face.c ];
  5833. cb.subVectors( vC, vB );
  5834. ab.subVectors( vA, vB );
  5835. cb.cross( ab );
  5836. vertices[ face.a ].add( cb );
  5837. vertices[ face.b ].add( cb );
  5838. vertices[ face.c ].add( cb );
  5839. }
  5840. } else {
  5841. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5842. face = this.faces[ f ];
  5843. vertices[ face.a ].add( face.normal );
  5844. vertices[ face.b ].add( face.normal );
  5845. vertices[ face.c ].add( face.normal );
  5846. }
  5847. }
  5848. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5849. vertices[ v ].normalize();
  5850. }
  5851. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5852. face = this.faces[ f ];
  5853. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5854. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5855. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5856. }
  5857. },
  5858. computeMorphNormals: function () {
  5859. var i, il, f, fl, face;
  5860. // save original normals
  5861. // - create temp variables on first access
  5862. // otherwise just copy (for faster repeated calls)
  5863. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5864. face = this.faces[ f ];
  5865. if ( ! face.__originalFaceNormal ) {
  5866. face.__originalFaceNormal = face.normal.clone();
  5867. } else {
  5868. face.__originalFaceNormal.copy( face.normal );
  5869. }
  5870. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5871. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5872. if ( ! face.__originalVertexNormals[ i ] ) {
  5873. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5874. } else {
  5875. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5876. }
  5877. }
  5878. }
  5879. // use temp geometry to compute face and vertex normals for each morph
  5880. var tmpGeo = new THREE.Geometry();
  5881. tmpGeo.faces = this.faces;
  5882. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5883. // create on first access
  5884. if ( ! this.morphNormals[ i ] ) {
  5885. this.morphNormals[ i ] = {};
  5886. this.morphNormals[ i ].faceNormals = [];
  5887. this.morphNormals[ i ].vertexNormals = [];
  5888. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5889. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5890. var faceNormal, vertexNormals;
  5891. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5892. face = this.faces[ f ];
  5893. faceNormal = new THREE.Vector3();
  5894. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5895. dstNormalsFace.push( faceNormal );
  5896. dstNormalsVertex.push( vertexNormals );
  5897. }
  5898. }
  5899. var morphNormals = this.morphNormals[ i ];
  5900. // set vertices to morph target
  5901. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5902. // compute morph normals
  5903. tmpGeo.computeFaceNormals();
  5904. tmpGeo.computeVertexNormals();
  5905. // store morph normals
  5906. var faceNormal, vertexNormals;
  5907. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5908. face = this.faces[ f ];
  5909. faceNormal = morphNormals.faceNormals[ f ];
  5910. vertexNormals = morphNormals.vertexNormals[ f ];
  5911. faceNormal.copy( face.normal );
  5912. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5913. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5914. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5915. }
  5916. }
  5917. // restore original normals
  5918. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5919. face = this.faces[ f ];
  5920. face.normal = face.__originalFaceNormal;
  5921. face.vertexNormals = face.__originalVertexNormals;
  5922. }
  5923. },
  5924. computeTangents: function () {
  5925. // based on http://www.terathon.com/code/tangent.html
  5926. // tangents go to vertices
  5927. var f, fl, v, vl, i, il, vertexIndex,
  5928. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5929. x1, x2, y1, y2, z1, z2,
  5930. s1, s2, t1, t2, r, t, test,
  5931. tan1 = [], tan2 = [],
  5932. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5933. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5934. n = new THREE.Vector3(), w;
  5935. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5936. tan1[ v ] = new THREE.Vector3();
  5937. tan2[ v ] = new THREE.Vector3();
  5938. }
  5939. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5940. vA = context.vertices[ a ];
  5941. vB = context.vertices[ b ];
  5942. vC = context.vertices[ c ];
  5943. uvA = uv[ ua ];
  5944. uvB = uv[ ub ];
  5945. uvC = uv[ uc ];
  5946. x1 = vB.x - vA.x;
  5947. x2 = vC.x - vA.x;
  5948. y1 = vB.y - vA.y;
  5949. y2 = vC.y - vA.y;
  5950. z1 = vB.z - vA.z;
  5951. z2 = vC.z - vA.z;
  5952. s1 = uvB.x - uvA.x;
  5953. s2 = uvC.x - uvA.x;
  5954. t1 = uvB.y - uvA.y;
  5955. t2 = uvC.y - uvA.y;
  5956. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5957. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5958. ( t2 * y1 - t1 * y2 ) * r,
  5959. ( t2 * z1 - t1 * z2 ) * r );
  5960. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5961. ( s1 * y2 - s2 * y1 ) * r,
  5962. ( s1 * z2 - s2 * z1 ) * r );
  5963. tan1[ a ].add( sdir );
  5964. tan1[ b ].add( sdir );
  5965. tan1[ c ].add( sdir );
  5966. tan2[ a ].add( tdir );
  5967. tan2[ b ].add( tdir );
  5968. tan2[ c ].add( tdir );
  5969. }
  5970. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5971. face = this.faces[ f ];
  5972. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5973. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5974. }
  5975. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5976. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5977. face = this.faces[ f ];
  5978. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5979. n.copy( face.vertexNormals[ i ] );
  5980. vertexIndex = face[ faceIndex[ i ] ];
  5981. t = tan1[ vertexIndex ];
  5982. // Gram-Schmidt orthogonalize
  5983. tmp.copy( t );
  5984. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5985. // Calculate handedness
  5986. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5987. test = tmp2.dot( tan2[ vertexIndex ] );
  5988. w = (test < 0.0) ? -1.0 : 1.0;
  5989. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5990. }
  5991. }
  5992. this.hasTangents = true;
  5993. },
  5994. computeLineDistances: function ( ) {
  5995. var d = 0;
  5996. var vertices = this.vertices;
  5997. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5998. if ( i > 0 ) {
  5999. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6000. }
  6001. this.lineDistances[ i ] = d;
  6002. }
  6003. },
  6004. computeBoundingBox: function () {
  6005. if ( this.boundingBox === null ) {
  6006. this.boundingBox = new THREE.Box3();
  6007. }
  6008. this.boundingBox.setFromPoints( this.vertices );
  6009. },
  6010. computeBoundingSphere: function () {
  6011. if ( this.boundingSphere === null ) {
  6012. this.boundingSphere = new THREE.Sphere();
  6013. }
  6014. this.boundingSphere.setFromPoints( this.vertices );
  6015. },
  6016. /*
  6017. * Checks for duplicate vertices with hashmap.
  6018. * Duplicated vertices are removed
  6019. * and faces' vertices are updated.
  6020. */
  6021. mergeVertices: function () {
  6022. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6023. var unique = [], changes = [];
  6024. var v, key;
  6025. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6026. var precision = Math.pow( 10, precisionPoints );
  6027. var i,il, face;
  6028. var indices, k, j, jl, u;
  6029. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6030. v = this.vertices[ i ];
  6031. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6032. if ( verticesMap[ key ] === undefined ) {
  6033. verticesMap[ key ] = i;
  6034. unique.push( this.vertices[ i ] );
  6035. changes[ i ] = unique.length - 1;
  6036. } else {
  6037. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6038. changes[ i ] = changes[ verticesMap[ key ] ];
  6039. }
  6040. };
  6041. // if faces are completely degenerate after merging vertices, we
  6042. // have to remove them from the geometry.
  6043. var faceIndicesToRemove = [];
  6044. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  6045. face = this.faces[ i ];
  6046. face.a = changes[ face.a ];
  6047. face.b = changes[ face.b ];
  6048. face.c = changes[ face.c ];
  6049. indices = [ face.a, face.b, face.c ];
  6050. var dupIndex = -1;
  6051. // if any duplicate vertices are found in a Face3
  6052. // we have to remove the face as nothing can be saved
  6053. for ( var n = 0; n < 3; n ++ ) {
  6054. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6055. dupIndex = n;
  6056. faceIndicesToRemove.push( i );
  6057. break;
  6058. }
  6059. }
  6060. }
  6061. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6062. var idx = faceIndicesToRemove[ i ];
  6063. this.faces.splice( idx, 1 );
  6064. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6065. this.faceVertexUvs[ j ].splice( idx, 1 );
  6066. }
  6067. }
  6068. // Use unique set of vertices
  6069. var diff = this.vertices.length - unique.length;
  6070. this.vertices = unique;
  6071. return diff;
  6072. },
  6073. // Geometry splitting
  6074. makeGroups: ( function () {
  6075. var geometryGroupCounter = 0;
  6076. return function ( usesFaceMaterial, maxVerticesInGroup ) {
  6077. var f, fl, face, materialIndex,
  6078. groupHash, hash_map = {};
  6079. var numMorphTargets = this.morphTargets.length;
  6080. var numMorphNormals = this.morphNormals.length;
  6081. this.geometryGroups = {};
  6082. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6083. face = this.faces[ f ];
  6084. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  6085. if ( ! ( materialIndex in hash_map ) ) {
  6086. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  6087. }
  6088. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6089. if ( ! ( groupHash in this.geometryGroups ) ) {
  6090. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6091. }
  6092. if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  6093. hash_map[ materialIndex ].counter += 1;
  6094. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6095. if ( ! ( groupHash in this.geometryGroups ) ) {
  6096. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6097. }
  6098. }
  6099. this.geometryGroups[ groupHash ].faces3.push( f );
  6100. this.geometryGroups[ groupHash ].vertices += 3;
  6101. }
  6102. this.geometryGroupsList = [];
  6103. for ( var g in this.geometryGroups ) {
  6104. this.geometryGroups[ g ].id = geometryGroupCounter ++;
  6105. this.geometryGroupsList.push( this.geometryGroups[ g ] );
  6106. }
  6107. };
  6108. } )(),
  6109. clone: function () {
  6110. var geometry = new THREE.Geometry();
  6111. var vertices = this.vertices;
  6112. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6113. geometry.vertices.push( vertices[ i ].clone() );
  6114. }
  6115. var faces = this.faces;
  6116. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6117. geometry.faces.push( faces[ i ].clone() );
  6118. }
  6119. var uvs = this.faceVertexUvs[ 0 ];
  6120. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  6121. var uv = uvs[ i ], uvCopy = [];
  6122. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6123. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6124. }
  6125. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  6126. }
  6127. return geometry;
  6128. },
  6129. dispose: function () {
  6130. this.dispatchEvent( { type: 'dispose' } );
  6131. }
  6132. };
  6133. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6134. THREE.GeometryIdCount = 0;
  6135. /**
  6136. * @author mrdoob / http://mrdoob.com/
  6137. */
  6138. THREE.Geometry2 = function ( size ) {
  6139. THREE.BufferGeometry.call( this );
  6140. this.addAttribute( 'position', new Float32Array( size * 3 ), 3 );
  6141. this.addAttribute( 'normal', new Float32Array( size * 3 ), 3 );
  6142. this.addAttribute( 'uv', new Float32Array( size * 2 ), 2 );
  6143. this.vertices = this.getAttribute( 'position' ).array;
  6144. this.normals = this.getAttribute( 'normal' ).array;
  6145. this.uvs = this.getAttribute( 'uv' ).array;
  6146. this.boundingBox = null;
  6147. this.boundingSphere = null;
  6148. };
  6149. THREE.Geometry2.prototype = Object.create( THREE.BufferGeometry.prototype );
  6150. /**
  6151. * @author mrdoob / http://mrdoob.com/
  6152. * @author mikael emtinger / http://gomo.se/
  6153. * @author WestLangley / http://github.com/WestLangley
  6154. */
  6155. THREE.Camera = function () {
  6156. THREE.Object3D.call( this );
  6157. this.matrixWorldInverse = new THREE.Matrix4();
  6158. this.projectionMatrix = new THREE.Matrix4();
  6159. };
  6160. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6161. THREE.Camera.prototype.lookAt = function () {
  6162. // This routine does not support cameras with rotated and/or translated parent(s)
  6163. var m1 = new THREE.Matrix4();
  6164. return function ( vector ) {
  6165. m1.lookAt( this.position, vector, this.up );
  6166. this.quaternion.setFromRotationMatrix( m1 );
  6167. };
  6168. }();
  6169. THREE.Camera.prototype.clone = function (camera) {
  6170. if ( camera === undefined ) camera = new THREE.Camera();
  6171. THREE.Object3D.prototype.clone.call( this, camera );
  6172. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6173. camera.projectionMatrix.copy( this.projectionMatrix );
  6174. return camera;
  6175. };
  6176. /**
  6177. * @author alteredq / http://alteredqualia.com/
  6178. */
  6179. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6180. THREE.Camera.call( this );
  6181. this.left = left;
  6182. this.right = right;
  6183. this.top = top;
  6184. this.bottom = bottom;
  6185. this.near = ( near !== undefined ) ? near : 0.1;
  6186. this.far = ( far !== undefined ) ? far : 2000;
  6187. this.updateProjectionMatrix();
  6188. };
  6189. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6190. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6191. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6192. };
  6193. THREE.OrthographicCamera.prototype.clone = function () {
  6194. var camera = new THREE.OrthographicCamera();
  6195. THREE.Camera.prototype.clone.call( this, camera );
  6196. camera.left = this.left;
  6197. camera.right = this.right;
  6198. camera.top = this.top;
  6199. camera.bottom = this.bottom;
  6200. camera.near = this.near;
  6201. camera.far = this.far;
  6202. return camera;
  6203. };
  6204. /**
  6205. * @author mrdoob / http://mrdoob.com/
  6206. * @author greggman / http://games.greggman.com/
  6207. * @author zz85 / http://www.lab4games.net/zz85/blog
  6208. */
  6209. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6210. THREE.Camera.call( this );
  6211. this.fov = fov !== undefined ? fov : 50;
  6212. this.aspect = aspect !== undefined ? aspect : 1;
  6213. this.near = near !== undefined ? near : 0.1;
  6214. this.far = far !== undefined ? far : 2000;
  6215. this.updateProjectionMatrix();
  6216. };
  6217. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6218. /**
  6219. * Uses Focal Length (in mm) to estimate and set FOV
  6220. * 35mm (fullframe) camera is used if frame size is not specified;
  6221. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6222. */
  6223. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6224. if ( frameHeight === undefined ) frameHeight = 24;
  6225. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6226. this.updateProjectionMatrix();
  6227. }
  6228. /**
  6229. * Sets an offset in a larger frustum. This is useful for multi-window or
  6230. * multi-monitor/multi-machine setups.
  6231. *
  6232. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6233. * the monitors are in grid like this
  6234. *
  6235. * +---+---+---+
  6236. * | A | B | C |
  6237. * +---+---+---+
  6238. * | D | E | F |
  6239. * +---+---+---+
  6240. *
  6241. * then for each monitor you would call it like this
  6242. *
  6243. * var w = 1920;
  6244. * var h = 1080;
  6245. * var fullWidth = w * 3;
  6246. * var fullHeight = h * 2;
  6247. *
  6248. * --A--
  6249. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6250. * --B--
  6251. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6252. * --C--
  6253. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6254. * --D--
  6255. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6256. * --E--
  6257. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6258. * --F--
  6259. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6260. *
  6261. * Note there is no reason monitors have to be the same size or in a grid.
  6262. */
  6263. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6264. this.fullWidth = fullWidth;
  6265. this.fullHeight = fullHeight;
  6266. this.x = x;
  6267. this.y = y;
  6268. this.width = width;
  6269. this.height = height;
  6270. this.updateProjectionMatrix();
  6271. };
  6272. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6273. if ( this.fullWidth ) {
  6274. var aspect = this.fullWidth / this.fullHeight;
  6275. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6276. var bottom = -top;
  6277. var left = aspect * bottom;
  6278. var right = aspect * top;
  6279. var width = Math.abs( right - left );
  6280. var height = Math.abs( top - bottom );
  6281. this.projectionMatrix.makeFrustum(
  6282. left + this.x * width / this.fullWidth,
  6283. left + ( this.x + this.width ) * width / this.fullWidth,
  6284. top - ( this.y + this.height ) * height / this.fullHeight,
  6285. top - this.y * height / this.fullHeight,
  6286. this.near,
  6287. this.far
  6288. );
  6289. } else {
  6290. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6291. }
  6292. };
  6293. THREE.PerspectiveCamera.prototype.clone = function () {
  6294. var camera = new THREE.PerspectiveCamera();
  6295. THREE.Camera.prototype.clone.call( this, camera );
  6296. camera.fov = this.fov;
  6297. camera.aspect = this.aspect;
  6298. camera.near = this.near;
  6299. camera.far = this.far;
  6300. return camera;
  6301. };
  6302. /**
  6303. * @author mrdoob / http://mrdoob.com/
  6304. * @author alteredq / http://alteredqualia.com/
  6305. */
  6306. THREE.Light = function ( color ) {
  6307. THREE.Object3D.call( this );
  6308. this.color = new THREE.Color( color );
  6309. };
  6310. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6311. THREE.Light.prototype.clone = function ( light ) {
  6312. if ( light === undefined ) light = new THREE.Light();
  6313. THREE.Object3D.prototype.clone.call( this, light );
  6314. light.color.copy( this.color );
  6315. return light;
  6316. };
  6317. /**
  6318. * @author mrdoob / http://mrdoob.com/
  6319. */
  6320. THREE.AmbientLight = function ( color ) {
  6321. THREE.Light.call( this, color );
  6322. };
  6323. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6324. THREE.AmbientLight.prototype.clone = function () {
  6325. var light = new THREE.AmbientLight();
  6326. THREE.Light.prototype.clone.call( this, light );
  6327. return light;
  6328. };
  6329. /**
  6330. * @author MPanknin / http://www.redplant.de/
  6331. * @author alteredq / http://alteredqualia.com/
  6332. */
  6333. THREE.AreaLight = function ( color, intensity ) {
  6334. THREE.Light.call( this, color );
  6335. this.normal = new THREE.Vector3( 0, -1, 0 );
  6336. this.right = new THREE.Vector3( 1, 0, 0 );
  6337. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6338. this.width = 1.0;
  6339. this.height = 1.0;
  6340. this.constantAttenuation = 1.5;
  6341. this.linearAttenuation = 0.5;
  6342. this.quadraticAttenuation = 0.1;
  6343. };
  6344. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6345. /**
  6346. * @author mrdoob / http://mrdoob.com/
  6347. * @author alteredq / http://alteredqualia.com/
  6348. */
  6349. THREE.DirectionalLight = function ( color, intensity ) {
  6350. THREE.Light.call( this, color );
  6351. this.position.set( 0, 1, 0 );
  6352. this.target = new THREE.Object3D();
  6353. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6354. this.castShadow = false;
  6355. this.onlyShadow = false;
  6356. //
  6357. this.shadowCameraNear = 50;
  6358. this.shadowCameraFar = 5000;
  6359. this.shadowCameraLeft = -500;
  6360. this.shadowCameraRight = 500;
  6361. this.shadowCameraTop = 500;
  6362. this.shadowCameraBottom = -500;
  6363. this.shadowCameraVisible = false;
  6364. this.shadowBias = 0;
  6365. this.shadowDarkness = 0.5;
  6366. this.shadowMapWidth = 512;
  6367. this.shadowMapHeight = 512;
  6368. //
  6369. this.shadowCascade = false;
  6370. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6371. this.shadowCascadeCount = 2;
  6372. this.shadowCascadeBias = [ 0, 0, 0 ];
  6373. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6374. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6375. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6376. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6377. this.shadowCascadeArray = [];
  6378. //
  6379. this.shadowMap = null;
  6380. this.shadowMapSize = null;
  6381. this.shadowCamera = null;
  6382. this.shadowMatrix = null;
  6383. };
  6384. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6385. THREE.DirectionalLight.prototype.clone = function () {
  6386. var light = new THREE.DirectionalLight();
  6387. THREE.Light.prototype.clone.call( this, light );
  6388. light.target = this.target.clone();
  6389. light.intensity = this.intensity;
  6390. light.castShadow = this.castShadow;
  6391. light.onlyShadow = this.onlyShadow;
  6392. //
  6393. light.shadowCameraNear = this.shadowCameraNear;
  6394. light.shadowCameraFar = this.shadowCameraFar;
  6395. light.shadowCameraLeft = this.shadowCameraLeft;
  6396. light.shadowCameraRight = this.shadowCameraRight;
  6397. light.shadowCameraTop = this.shadowCameraTop;
  6398. light.shadowCameraBottom = this.shadowCameraBottom;
  6399. light.shadowCameraVisible = this.shadowCameraVisible;
  6400. light.shadowBias = this.shadowBias;
  6401. light.shadowDarkness = this.shadowDarkness;
  6402. light.shadowMapWidth = this.shadowMapWidth;
  6403. light.shadowMapHeight = this.shadowMapHeight;
  6404. //
  6405. light.shadowCascade = this.shadowCascade;
  6406. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6407. light.shadowCascadeCount = this.shadowCascadeCount;
  6408. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6409. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6410. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6411. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6412. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6413. return light;
  6414. };
  6415. /**
  6416. * @author alteredq / http://alteredqualia.com/
  6417. */
  6418. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6419. THREE.Light.call( this, skyColor );
  6420. this.position.set( 0, 100, 0 );
  6421. this.groundColor = new THREE.Color( groundColor );
  6422. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6423. };
  6424. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6425. THREE.HemisphereLight.prototype.clone = function () {
  6426. var light = new THREE.HemisphereLight();
  6427. THREE.Light.prototype.clone.call( this, light );
  6428. light.groundColor.copy( this.groundColor );
  6429. light.intensity = this.intensity;
  6430. return light;
  6431. };
  6432. /**
  6433. * @author mrdoob / http://mrdoob.com/
  6434. */
  6435. THREE.PointLight = function ( color, intensity, distance ) {
  6436. THREE.Light.call( this, color );
  6437. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6438. this.distance = ( distance !== undefined ) ? distance : 0;
  6439. };
  6440. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6441. THREE.PointLight.prototype.clone = function () {
  6442. var light = new THREE.PointLight();
  6443. THREE.Light.prototype.clone.call( this, light );
  6444. light.intensity = this.intensity;
  6445. light.distance = this.distance;
  6446. return light;
  6447. };
  6448. /**
  6449. * @author alteredq / http://alteredqualia.com/
  6450. */
  6451. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6452. THREE.Light.call( this, color );
  6453. this.position.set( 0, 1, 0 );
  6454. this.target = new THREE.Object3D();
  6455. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6456. this.distance = ( distance !== undefined ) ? distance : 0;
  6457. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6458. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6459. this.castShadow = false;
  6460. this.onlyShadow = false;
  6461. //
  6462. this.shadowCameraNear = 50;
  6463. this.shadowCameraFar = 5000;
  6464. this.shadowCameraFov = 50;
  6465. this.shadowCameraVisible = false;
  6466. this.shadowBias = 0;
  6467. this.shadowDarkness = 0.5;
  6468. this.shadowMapWidth = 512;
  6469. this.shadowMapHeight = 512;
  6470. //
  6471. this.shadowMap = null;
  6472. this.shadowMapSize = null;
  6473. this.shadowCamera = null;
  6474. this.shadowMatrix = null;
  6475. };
  6476. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6477. THREE.SpotLight.prototype.clone = function () {
  6478. var light = new THREE.SpotLight();
  6479. THREE.Light.prototype.clone.call( this, light );
  6480. light.target = this.target.clone();
  6481. light.intensity = this.intensity;
  6482. light.distance = this.distance;
  6483. light.angle = this.angle;
  6484. light.exponent = this.exponent;
  6485. light.castShadow = this.castShadow;
  6486. light.onlyShadow = this.onlyShadow;
  6487. //
  6488. light.shadowCameraNear = this.shadowCameraNear;
  6489. light.shadowCameraFar = this.shadowCameraFar;
  6490. light.shadowCameraFov = this.shadowCameraFov;
  6491. light.shadowCameraVisible = this.shadowCameraVisible;
  6492. light.shadowBias = this.shadowBias;
  6493. light.shadowDarkness = this.shadowDarkness;
  6494. light.shadowMapWidth = this.shadowMapWidth;
  6495. light.shadowMapHeight = this.shadowMapHeight;
  6496. return light;
  6497. };
  6498. /**
  6499. * @author alteredq / http://alteredqualia.com/
  6500. */
  6501. THREE.Loader = function ( showStatus ) {
  6502. this.showStatus = showStatus;
  6503. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6504. this.onLoadStart = function () {};
  6505. this.onLoadProgress = function () {};
  6506. this.onLoadComplete = function () {};
  6507. };
  6508. THREE.Loader.prototype = {
  6509. constructor: THREE.Loader,
  6510. crossOrigin: undefined,
  6511. addStatusElement: function () {
  6512. var e = document.createElement( "div" );
  6513. e.style.position = "absolute";
  6514. e.style.right = "0px";
  6515. e.style.top = "0px";
  6516. e.style.fontSize = "0.8em";
  6517. e.style.textAlign = "left";
  6518. e.style.background = "rgba(0,0,0,0.25)";
  6519. e.style.color = "#fff";
  6520. e.style.width = "120px";
  6521. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6522. e.style.zIndex = 1000;
  6523. e.innerHTML = "Loading ...";
  6524. return e;
  6525. },
  6526. updateProgress: function ( progress ) {
  6527. var message = "Loaded ";
  6528. if ( progress.total ) {
  6529. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6530. } else {
  6531. message += ( progress.loaded / 1024 ).toFixed(2) + " KB";
  6532. }
  6533. this.statusDomElement.innerHTML = message;
  6534. },
  6535. extractUrlBase: function ( url ) {
  6536. var parts = url.split( '/' );
  6537. if ( parts.length === 1 ) return './';
  6538. parts.pop();
  6539. return parts.join( '/' ) + '/';
  6540. },
  6541. initMaterials: function ( materials, texturePath ) {
  6542. var array = [];
  6543. for ( var i = 0; i < materials.length; ++ i ) {
  6544. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6545. }
  6546. return array;
  6547. },
  6548. needsTangents: function ( materials ) {
  6549. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6550. var m = materials[ i ];
  6551. if ( m instanceof THREE.ShaderMaterial ) return true;
  6552. }
  6553. return false;
  6554. },
  6555. createMaterial: function ( m, texturePath ) {
  6556. var _this = this;
  6557. function is_pow2( n ) {
  6558. var l = Math.log( n ) / Math.LN2;
  6559. return Math.floor( l ) == l;
  6560. }
  6561. function nearest_pow2( n ) {
  6562. var l = Math.log( n ) / Math.LN2;
  6563. return Math.pow( 2, Math.round( l ) );
  6564. }
  6565. function load_image( where, url ) {
  6566. var image = new Image();
  6567. image.onload = function () {
  6568. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6569. var width = nearest_pow2( this.width );
  6570. var height = nearest_pow2( this.height );
  6571. where.image.width = width;
  6572. where.image.height = height;
  6573. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6574. } else {
  6575. where.image = this;
  6576. }
  6577. where.needsUpdate = true;
  6578. };
  6579. if ( _this.crossOrigin !== undefined ) image.crossOrigin = _this.crossOrigin;
  6580. image.src = url;
  6581. }
  6582. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6583. var isCompressed = /\.dds$/i.test( sourceFile );
  6584. var fullPath = texturePath + sourceFile;
  6585. if ( isCompressed ) {
  6586. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6587. where[ name ] = texture;
  6588. } else {
  6589. var texture = document.createElement( 'canvas' );
  6590. where[ name ] = new THREE.Texture( texture );
  6591. }
  6592. where[ name ].sourceFile = sourceFile;
  6593. if( repeat ) {
  6594. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6595. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6596. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6597. }
  6598. if ( offset ) {
  6599. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6600. }
  6601. if ( wrap ) {
  6602. var wrapMap = {
  6603. "repeat": THREE.RepeatWrapping,
  6604. "mirror": THREE.MirroredRepeatWrapping
  6605. }
  6606. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6607. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6608. }
  6609. if ( anisotropy ) {
  6610. where[ name ].anisotropy = anisotropy;
  6611. }
  6612. if ( ! isCompressed ) {
  6613. load_image( where[ name ], fullPath );
  6614. }
  6615. }
  6616. function rgb2hex( rgb ) {
  6617. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6618. }
  6619. // defaults
  6620. var mtype = "MeshLambertMaterial";
  6621. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6622. // parameters from model file
  6623. if ( m.shading ) {
  6624. var shading = m.shading.toLowerCase();
  6625. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6626. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6627. }
  6628. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6629. mpars.blending = THREE[ m.blending ];
  6630. }
  6631. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6632. mpars.transparent = m.transparent;
  6633. }
  6634. if ( m.depthTest !== undefined ) {
  6635. mpars.depthTest = m.depthTest;
  6636. }
  6637. if ( m.depthWrite !== undefined ) {
  6638. mpars.depthWrite = m.depthWrite;
  6639. }
  6640. if ( m.visible !== undefined ) {
  6641. mpars.visible = m.visible;
  6642. }
  6643. if ( m.flipSided !== undefined ) {
  6644. mpars.side = THREE.BackSide;
  6645. }
  6646. if ( m.doubleSided !== undefined ) {
  6647. mpars.side = THREE.DoubleSide;
  6648. }
  6649. if ( m.wireframe !== undefined ) {
  6650. mpars.wireframe = m.wireframe;
  6651. }
  6652. if ( m.vertexColors !== undefined ) {
  6653. if ( m.vertexColors === "face" ) {
  6654. mpars.vertexColors = THREE.FaceColors;
  6655. } else if ( m.vertexColors ) {
  6656. mpars.vertexColors = THREE.VertexColors;
  6657. }
  6658. }
  6659. // colors
  6660. if ( m.colorDiffuse ) {
  6661. mpars.color = rgb2hex( m.colorDiffuse );
  6662. } else if ( m.DbgColor ) {
  6663. mpars.color = m.DbgColor;
  6664. }
  6665. if ( m.colorSpecular ) {
  6666. mpars.specular = rgb2hex( m.colorSpecular );
  6667. }
  6668. if ( m.colorAmbient ) {
  6669. mpars.ambient = rgb2hex( m.colorAmbient );
  6670. }
  6671. // modifiers
  6672. if ( m.transparency ) {
  6673. mpars.opacity = m.transparency;
  6674. }
  6675. if ( m.specularCoef ) {
  6676. mpars.shininess = m.specularCoef;
  6677. }
  6678. // textures
  6679. if ( m.mapDiffuse && texturePath ) {
  6680. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6681. }
  6682. if ( m.mapLight && texturePath ) {
  6683. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6684. }
  6685. if ( m.mapBump && texturePath ) {
  6686. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6687. }
  6688. if ( m.mapNormal && texturePath ) {
  6689. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6690. }
  6691. if ( m.mapSpecular && texturePath ) {
  6692. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6693. }
  6694. //
  6695. if ( m.mapBumpScale ) {
  6696. mpars.bumpScale = m.mapBumpScale;
  6697. }
  6698. // special case for normal mapped material
  6699. if ( m.mapNormal ) {
  6700. var shader = THREE.ShaderLib[ "normalmap" ];
  6701. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6702. uniforms[ "tNormal" ].value = mpars.normalMap;
  6703. if ( m.mapNormalFactor ) {
  6704. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6705. }
  6706. if ( mpars.map ) {
  6707. uniforms[ "tDiffuse" ].value = mpars.map;
  6708. uniforms[ "enableDiffuse" ].value = true;
  6709. }
  6710. if ( mpars.specularMap ) {
  6711. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6712. uniforms[ "enableSpecular" ].value = true;
  6713. }
  6714. if ( mpars.lightMap ) {
  6715. uniforms[ "tAO" ].value = mpars.lightMap;
  6716. uniforms[ "enableAO" ].value = true;
  6717. }
  6718. // for the moment don't handle displacement texture
  6719. uniforms[ "diffuse" ].value.setHex( mpars.color );
  6720. uniforms[ "specular" ].value.setHex( mpars.specular );
  6721. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  6722. uniforms[ "shininess" ].value = mpars.shininess;
  6723. if ( mpars.opacity !== undefined ) {
  6724. uniforms[ "opacity" ].value = mpars.opacity;
  6725. }
  6726. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6727. var material = new THREE.ShaderMaterial( parameters );
  6728. if ( mpars.transparent ) {
  6729. material.transparent = true;
  6730. }
  6731. } else {
  6732. var material = new THREE[ mtype ]( mpars );
  6733. }
  6734. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6735. return material;
  6736. }
  6737. };
  6738. /**
  6739. * @author mrdoob / http://mrdoob.com/
  6740. */
  6741. THREE.XHRLoader = function ( manager ) {
  6742. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6743. };
  6744. THREE.XHRLoader.prototype = {
  6745. constructor: THREE.XHRLoader,
  6746. load: function ( url, onLoad, onProgress, onError ) {
  6747. var scope = this;
  6748. var request = new XMLHttpRequest();
  6749. if ( onLoad !== undefined ) {
  6750. request.addEventListener( 'load', function ( event ) {
  6751. onLoad( event.target.responseText );
  6752. scope.manager.itemEnd( url );
  6753. }, false );
  6754. }
  6755. if ( onProgress !== undefined ) {
  6756. request.addEventListener( 'progress', function ( event ) {
  6757. onProgress( event );
  6758. }, false );
  6759. }
  6760. if ( onError !== undefined ) {
  6761. request.addEventListener( 'error', function ( event ) {
  6762. onError( event );
  6763. }, false );
  6764. }
  6765. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6766. request.open( 'GET', url, true );
  6767. request.send( null );
  6768. scope.manager.itemStart( url );
  6769. },
  6770. setCrossOrigin: function ( value ) {
  6771. this.crossOrigin = value;
  6772. }
  6773. };
  6774. /**
  6775. * @author mrdoob / http://mrdoob.com/
  6776. */
  6777. THREE.ImageLoader = function ( manager ) {
  6778. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6779. };
  6780. THREE.ImageLoader.prototype = {
  6781. constructor: THREE.ImageLoader,
  6782. load: function ( url, onLoad, onProgress, onError ) {
  6783. var scope = this;
  6784. var image = document.createElement( 'img' );
  6785. if ( onLoad !== undefined ) {
  6786. image.addEventListener( 'load', function ( event ) {
  6787. scope.manager.itemEnd( url );
  6788. onLoad( this );
  6789. }, false );
  6790. }
  6791. if ( onProgress !== undefined ) {
  6792. image.addEventListener( 'progress', function ( event ) {
  6793. onProgress( event );
  6794. }, false );
  6795. }
  6796. if ( onError !== undefined ) {
  6797. image.addEventListener( 'error', function ( event ) {
  6798. onError( event );
  6799. }, false );
  6800. }
  6801. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6802. image.src = url;
  6803. scope.manager.itemStart( url );
  6804. return image;
  6805. },
  6806. setCrossOrigin: function ( value ) {
  6807. this.crossOrigin = value;
  6808. }
  6809. }
  6810. /**
  6811. * @author mrdoob / http://mrdoob.com/
  6812. * @author alteredq / http://alteredqualia.com/
  6813. */
  6814. THREE.JSONLoader = function ( showStatus ) {
  6815. THREE.Loader.call( this, showStatus );
  6816. this.withCredentials = false;
  6817. };
  6818. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6819. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6820. var scope = this;
  6821. // todo: unify load API to for easier SceneLoader use
  6822. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6823. this.onLoadStart();
  6824. this.loadAjaxJSON( this, url, callback, texturePath );
  6825. };
  6826. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6827. var xhr = new XMLHttpRequest();
  6828. var length = 0;
  6829. xhr.onreadystatechange = function () {
  6830. if ( xhr.readyState === xhr.DONE ) {
  6831. if ( xhr.status === 200 || xhr.status === 0 ) {
  6832. if ( xhr.responseText ) {
  6833. var json = JSON.parse( xhr.responseText );
  6834. if ( json.metadata.type === 'scene' ) {
  6835. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  6836. return;
  6837. }
  6838. var result = context.parse( json, texturePath );
  6839. callback( result.geometry, result.materials );
  6840. } else {
  6841. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  6842. }
  6843. // in context of more complex asset initialization
  6844. // do not block on single failed file
  6845. // maybe should go even one more level up
  6846. context.onLoadComplete();
  6847. } else {
  6848. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  6849. }
  6850. } else if ( xhr.readyState === xhr.LOADING ) {
  6851. if ( callbackProgress ) {
  6852. if ( length === 0 ) {
  6853. length = xhr.getResponseHeader( 'Content-Length' );
  6854. }
  6855. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6856. }
  6857. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6858. if ( callbackProgress !== undefined ) {
  6859. length = xhr.getResponseHeader( "Content-Length" );
  6860. }
  6861. }
  6862. };
  6863. xhr.open( "GET", url, true );
  6864. xhr.withCredentials = this.withCredentials;
  6865. xhr.send( null );
  6866. };
  6867. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6868. var scope = this,
  6869. geometry = new THREE.Geometry(),
  6870. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6871. parseModel( scale );
  6872. parseSkin();
  6873. parseMorphing( scale );
  6874. geometry.computeFaceNormals();
  6875. geometry.computeBoundingSphere();
  6876. function parseModel( scale ) {
  6877. function isBitSet( value, position ) {
  6878. return value & ( 1 << position );
  6879. }
  6880. var i, j, fi,
  6881. offset, zLength,
  6882. colorIndex, normalIndex, uvIndex, materialIndex,
  6883. type,
  6884. isQuad,
  6885. hasMaterial,
  6886. hasFaceVertexUv,
  6887. hasFaceNormal, hasFaceVertexNormal,
  6888. hasFaceColor, hasFaceVertexColor,
  6889. vertex, face, faceA, faceB, color, hex, normal,
  6890. uvLayer, uv, u, v,
  6891. faces = json.faces,
  6892. vertices = json.vertices,
  6893. normals = json.normals,
  6894. colors = json.colors,
  6895. nUvLayers = 0;
  6896. if ( json.uvs !== undefined ) {
  6897. // disregard empty arrays
  6898. for ( i = 0; i < json.uvs.length; i++ ) {
  6899. if ( json.uvs[ i ].length ) nUvLayers ++;
  6900. }
  6901. for ( i = 0; i < nUvLayers; i++ ) {
  6902. geometry.faceVertexUvs[ i ] = [];
  6903. }
  6904. }
  6905. offset = 0;
  6906. zLength = vertices.length;
  6907. while ( offset < zLength ) {
  6908. vertex = new THREE.Vector3();
  6909. vertex.x = vertices[ offset ++ ] * scale;
  6910. vertex.y = vertices[ offset ++ ] * scale;
  6911. vertex.z = vertices[ offset ++ ] * scale;
  6912. geometry.vertices.push( vertex );
  6913. }
  6914. offset = 0;
  6915. zLength = faces.length;
  6916. while ( offset < zLength ) {
  6917. type = faces[ offset ++ ];
  6918. isQuad = isBitSet( type, 0 );
  6919. hasMaterial = isBitSet( type, 1 );
  6920. hasFaceVertexUv = isBitSet( type, 3 );
  6921. hasFaceNormal = isBitSet( type, 4 );
  6922. hasFaceVertexNormal = isBitSet( type, 5 );
  6923. hasFaceColor = isBitSet( type, 6 );
  6924. hasFaceVertexColor = isBitSet( type, 7 );
  6925. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6926. if ( isQuad ) {
  6927. faceA = new THREE.Face3();
  6928. faceA.a = faces[ offset ];
  6929. faceA.b = faces[ offset + 1 ];
  6930. faceA.c = faces[ offset + 3 ];
  6931. faceB = new THREE.Face3();
  6932. faceB.a = faces[ offset + 1 ];
  6933. faceB.b = faces[ offset + 2 ];
  6934. faceB.c = faces[ offset + 3 ];
  6935. offset += 4;
  6936. if ( hasMaterial ) {
  6937. materialIndex = faces[ offset ++ ];
  6938. faceA.materialIndex = materialIndex;
  6939. faceB.materialIndex = materialIndex;
  6940. }
  6941. // to get face <=> uv index correspondence
  6942. fi = geometry.faces.length;
  6943. if ( hasFaceVertexUv ) {
  6944. for ( i = 0; i < nUvLayers; i++ ) {
  6945. uvLayer = json.uvs[ i ];
  6946. geometry.faceVertexUvs[ i ][ fi ] = [];
  6947. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6948. for ( j = 0; j < 4; j ++ ) {
  6949. uvIndex = faces[ offset ++ ];
  6950. u = uvLayer[ uvIndex * 2 ];
  6951. v = uvLayer[ uvIndex * 2 + 1 ];
  6952. uv = new THREE.Vector2( u, v );
  6953. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6954. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6955. }
  6956. }
  6957. }
  6958. if ( hasFaceNormal ) {
  6959. normalIndex = faces[ offset ++ ] * 3;
  6960. faceA.normal.set(
  6961. normals[ normalIndex ++ ],
  6962. normals[ normalIndex ++ ],
  6963. normals[ normalIndex ]
  6964. );
  6965. faceB.normal.copy( faceA.normal );
  6966. }
  6967. if ( hasFaceVertexNormal ) {
  6968. for ( i = 0; i < 4; i++ ) {
  6969. normalIndex = faces[ offset ++ ] * 3;
  6970. normal = new THREE.Vector3(
  6971. normals[ normalIndex ++ ],
  6972. normals[ normalIndex ++ ],
  6973. normals[ normalIndex ]
  6974. );
  6975. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6976. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6977. }
  6978. }
  6979. if ( hasFaceColor ) {
  6980. colorIndex = faces[ offset ++ ];
  6981. hex = colors[ colorIndex ];
  6982. faceA.color.setHex( hex );
  6983. faceB.color.setHex( hex );
  6984. }
  6985. if ( hasFaceVertexColor ) {
  6986. for ( i = 0; i < 4; i++ ) {
  6987. colorIndex = faces[ offset ++ ];
  6988. hex = colors[ colorIndex ];
  6989. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6990. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6991. }
  6992. }
  6993. geometry.faces.push( faceA );
  6994. geometry.faces.push( faceB );
  6995. } else {
  6996. face = new THREE.Face3();
  6997. face.a = faces[ offset ++ ];
  6998. face.b = faces[ offset ++ ];
  6999. face.c = faces[ offset ++ ];
  7000. if ( hasMaterial ) {
  7001. materialIndex = faces[ offset ++ ];
  7002. face.materialIndex = materialIndex;
  7003. }
  7004. // to get face <=> uv index correspondence
  7005. fi = geometry.faces.length;
  7006. if ( hasFaceVertexUv ) {
  7007. for ( i = 0; i < nUvLayers; i++ ) {
  7008. uvLayer = json.uvs[ i ];
  7009. geometry.faceVertexUvs[ i ][ fi ] = [];
  7010. for ( j = 0; j < 3; j ++ ) {
  7011. uvIndex = faces[ offset ++ ];
  7012. u = uvLayer[ uvIndex * 2 ];
  7013. v = uvLayer[ uvIndex * 2 + 1 ];
  7014. uv = new THREE.Vector2( u, v );
  7015. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7016. }
  7017. }
  7018. }
  7019. if ( hasFaceNormal ) {
  7020. normalIndex = faces[ offset ++ ] * 3;
  7021. face.normal.set(
  7022. normals[ normalIndex ++ ],
  7023. normals[ normalIndex ++ ],
  7024. normals[ normalIndex ]
  7025. );
  7026. }
  7027. if ( hasFaceVertexNormal ) {
  7028. for ( i = 0; i < 3; i++ ) {
  7029. normalIndex = faces[ offset ++ ] * 3;
  7030. normal = new THREE.Vector3(
  7031. normals[ normalIndex ++ ],
  7032. normals[ normalIndex ++ ],
  7033. normals[ normalIndex ]
  7034. );
  7035. face.vertexNormals.push( normal );
  7036. }
  7037. }
  7038. if ( hasFaceColor ) {
  7039. colorIndex = faces[ offset ++ ];
  7040. face.color.setHex( colors[ colorIndex ] );
  7041. }
  7042. if ( hasFaceVertexColor ) {
  7043. for ( i = 0; i < 3; i++ ) {
  7044. colorIndex = faces[ offset ++ ];
  7045. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7046. }
  7047. }
  7048. geometry.faces.push( face );
  7049. }
  7050. }
  7051. };
  7052. function parseSkin() {
  7053. if ( json.skinWeights ) {
  7054. for ( var i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  7055. var x = json.skinWeights[ i ];
  7056. var y = json.skinWeights[ i + 1 ];
  7057. var z = 0;
  7058. var w = 0;
  7059. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7060. }
  7061. }
  7062. if ( json.skinIndices ) {
  7063. for ( var i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  7064. var a = json.skinIndices[ i ];
  7065. var b = json.skinIndices[ i + 1 ];
  7066. var c = 0;
  7067. var d = 0;
  7068. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7069. }
  7070. }
  7071. geometry.bones = json.bones;
  7072. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7073. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7074. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7075. }
  7076. // could change this to json.animations[0] or remove completely
  7077. geometry.animation = json.animation;
  7078. geometry.animations = json.animations;
  7079. };
  7080. function parseMorphing( scale ) {
  7081. if ( json.morphTargets !== undefined ) {
  7082. var i, l, v, vl, dstVertices, srcVertices;
  7083. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7084. geometry.morphTargets[ i ] = {};
  7085. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7086. geometry.morphTargets[ i ].vertices = [];
  7087. dstVertices = geometry.morphTargets[ i ].vertices;
  7088. srcVertices = json.morphTargets [ i ].vertices;
  7089. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7090. var vertex = new THREE.Vector3();
  7091. vertex.x = srcVertices[ v ] * scale;
  7092. vertex.y = srcVertices[ v + 1 ] * scale;
  7093. vertex.z = srcVertices[ v + 2 ] * scale;
  7094. dstVertices.push( vertex );
  7095. }
  7096. }
  7097. }
  7098. if ( json.morphColors !== undefined ) {
  7099. var i, l, c, cl, dstColors, srcColors, color;
  7100. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  7101. geometry.morphColors[ i ] = {};
  7102. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7103. geometry.morphColors[ i ].colors = [];
  7104. dstColors = geometry.morphColors[ i ].colors;
  7105. srcColors = json.morphColors [ i ].colors;
  7106. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7107. color = new THREE.Color( 0xffaa00 );
  7108. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7109. dstColors.push( color );
  7110. }
  7111. }
  7112. }
  7113. };
  7114. if ( json.materials === undefined || json.materials.length === 0 ) {
  7115. return { geometry: geometry };
  7116. } else {
  7117. var materials = this.initMaterials( json.materials, texturePath );
  7118. if ( this.needsTangents( materials ) ) {
  7119. geometry.computeTangents();
  7120. }
  7121. return { geometry: geometry, materials: materials };
  7122. }
  7123. };
  7124. /**
  7125. * @author mrdoob / http://mrdoob.com/
  7126. */
  7127. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7128. var scope = this;
  7129. var loaded = 0, total = 0;
  7130. this.onLoad = onLoad;
  7131. this.onProgress = onProgress;
  7132. this.onError = onError;
  7133. this.itemStart = function ( url ) {
  7134. total ++;
  7135. };
  7136. this.itemEnd = function ( url ) {
  7137. loaded ++;
  7138. if ( scope.onProgress !== undefined ) {
  7139. scope.onProgress( url, loaded, total );
  7140. }
  7141. if ( loaded === total && scope.onLoad !== undefined ) {
  7142. scope.onLoad();
  7143. }
  7144. };
  7145. };
  7146. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7147. /**
  7148. * @author mrdoob / http://mrdoob.com/
  7149. */
  7150. THREE.BufferGeometryLoader = function ( manager ) {
  7151. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7152. };
  7153. THREE.BufferGeometryLoader.prototype = {
  7154. constructor: THREE.BufferGeometryLoader,
  7155. load: function ( url, onLoad, onProgress, onError ) {
  7156. var scope = this;
  7157. var loader = new THREE.XHRLoader();
  7158. loader.setCrossOrigin( this.crossOrigin );
  7159. loader.load( url, function ( text ) {
  7160. onLoad( scope.parse( JSON.parse( text ) ) );
  7161. } );
  7162. },
  7163. setCrossOrigin: function ( value ) {
  7164. this.crossOrigin = value;
  7165. },
  7166. parse: function ( json ) {
  7167. var geometry = new THREE.BufferGeometry();
  7168. var attributes = json.attributes;
  7169. var offsets = json.offsets;
  7170. var boundingSphere = json.boundingSphere;
  7171. for ( var key in attributes ) {
  7172. var attribute = attributes[ key ];
  7173. geometry.attributes[ key ] = {
  7174. itemSize: attribute.itemSize,
  7175. array: new self[ attribute.type ]( attribute.array )
  7176. }
  7177. }
  7178. if ( offsets !== undefined ) {
  7179. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7180. }
  7181. if ( boundingSphere !== undefined ) {
  7182. geometry.boundingSphere = new THREE.Sphere(
  7183. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7184. boundingSphere.radius
  7185. );
  7186. }
  7187. return geometry;
  7188. }
  7189. };
  7190. /**
  7191. * @author mrdoob / http://mrdoob.com/
  7192. */
  7193. THREE.Geometry2Loader = function ( manager ) {
  7194. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7195. };
  7196. THREE.Geometry2Loader.prototype = {
  7197. constructor: THREE.Geometry2Loader,
  7198. load: function ( url, onLoad, onProgress, onError ) {
  7199. var scope = this;
  7200. var loader = new THREE.XHRLoader();
  7201. loader.setCrossOrigin( this.crossOrigin );
  7202. loader.load( url, function ( text ) {
  7203. onLoad( scope.parse( JSON.parse( text ) ) );
  7204. } );
  7205. },
  7206. setCrossOrigin: function ( value ) {
  7207. this.crossOrigin = value;
  7208. },
  7209. parse: function ( json ) {
  7210. var geometry = new THREE.Geometry2( json.vertices.length / 3 );
  7211. var attributes = [ 'vertices', 'normals', 'uvs' ];
  7212. var boundingSphere = json.boundingSphere;
  7213. for ( var key in attributes ) {
  7214. var attribute = attributes[ key ];
  7215. geometry[ attribute ].set( json[ attribute ] );
  7216. }
  7217. if ( boundingSphere !== undefined ) {
  7218. geometry.boundingSphere = new THREE.Sphere(
  7219. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7220. boundingSphere.radius
  7221. );
  7222. }
  7223. return geometry;
  7224. }
  7225. };
  7226. /**
  7227. * @author mrdoob / http://mrdoob.com/
  7228. */
  7229. THREE.MaterialLoader = function ( manager ) {
  7230. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7231. };
  7232. THREE.MaterialLoader.prototype = {
  7233. constructor: THREE.MaterialLoader,
  7234. load: function ( url, onLoad, onProgress, onError ) {
  7235. var scope = this;
  7236. var loader = new THREE.XHRLoader();
  7237. loader.setCrossOrigin( this.crossOrigin );
  7238. loader.load( url, function ( text ) {
  7239. onLoad( scope.parse( JSON.parse( text ) ) );
  7240. } );
  7241. },
  7242. setCrossOrigin: function ( value ) {
  7243. this.crossOrigin = value;
  7244. },
  7245. parse: function ( json ) {
  7246. var material = new THREE[ json.type ];
  7247. if ( json.color !== undefined ) material.color.setHex( json.color );
  7248. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7249. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7250. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7251. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7252. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7253. if ( json.blending !== undefined ) material.blending = json.blending;
  7254. if ( json.side !== undefined ) material.side = json.side;
  7255. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7256. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7257. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7258. if ( json.materials !== undefined ) {
  7259. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7260. material.materials.push( this.parse( json.materials[ i ] ) );
  7261. }
  7262. }
  7263. return material;
  7264. }
  7265. };
  7266. /**
  7267. * @author mrdoob / http://mrdoob.com/
  7268. */
  7269. THREE.ObjectLoader = function ( manager ) {
  7270. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7271. };
  7272. THREE.ObjectLoader.prototype = {
  7273. constructor: THREE.ObjectLoader,
  7274. load: function ( url, onLoad, onProgress, onError ) {
  7275. var scope = this;
  7276. var loader = new THREE.XHRLoader( scope.manager );
  7277. loader.setCrossOrigin( this.crossOrigin );
  7278. loader.load( url, function ( text ) {
  7279. onLoad( scope.parse( JSON.parse( text ) ) );
  7280. } );
  7281. },
  7282. setCrossOrigin: function ( value ) {
  7283. this.crossOrigin = value;
  7284. },
  7285. parse: function ( json ) {
  7286. var geometries = this.parseGeometries( json.geometries );
  7287. var materials = this.parseMaterials( json.materials );
  7288. var object = this.parseObject( json.object, geometries, materials );
  7289. return object;
  7290. },
  7291. parseGeometries: function ( json ) {
  7292. var geometries = {};
  7293. if ( json !== undefined ) {
  7294. var geometryLoader = new THREE.JSONLoader();
  7295. var geometry2Loader = new THREE.Geometry2Loader();
  7296. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7297. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7298. var geometry;
  7299. var data = json[ i ];
  7300. switch ( data.type ) {
  7301. case 'PlaneGeometry':
  7302. geometry = new THREE.PlaneGeometry(
  7303. data.width,
  7304. data.height,
  7305. data.widthSegments,
  7306. data.heightSegments
  7307. );
  7308. break;
  7309. case 'BoxGeometry':
  7310. case 'CubeGeometry': // DEPRECATED
  7311. geometry = new THREE.BoxGeometry(
  7312. data.width,
  7313. data.height,
  7314. data.depth,
  7315. data.widthSegments,
  7316. data.heightSegments,
  7317. data.depthSegments
  7318. );
  7319. break;
  7320. case 'CircleGeometry':
  7321. geometry = new THREE.CircleGeometry(
  7322. data.radius,
  7323. data.segments
  7324. );
  7325. break;
  7326. case 'CylinderGeometry':
  7327. geometry = new THREE.CylinderGeometry(
  7328. data.radiusTop,
  7329. data.radiusBottom,
  7330. data.height,
  7331. data.radialSegments,
  7332. data.heightSegments,
  7333. data.openEnded
  7334. );
  7335. break;
  7336. case 'SphereGeometry':
  7337. geometry = new THREE.SphereGeometry(
  7338. data.radius,
  7339. data.widthSegments,
  7340. data.heightSegments,
  7341. data.phiStart,
  7342. data.phiLength,
  7343. data.thetaStart,
  7344. data.thetaLength
  7345. );
  7346. break;
  7347. case 'IcosahedronGeometry':
  7348. geometry = new THREE.IcosahedronGeometry(
  7349. data.radius,
  7350. data.detail
  7351. );
  7352. break;
  7353. case 'TorusGeometry':
  7354. geometry = new THREE.TorusGeometry(
  7355. data.radius,
  7356. data.tube,
  7357. data.radialSegments,
  7358. data.tubularSegments,
  7359. data.arc
  7360. );
  7361. break;
  7362. case 'TorusKnotGeometry':
  7363. geometry = new THREE.TorusKnotGeometry(
  7364. data.radius,
  7365. data.tube,
  7366. data.radialSegments,
  7367. data.tubularSegments,
  7368. data.p,
  7369. data.q,
  7370. data.heightScale
  7371. );
  7372. break;
  7373. case 'BufferGeometry':
  7374. geometry = bufferGeometryLoader.parse( data.data );
  7375. break;
  7376. case 'Geometry2':
  7377. geometry = geometry2Loader.parse( data.data );
  7378. break;
  7379. case 'Geometry':
  7380. geometry = geometryLoader.parse( data.data ).geometry;
  7381. break;
  7382. }
  7383. geometry.uuid = data.uuid;
  7384. if ( data.name !== undefined ) geometry.name = data.name;
  7385. geometries[ data.uuid ] = geometry;
  7386. }
  7387. }
  7388. return geometries;
  7389. },
  7390. parseMaterials: function ( json ) {
  7391. var materials = {};
  7392. if ( json !== undefined ) {
  7393. var loader = new THREE.MaterialLoader();
  7394. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7395. var data = json[ i ];
  7396. var material = loader.parse( data );
  7397. material.uuid = data.uuid;
  7398. if ( data.name !== undefined ) material.name = data.name;
  7399. materials[ data.uuid ] = material;
  7400. }
  7401. }
  7402. return materials;
  7403. },
  7404. parseObject: function () {
  7405. var matrix = new THREE.Matrix4();
  7406. return function ( data, geometries, materials ) {
  7407. var object;
  7408. switch ( data.type ) {
  7409. case 'Scene':
  7410. object = new THREE.Scene();
  7411. break;
  7412. case 'PerspectiveCamera':
  7413. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7414. break;
  7415. case 'OrthographicCamera':
  7416. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7417. break;
  7418. case 'AmbientLight':
  7419. object = new THREE.AmbientLight( data.color );
  7420. break;
  7421. case 'DirectionalLight':
  7422. object = new THREE.DirectionalLight( data.color, data.intensity );
  7423. break;
  7424. case 'PointLight':
  7425. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7426. break;
  7427. case 'SpotLight':
  7428. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7429. break;
  7430. case 'HemisphereLight':
  7431. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7432. break;
  7433. case 'Mesh':
  7434. var geometry = geometries[ data.geometry ];
  7435. var material = materials[ data.material ];
  7436. if ( geometry === undefined ) {
  7437. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7438. }
  7439. if ( material === undefined ) {
  7440. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7441. }
  7442. object = new THREE.Mesh( geometry, material );
  7443. break;
  7444. case 'Sprite':
  7445. var material = materials[ data.material ];
  7446. if ( material === undefined ) {
  7447. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7448. }
  7449. object = new THREE.Sprite( material );
  7450. break;
  7451. default:
  7452. object = new THREE.Object3D();
  7453. }
  7454. object.uuid = data.uuid;
  7455. if ( data.name !== undefined ) object.name = data.name;
  7456. if ( data.matrix !== undefined ) {
  7457. matrix.fromArray( data.matrix );
  7458. matrix.decompose( object.position, object.quaternion, object.scale );
  7459. } else {
  7460. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7461. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7462. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7463. }
  7464. if ( data.visible !== undefined ) object.visible = data.visible;
  7465. if ( data.userData !== undefined ) object.userData = data.userData;
  7466. if ( data.children !== undefined ) {
  7467. for ( var child in data.children ) {
  7468. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7469. }
  7470. }
  7471. return object;
  7472. }
  7473. }()
  7474. };
  7475. /**
  7476. * @author alteredq / http://alteredqualia.com/
  7477. */
  7478. THREE.SceneLoader = function () {
  7479. this.onLoadStart = function () {};
  7480. this.onLoadProgress = function() {};
  7481. this.onLoadComplete = function () {};
  7482. this.callbackSync = function () {};
  7483. this.callbackProgress = function () {};
  7484. this.geometryHandlers = {};
  7485. this.hierarchyHandlers = {};
  7486. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  7487. };
  7488. THREE.SceneLoader.prototype = {
  7489. constructor: THREE.SceneLoader,
  7490. load: function ( url, onLoad, onProgress, onError ) {
  7491. var scope = this;
  7492. var loader = new THREE.XHRLoader( scope.manager );
  7493. loader.setCrossOrigin( this.crossOrigin );
  7494. loader.load( url, function ( text ) {
  7495. scope.parse( JSON.parse( text ), onLoad, url );
  7496. } );
  7497. },
  7498. setCrossOrigin: function ( value ) {
  7499. this.crossOrigin = value;
  7500. },
  7501. addGeometryHandler: function ( typeID, loaderClass ) {
  7502. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7503. },
  7504. addHierarchyHandler: function ( typeID, loaderClass ) {
  7505. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7506. },
  7507. parse: function ( json, callbackFinished, url ) {
  7508. var scope = this;
  7509. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7510. var geometry, material, camera, fog,
  7511. texture, images, color,
  7512. light, hex, intensity,
  7513. counter_models, counter_textures,
  7514. total_models, total_textures,
  7515. result;
  7516. var target_array = [];
  7517. var data = json;
  7518. // async geometry loaders
  7519. for ( var typeID in this.geometryHandlers ) {
  7520. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7521. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7522. }
  7523. // async hierachy loaders
  7524. for ( var typeID in this.hierarchyHandlers ) {
  7525. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7526. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7527. }
  7528. counter_models = 0;
  7529. counter_textures = 0;
  7530. result = {
  7531. scene: new THREE.Scene(),
  7532. geometries: {},
  7533. face_materials: {},
  7534. materials: {},
  7535. textures: {},
  7536. objects: {},
  7537. cameras: {},
  7538. lights: {},
  7539. fogs: {},
  7540. empties: {},
  7541. groups: {}
  7542. };
  7543. if ( data.transform ) {
  7544. var position = data.transform.position,
  7545. rotation = data.transform.rotation,
  7546. scale = data.transform.scale;
  7547. if ( position ) {
  7548. result.scene.position.fromArray( position );
  7549. }
  7550. if ( rotation ) {
  7551. result.scene.rotation.fromArray( rotation );
  7552. }
  7553. if ( scale ) {
  7554. result.scene.scale.fromArray( scale );
  7555. }
  7556. if ( position || rotation || scale ) {
  7557. result.scene.updateMatrix();
  7558. result.scene.updateMatrixWorld();
  7559. }
  7560. }
  7561. function get_url( source_url, url_type ) {
  7562. if ( url_type == "relativeToHTML" ) {
  7563. return source_url;
  7564. } else {
  7565. return urlBase + source_url;
  7566. }
  7567. };
  7568. // toplevel loader function, delegates to handle_children
  7569. function handle_objects() {
  7570. handle_children( result.scene, data.objects );
  7571. }
  7572. // handle all the children from the loaded json and attach them to given parent
  7573. function handle_children( parent, children ) {
  7574. var mat, dst, pos, rot, scl, quat;
  7575. for ( var objID in children ) {
  7576. // check by id if child has already been handled,
  7577. // if not, create new object
  7578. var object = result.objects[ objID ];
  7579. var objJSON = children[ objID ];
  7580. if ( object === undefined ) {
  7581. // meshes
  7582. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7583. if ( objJSON.loading === undefined ) {
  7584. var reservedTypes = {
  7585. "type": 1, "url": 1, "material": 1,
  7586. "position": 1, "rotation": 1, "scale" : 1,
  7587. "visible": 1, "children": 1, "userData": 1,
  7588. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7589. };
  7590. var loaderParameters = {};
  7591. for ( var parType in objJSON ) {
  7592. if ( ! ( parType in reservedTypes ) ) {
  7593. loaderParameters[ parType ] = objJSON[ parType ];
  7594. }
  7595. }
  7596. material = result.materials[ objJSON.material ];
  7597. objJSON.loading = true;
  7598. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7599. // ColladaLoader
  7600. if ( loader.options ) {
  7601. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7602. // UTF8Loader
  7603. // OBJLoader
  7604. } else {
  7605. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7606. }
  7607. }
  7608. } else if ( objJSON.geometry !== undefined ) {
  7609. geometry = result.geometries[ objJSON.geometry ];
  7610. // geometry already loaded
  7611. if ( geometry ) {
  7612. var needsTangents = false;
  7613. material = result.materials[ objJSON.material ];
  7614. needsTangents = material instanceof THREE.ShaderMaterial;
  7615. pos = objJSON.position;
  7616. rot = objJSON.rotation;
  7617. scl = objJSON.scale;
  7618. mat = objJSON.matrix;
  7619. quat = objJSON.quaternion;
  7620. // use materials from the model file
  7621. // if there is no material specified in the object
  7622. if ( ! objJSON.material ) {
  7623. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7624. }
  7625. // use materials from the model file
  7626. // if there is just empty face material
  7627. // (must create new material as each model has its own face material)
  7628. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7629. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7630. }
  7631. if ( material instanceof THREE.MeshFaceMaterial ) {
  7632. for ( var i = 0; i < material.materials.length; i ++ ) {
  7633. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7634. }
  7635. }
  7636. if ( needsTangents ) {
  7637. geometry.computeTangents();
  7638. }
  7639. if ( objJSON.skin ) {
  7640. object = new THREE.SkinnedMesh( geometry, material );
  7641. } else if ( objJSON.morph ) {
  7642. object = new THREE.MorphAnimMesh( geometry, material );
  7643. if ( objJSON.duration !== undefined ) {
  7644. object.duration = objJSON.duration;
  7645. }
  7646. if ( objJSON.time !== undefined ) {
  7647. object.time = objJSON.time;
  7648. }
  7649. if ( objJSON.mirroredLoop !== undefined ) {
  7650. object.mirroredLoop = objJSON.mirroredLoop;
  7651. }
  7652. if ( material.morphNormals ) {
  7653. geometry.computeMorphNormals();
  7654. }
  7655. } else {
  7656. object = new THREE.Mesh( geometry, material );
  7657. }
  7658. object.name = objID;
  7659. if ( mat ) {
  7660. object.matrixAutoUpdate = false;
  7661. object.matrix.set(
  7662. mat[0], mat[1], mat[2], mat[3],
  7663. mat[4], mat[5], mat[6], mat[7],
  7664. mat[8], mat[9], mat[10], mat[11],
  7665. mat[12], mat[13], mat[14], mat[15]
  7666. );
  7667. } else {
  7668. object.position.fromArray( pos );
  7669. if ( quat ) {
  7670. object.quaternion.fromArray( quat );
  7671. } else {
  7672. object.rotation.fromArray( rot );
  7673. }
  7674. object.scale.fromArray( scl );
  7675. }
  7676. object.visible = objJSON.visible;
  7677. object.castShadow = objJSON.castShadow;
  7678. object.receiveShadow = objJSON.receiveShadow;
  7679. parent.add( object );
  7680. result.objects[ objID ] = object;
  7681. }
  7682. // lights
  7683. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7684. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7685. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7686. var color = objJSON.color;
  7687. var intensity = objJSON.intensity;
  7688. var distance = objJSON.distance;
  7689. var position = objJSON.position;
  7690. var rotation = objJSON.rotation;
  7691. switch ( objJSON.type ) {
  7692. case 'AmbientLight':
  7693. light = new THREE.AmbientLight( color );
  7694. break;
  7695. case 'PointLight':
  7696. light = new THREE.PointLight( color, intensity, distance );
  7697. light.position.fromArray( position );
  7698. break;
  7699. case 'DirectionalLight':
  7700. light = new THREE.DirectionalLight( color, intensity );
  7701. light.position.fromArray( objJSON.direction );
  7702. break;
  7703. case 'SpotLight':
  7704. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7705. light.angle = objJSON.angle;
  7706. light.position.fromArray( position );
  7707. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7708. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7709. break;
  7710. case 'HemisphereLight':
  7711. light = new THREE.DirectionalLight( color, intensity, distance );
  7712. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7713. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7714. break;
  7715. case 'AreaLight':
  7716. light = new THREE.AreaLight(color, intensity);
  7717. light.position.fromArray( position );
  7718. light.width = objJSON.size;
  7719. light.height = objJSON.size_y;
  7720. break;
  7721. }
  7722. parent.add( light );
  7723. light.name = objID;
  7724. result.lights[ objID ] = light;
  7725. result.objects[ objID ] = light;
  7726. // cameras
  7727. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7728. pos = objJSON.position;
  7729. rot = objJSON.rotation;
  7730. quat = objJSON.quaternion;
  7731. if ( objJSON.type === "PerspectiveCamera" ) {
  7732. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7733. } else if ( objJSON.type === "OrthographicCamera" ) {
  7734. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7735. }
  7736. camera.name = objID;
  7737. camera.position.fromArray( pos );
  7738. if ( quat !== undefined ) {
  7739. camera.quaternion.fromArray( quat );
  7740. } else if ( rot !== undefined ) {
  7741. camera.rotation.fromArray( rot );
  7742. }
  7743. parent.add( camera );
  7744. result.cameras[ objID ] = camera;
  7745. result.objects[ objID ] = camera;
  7746. // pure Object3D
  7747. } else {
  7748. pos = objJSON.position;
  7749. rot = objJSON.rotation;
  7750. scl = objJSON.scale;
  7751. quat = objJSON.quaternion;
  7752. object = new THREE.Object3D();
  7753. object.name = objID;
  7754. object.position.fromArray( pos );
  7755. if ( quat ) {
  7756. object.quaternion.fromArray( quat );
  7757. } else {
  7758. object.rotation.fromArray( rot );
  7759. }
  7760. object.scale.fromArray( scl );
  7761. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7762. parent.add( object );
  7763. result.objects[ objID ] = object;
  7764. result.empties[ objID ] = object;
  7765. }
  7766. if ( object ) {
  7767. if ( objJSON.userData !== undefined ) {
  7768. for ( var key in objJSON.userData ) {
  7769. var value = objJSON.userData[ key ];
  7770. object.userData[ key ] = value;
  7771. }
  7772. }
  7773. if ( objJSON.groups !== undefined ) {
  7774. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7775. var groupID = objJSON.groups[ i ];
  7776. if ( result.groups[ groupID ] === undefined ) {
  7777. result.groups[ groupID ] = [];
  7778. }
  7779. result.groups[ groupID ].push( objID );
  7780. }
  7781. }
  7782. }
  7783. }
  7784. if ( object !== undefined && objJSON.children !== undefined ) {
  7785. handle_children( object, objJSON.children );
  7786. }
  7787. }
  7788. };
  7789. function handle_mesh( geo, mat, id ) {
  7790. result.geometries[ id ] = geo;
  7791. result.face_materials[ id ] = mat;
  7792. handle_objects();
  7793. };
  7794. function handle_hierarchy( node, id, parent, material, obj ) {
  7795. var p = obj.position;
  7796. var r = obj.rotation;
  7797. var q = obj.quaternion;
  7798. var s = obj.scale;
  7799. node.position.fromArray( p );
  7800. if ( q ) {
  7801. node.quaternion.fromArray( q );
  7802. } else {
  7803. node.rotation.fromArray( r );
  7804. }
  7805. node.scale.fromArray( s );
  7806. // override children materials
  7807. // if object material was specified in JSON explicitly
  7808. if ( material ) {
  7809. node.traverse( function ( child ) {
  7810. child.material = material;
  7811. } );
  7812. }
  7813. // override children visibility
  7814. // with root node visibility as specified in JSON
  7815. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7816. node.traverse( function ( child ) {
  7817. child.visible = visible;
  7818. } );
  7819. parent.add( node );
  7820. node.name = id;
  7821. result.objects[ id ] = node;
  7822. handle_objects();
  7823. };
  7824. function create_callback_geometry( id ) {
  7825. return function ( geo, mat ) {
  7826. geo.name = id;
  7827. handle_mesh( geo, mat, id );
  7828. counter_models -= 1;
  7829. scope.onLoadComplete();
  7830. async_callback_gate();
  7831. }
  7832. };
  7833. function create_callback_hierachy( id, parent, material, obj ) {
  7834. return function ( event ) {
  7835. var result;
  7836. // loaders which use EventDispatcher
  7837. if ( event.content ) {
  7838. result = event.content;
  7839. // ColladaLoader
  7840. } else if ( event.dae ) {
  7841. result = event.scene;
  7842. // UTF8Loader
  7843. } else {
  7844. result = event;
  7845. }
  7846. handle_hierarchy( result, id, parent, material, obj );
  7847. counter_models -= 1;
  7848. scope.onLoadComplete();
  7849. async_callback_gate();
  7850. }
  7851. };
  7852. function create_callback_embed( id ) {
  7853. return function ( geo, mat ) {
  7854. geo.name = id;
  7855. result.geometries[ id ] = geo;
  7856. result.face_materials[ id ] = mat;
  7857. }
  7858. };
  7859. function async_callback_gate() {
  7860. var progress = {
  7861. totalModels : total_models,
  7862. totalTextures : total_textures,
  7863. loadedModels : total_models - counter_models,
  7864. loadedTextures : total_textures - counter_textures
  7865. };
  7866. scope.callbackProgress( progress, result );
  7867. scope.onLoadProgress();
  7868. if ( counter_models === 0 && counter_textures === 0 ) {
  7869. finalize();
  7870. callbackFinished( result );
  7871. }
  7872. };
  7873. function finalize() {
  7874. // take care of targets which could be asynchronously loaded objects
  7875. for ( var i = 0; i < target_array.length; i ++ ) {
  7876. var ta = target_array[ i ];
  7877. var target = result.objects[ ta.targetName ];
  7878. if ( target ) {
  7879. ta.object.target = target;
  7880. } else {
  7881. // if there was error and target of specified name doesn't exist in the scene file
  7882. // create instead dummy target
  7883. // (target must be added to scene explicitly as parent is already added)
  7884. ta.object.target = new THREE.Object3D();
  7885. result.scene.add( ta.object.target );
  7886. }
  7887. ta.object.target.userData.targetInverse = ta.object;
  7888. }
  7889. };
  7890. var callbackTexture = function ( count ) {
  7891. counter_textures -= count;
  7892. async_callback_gate();
  7893. scope.onLoadComplete();
  7894. };
  7895. // must use this instead of just directly calling callbackTexture
  7896. // because of closure in the calling context loop
  7897. var generateTextureCallback = function ( count ) {
  7898. return function () {
  7899. callbackTexture( count );
  7900. };
  7901. };
  7902. function traverse_json_hierarchy( objJSON, callback ) {
  7903. callback( objJSON );
  7904. if ( objJSON.children !== undefined ) {
  7905. for ( var objChildID in objJSON.children ) {
  7906. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7907. }
  7908. }
  7909. };
  7910. // first go synchronous elements
  7911. // fogs
  7912. var fogID, fogJSON;
  7913. for ( fogID in data.fogs ) {
  7914. fogJSON = data.fogs[ fogID ];
  7915. if ( fogJSON.type === "linear" ) {
  7916. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7917. } else if ( fogJSON.type === "exp2" ) {
  7918. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7919. }
  7920. color = fogJSON.color;
  7921. fog.color.setRGB( color[0], color[1], color[2] );
  7922. result.fogs[ fogID ] = fog;
  7923. }
  7924. // now come potentially asynchronous elements
  7925. // geometries
  7926. // count how many geometries will be loaded asynchronously
  7927. var geoID, geoJSON;
  7928. for ( geoID in data.geometries ) {
  7929. geoJSON = data.geometries[ geoID ];
  7930. if ( geoJSON.type in this.geometryHandlers ) {
  7931. counter_models += 1;
  7932. scope.onLoadStart();
  7933. }
  7934. }
  7935. // count how many hierarchies will be loaded asynchronously
  7936. for ( var objID in data.objects ) {
  7937. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7938. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7939. counter_models += 1;
  7940. scope.onLoadStart();
  7941. }
  7942. });
  7943. }
  7944. total_models = counter_models;
  7945. for ( geoID in data.geometries ) {
  7946. geoJSON = data.geometries[ geoID ];
  7947. if ( geoJSON.type === "cube" ) {
  7948. geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7949. geometry.name = geoID;
  7950. result.geometries[ geoID ] = geometry;
  7951. } else if ( geoJSON.type === "plane" ) {
  7952. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7953. geometry.name = geoID;
  7954. result.geometries[ geoID ] = geometry;
  7955. } else if ( geoJSON.type === "sphere" ) {
  7956. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7957. geometry.name = geoID;
  7958. result.geometries[ geoID ] = geometry;
  7959. } else if ( geoJSON.type === "cylinder" ) {
  7960. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7961. geometry.name = geoID;
  7962. result.geometries[ geoID ] = geometry;
  7963. } else if ( geoJSON.type === "torus" ) {
  7964. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7965. geometry.name = geoID;
  7966. result.geometries[ geoID ] = geometry;
  7967. } else if ( geoJSON.type === "icosahedron" ) {
  7968. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7969. geometry.name = geoID;
  7970. result.geometries[ geoID ] = geometry;
  7971. } else if ( geoJSON.type in this.geometryHandlers ) {
  7972. var loaderParameters = {};
  7973. for ( var parType in geoJSON ) {
  7974. if ( parType !== "type" && parType !== "url" ) {
  7975. loaderParameters[ parType ] = geoJSON[ parType ];
  7976. }
  7977. }
  7978. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7979. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7980. } else if ( geoJSON.type === "embedded" ) {
  7981. var modelJson = data.embeds[ geoJSON.id ],
  7982. texture_path = "";
  7983. // pass metadata along to jsonLoader so it knows the format version
  7984. modelJson.metadata = data.metadata;
  7985. if ( modelJson ) {
  7986. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7987. var model = jsonLoader.parse( modelJson, texture_path );
  7988. create_callback_embed( geoID )( model.geometry, model.materials );
  7989. }
  7990. }
  7991. }
  7992. // textures
  7993. // count how many textures will be loaded asynchronously
  7994. var textureID, textureJSON;
  7995. for ( textureID in data.textures ) {
  7996. textureJSON = data.textures[ textureID ];
  7997. if ( textureJSON.url instanceof Array ) {
  7998. counter_textures += textureJSON.url.length;
  7999. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  8000. scope.onLoadStart();
  8001. }
  8002. } else {
  8003. counter_textures += 1;
  8004. scope.onLoadStart();
  8005. }
  8006. }
  8007. total_textures = counter_textures;
  8008. for ( textureID in data.textures ) {
  8009. textureJSON = data.textures[ textureID ];
  8010. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  8011. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  8012. }
  8013. if ( textureJSON.url instanceof Array ) {
  8014. var count = textureJSON.url.length;
  8015. var url_array = [];
  8016. for( var i = 0; i < count; i ++ ) {
  8017. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  8018. }
  8019. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  8020. if ( isCompressed ) {
  8021. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8022. } else {
  8023. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8024. }
  8025. } else {
  8026. var isCompressed = /\.dds$/i.test( textureJSON.url );
  8027. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  8028. var textureCallback = generateTextureCallback( 1 );
  8029. if ( isCompressed ) {
  8030. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  8031. } else {
  8032. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  8033. }
  8034. if ( THREE[ textureJSON.minFilter ] !== undefined )
  8035. texture.minFilter = THREE[ textureJSON.minFilter ];
  8036. if ( THREE[ textureJSON.magFilter ] !== undefined )
  8037. texture.magFilter = THREE[ textureJSON.magFilter ];
  8038. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  8039. if ( textureJSON.repeat ) {
  8040. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  8041. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  8042. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  8043. }
  8044. if ( textureJSON.offset ) {
  8045. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  8046. }
  8047. // handle wrap after repeat so that default repeat can be overriden
  8048. if ( textureJSON.wrap ) {
  8049. var wrapMap = {
  8050. "repeat": THREE.RepeatWrapping,
  8051. "mirror": THREE.MirroredRepeatWrapping
  8052. }
  8053. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  8054. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  8055. }
  8056. }
  8057. result.textures[ textureID ] = texture;
  8058. }
  8059. // materials
  8060. var matID, matJSON;
  8061. var parID;
  8062. for ( matID in data.materials ) {
  8063. matJSON = data.materials[ matID ];
  8064. for ( parID in matJSON.parameters ) {
  8065. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  8066. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  8067. } else if ( parID === "shading" ) {
  8068. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  8069. } else if ( parID === "side" ) {
  8070. if ( matJSON.parameters[ parID ] == "double" ) {
  8071. matJSON.parameters[ parID ] = THREE.DoubleSide;
  8072. } else if ( matJSON.parameters[ parID ] == "back" ) {
  8073. matJSON.parameters[ parID ] = THREE.BackSide;
  8074. } else {
  8075. matJSON.parameters[ parID ] = THREE.FrontSide;
  8076. }
  8077. } else if ( parID === "blending" ) {
  8078. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  8079. } else if ( parID === "combine" ) {
  8080. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  8081. } else if ( parID === "vertexColors" ) {
  8082. if ( matJSON.parameters[ parID ] == "face" ) {
  8083. matJSON.parameters[ parID ] = THREE.FaceColors;
  8084. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  8085. } else if ( matJSON.parameters[ parID ] ) {
  8086. matJSON.parameters[ parID ] = THREE.VertexColors;
  8087. }
  8088. } else if ( parID === "wrapRGB" ) {
  8089. var v3 = matJSON.parameters[ parID ];
  8090. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  8091. }
  8092. }
  8093. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  8094. matJSON.parameters.transparent = true;
  8095. }
  8096. if ( matJSON.parameters.normalMap ) {
  8097. var shader = THREE.ShaderLib[ "normalmap" ];
  8098. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  8099. var diffuse = matJSON.parameters.color;
  8100. var specular = matJSON.parameters.specular;
  8101. var ambient = matJSON.parameters.ambient;
  8102. var shininess = matJSON.parameters.shininess;
  8103. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  8104. if ( matJSON.parameters.normalScale ) {
  8105. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  8106. }
  8107. if ( matJSON.parameters.map ) {
  8108. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  8109. uniforms[ "enableDiffuse" ].value = true;
  8110. }
  8111. if ( matJSON.parameters.envMap ) {
  8112. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  8113. uniforms[ "enableReflection" ].value = true;
  8114. uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
  8115. }
  8116. if ( matJSON.parameters.lightMap ) {
  8117. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  8118. uniforms[ "enableAO" ].value = true;
  8119. }
  8120. if ( matJSON.parameters.specularMap ) {
  8121. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  8122. uniforms[ "enableSpecular" ].value = true;
  8123. }
  8124. if ( matJSON.parameters.displacementMap ) {
  8125. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  8126. uniforms[ "enableDisplacement" ].value = true;
  8127. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  8128. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  8129. }
  8130. uniforms[ "diffuse" ].value.setHex( diffuse );
  8131. uniforms[ "specular" ].value.setHex( specular );
  8132. uniforms[ "ambient" ].value.setHex( ambient );
  8133. uniforms[ "shininess" ].value = shininess;
  8134. if ( matJSON.parameters.opacity ) {
  8135. uniforms[ "opacity" ].value = matJSON.parameters.opacity;
  8136. }
  8137. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  8138. material = new THREE.ShaderMaterial( parameters );
  8139. } else {
  8140. material = new THREE[ matJSON.type ]( matJSON.parameters );
  8141. }
  8142. material.name = matID;
  8143. result.materials[ matID ] = material;
  8144. }
  8145. // second pass through all materials to initialize MeshFaceMaterials
  8146. // that could be referring to other materials out of order
  8147. for ( matID in data.materials ) {
  8148. matJSON = data.materials[ matID ];
  8149. if ( matJSON.parameters.materials ) {
  8150. var materialArray = [];
  8151. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  8152. var label = matJSON.parameters.materials[ i ];
  8153. materialArray.push( result.materials[ label ] );
  8154. }
  8155. result.materials[ matID ].materials = materialArray;
  8156. }
  8157. }
  8158. // objects ( synchronous init of procedural primitives )
  8159. handle_objects();
  8160. // defaults
  8161. if ( result.cameras && data.defaults.camera ) {
  8162. result.currentCamera = result.cameras[ data.defaults.camera ];
  8163. }
  8164. if ( result.fogs && data.defaults.fog ) {
  8165. result.scene.fog = result.fogs[ data.defaults.fog ];
  8166. }
  8167. // synchronous callback
  8168. scope.callbackSync( result );
  8169. // just in case there are no async elements
  8170. async_callback_gate();
  8171. }
  8172. }
  8173. /**
  8174. * @author mrdoob / http://mrdoob.com/
  8175. */
  8176. THREE.TextureLoader = function ( manager ) {
  8177. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8178. };
  8179. THREE.TextureLoader.prototype = {
  8180. constructor: THREE.TextureLoader,
  8181. load: function ( url, onLoad, onProgress, onError ) {
  8182. var scope = this;
  8183. var loader = new THREE.ImageLoader( scope.manager );
  8184. loader.setCrossOrigin( this.crossOrigin );
  8185. loader.load( url, function ( image ) {
  8186. var texture = new THREE.Texture( image );
  8187. texture.needsUpdate = true;
  8188. if ( onLoad !== undefined ) {
  8189. onLoad( texture );
  8190. }
  8191. } );
  8192. },
  8193. setCrossOrigin: function ( value ) {
  8194. this.crossOrigin = value;
  8195. }
  8196. };
  8197. /**
  8198. * @author mrdoob / http://mrdoob.com/
  8199. * @author alteredq / http://alteredqualia.com/
  8200. */
  8201. THREE.Material = function () {
  8202. this.id = THREE.MaterialIdCount ++;
  8203. this.uuid = THREE.Math.generateUUID();
  8204. this.name = '';
  8205. this.side = THREE.FrontSide;
  8206. this.opacity = 1;
  8207. this.transparent = false;
  8208. this.blending = THREE.NormalBlending;
  8209. this.blendSrc = THREE.SrcAlphaFactor;
  8210. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  8211. this.blendEquation = THREE.AddEquation;
  8212. this.depthTest = true;
  8213. this.depthWrite = true;
  8214. this.polygonOffset = false;
  8215. this.polygonOffsetFactor = 0;
  8216. this.polygonOffsetUnits = 0;
  8217. this.alphaTest = 0;
  8218. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8219. this.visible = true;
  8220. this.needsUpdate = true;
  8221. };
  8222. THREE.Material.prototype = {
  8223. constructor: THREE.Material,
  8224. setValues: function ( values ) {
  8225. if ( values === undefined ) return;
  8226. for ( var key in values ) {
  8227. var newValue = values[ key ];
  8228. if ( newValue === undefined ) {
  8229. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  8230. continue;
  8231. }
  8232. if ( key in this ) {
  8233. var currentValue = this[ key ];
  8234. if ( currentValue instanceof THREE.Color ) {
  8235. currentValue.set( newValue );
  8236. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  8237. currentValue.copy( newValue );
  8238. } else if ( key == 'overdraw') {
  8239. // ensure overdraw is backwards-compatable with legacy boolean type
  8240. this[ key ] = Number(newValue);
  8241. } else {
  8242. this[ key ] = newValue;
  8243. }
  8244. }
  8245. }
  8246. },
  8247. clone: function ( material ) {
  8248. if ( material === undefined ) material = new THREE.Material();
  8249. material.name = this.name;
  8250. material.side = this.side;
  8251. material.opacity = this.opacity;
  8252. material.transparent = this.transparent;
  8253. material.blending = this.blending;
  8254. material.blendSrc = this.blendSrc;
  8255. material.blendDst = this.blendDst;
  8256. material.blendEquation = this.blendEquation;
  8257. material.depthTest = this.depthTest;
  8258. material.depthWrite = this.depthWrite;
  8259. material.polygonOffset = this.polygonOffset;
  8260. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8261. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8262. material.alphaTest = this.alphaTest;
  8263. material.overdraw = this.overdraw;
  8264. material.visible = this.visible;
  8265. return material;
  8266. },
  8267. dispose: function () {
  8268. this.dispatchEvent( { type: 'dispose' } );
  8269. }
  8270. };
  8271. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8272. THREE.MaterialIdCount = 0;
  8273. /**
  8274. * @author mrdoob / http://mrdoob.com/
  8275. * @author alteredq / http://alteredqualia.com/
  8276. *
  8277. * parameters = {
  8278. * color: <hex>,
  8279. * opacity: <float>,
  8280. *
  8281. * blending: THREE.NormalBlending,
  8282. * depthTest: <bool>,
  8283. * depthWrite: <bool>,
  8284. *
  8285. * linewidth: <float>,
  8286. * linecap: "round",
  8287. * linejoin: "round",
  8288. *
  8289. * vertexColors: <bool>
  8290. *
  8291. * fog: <bool>
  8292. * }
  8293. */
  8294. THREE.LineBasicMaterial = function ( parameters ) {
  8295. THREE.Material.call( this );
  8296. this.color = new THREE.Color( 0xffffff );
  8297. this.linewidth = 1;
  8298. this.linecap = 'round';
  8299. this.linejoin = 'round';
  8300. this.vertexColors = false;
  8301. this.fog = true;
  8302. this.setValues( parameters );
  8303. };
  8304. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8305. THREE.LineBasicMaterial.prototype.clone = function () {
  8306. var material = new THREE.LineBasicMaterial();
  8307. THREE.Material.prototype.clone.call( this, material );
  8308. material.color.copy( this.color );
  8309. material.linewidth = this.linewidth;
  8310. material.linecap = this.linecap;
  8311. material.linejoin = this.linejoin;
  8312. material.vertexColors = this.vertexColors;
  8313. material.fog = this.fog;
  8314. return material;
  8315. };
  8316. /**
  8317. * @author alteredq / http://alteredqualia.com/
  8318. *
  8319. * parameters = {
  8320. * color: <hex>,
  8321. * opacity: <float>,
  8322. *
  8323. * blending: THREE.NormalBlending,
  8324. * depthTest: <bool>,
  8325. * depthWrite: <bool>,
  8326. *
  8327. * linewidth: <float>,
  8328. *
  8329. * scale: <float>,
  8330. * dashSize: <float>,
  8331. * gapSize: <float>,
  8332. *
  8333. * vertexColors: <bool>
  8334. *
  8335. * fog: <bool>
  8336. * }
  8337. */
  8338. THREE.LineDashedMaterial = function ( parameters ) {
  8339. THREE.Material.call( this );
  8340. this.color = new THREE.Color( 0xffffff );
  8341. this.linewidth = 1;
  8342. this.scale = 1;
  8343. this.dashSize = 3;
  8344. this.gapSize = 1;
  8345. this.vertexColors = false;
  8346. this.fog = true;
  8347. this.setValues( parameters );
  8348. };
  8349. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8350. THREE.LineDashedMaterial.prototype.clone = function () {
  8351. var material = new THREE.LineDashedMaterial();
  8352. THREE.Material.prototype.clone.call( this, material );
  8353. material.color.copy( this.color );
  8354. material.linewidth = this.linewidth;
  8355. material.scale = this.scale;
  8356. material.dashSize = this.dashSize;
  8357. material.gapSize = this.gapSize;
  8358. material.vertexColors = this.vertexColors;
  8359. material.fog = this.fog;
  8360. return material;
  8361. };
  8362. /**
  8363. * @author mrdoob / http://mrdoob.com/
  8364. * @author alteredq / http://alteredqualia.com/
  8365. *
  8366. * parameters = {
  8367. * color: <hex>,
  8368. * opacity: <float>,
  8369. * map: new THREE.Texture( <Image> ),
  8370. *
  8371. * lightMap: new THREE.Texture( <Image> ),
  8372. *
  8373. * specularMap: new THREE.Texture( <Image> ),
  8374. *
  8375. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8376. * combine: THREE.Multiply,
  8377. * reflectivity: <float>,
  8378. * refractionRatio: <float>,
  8379. *
  8380. * shading: THREE.SmoothShading,
  8381. * blending: THREE.NormalBlending,
  8382. * depthTest: <bool>,
  8383. * depthWrite: <bool>,
  8384. *
  8385. * wireframe: <boolean>,
  8386. * wireframeLinewidth: <float>,
  8387. *
  8388. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8389. *
  8390. * skinning: <bool>,
  8391. * morphTargets: <bool>,
  8392. *
  8393. * fog: <bool>
  8394. * }
  8395. */
  8396. THREE.MeshBasicMaterial = function ( parameters ) {
  8397. THREE.Material.call( this );
  8398. this.color = new THREE.Color( 0xffffff ); // emissive
  8399. this.map = null;
  8400. this.lightMap = null;
  8401. this.specularMap = null;
  8402. this.envMap = null;
  8403. this.combine = THREE.MultiplyOperation;
  8404. this.reflectivity = 1;
  8405. this.refractionRatio = 0.98;
  8406. this.fog = true;
  8407. this.shading = THREE.SmoothShading;
  8408. this.wireframe = false;
  8409. this.wireframeLinewidth = 1;
  8410. this.wireframeLinecap = 'round';
  8411. this.wireframeLinejoin = 'round';
  8412. this.vertexColors = THREE.NoColors;
  8413. this.skinning = false;
  8414. this.morphTargets = false;
  8415. this.setValues( parameters );
  8416. };
  8417. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8418. THREE.MeshBasicMaterial.prototype.clone = function () {
  8419. var material = new THREE.MeshBasicMaterial();
  8420. THREE.Material.prototype.clone.call( this, material );
  8421. material.color.copy( this.color );
  8422. material.map = this.map;
  8423. material.lightMap = this.lightMap;
  8424. material.specularMap = this.specularMap;
  8425. material.envMap = this.envMap;
  8426. material.combine = this.combine;
  8427. material.reflectivity = this.reflectivity;
  8428. material.refractionRatio = this.refractionRatio;
  8429. material.fog = this.fog;
  8430. material.shading = this.shading;
  8431. material.wireframe = this.wireframe;
  8432. material.wireframeLinewidth = this.wireframeLinewidth;
  8433. material.wireframeLinecap = this.wireframeLinecap;
  8434. material.wireframeLinejoin = this.wireframeLinejoin;
  8435. material.vertexColors = this.vertexColors;
  8436. material.skinning = this.skinning;
  8437. material.morphTargets = this.morphTargets;
  8438. return material;
  8439. };
  8440. /**
  8441. * @author mrdoob / http://mrdoob.com/
  8442. * @author alteredq / http://alteredqualia.com/
  8443. *
  8444. * parameters = {
  8445. * color: <hex>,
  8446. * ambient: <hex>,
  8447. * emissive: <hex>,
  8448. * opacity: <float>,
  8449. *
  8450. * map: new THREE.Texture( <Image> ),
  8451. *
  8452. * lightMap: new THREE.Texture( <Image> ),
  8453. *
  8454. * specularMap: new THREE.Texture( <Image> ),
  8455. *
  8456. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8457. * combine: THREE.Multiply,
  8458. * reflectivity: <float>,
  8459. * refractionRatio: <float>,
  8460. *
  8461. * shading: THREE.SmoothShading,
  8462. * blending: THREE.NormalBlending,
  8463. * depthTest: <bool>,
  8464. * depthWrite: <bool>,
  8465. *
  8466. * wireframe: <boolean>,
  8467. * wireframeLinewidth: <float>,
  8468. *
  8469. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8470. *
  8471. * skinning: <bool>,
  8472. * morphTargets: <bool>,
  8473. * morphNormals: <bool>,
  8474. *
  8475. * fog: <bool>
  8476. * }
  8477. */
  8478. THREE.MeshLambertMaterial = function ( parameters ) {
  8479. THREE.Material.call( this );
  8480. this.color = new THREE.Color( 0xffffff ); // diffuse
  8481. this.ambient = new THREE.Color( 0xffffff );
  8482. this.emissive = new THREE.Color( 0x000000 );
  8483. this.wrapAround = false;
  8484. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8485. this.map = null;
  8486. this.lightMap = null;
  8487. this.specularMap = null;
  8488. this.envMap = null;
  8489. this.combine = THREE.MultiplyOperation;
  8490. this.reflectivity = 1;
  8491. this.refractionRatio = 0.98;
  8492. this.fog = true;
  8493. this.shading = THREE.SmoothShading;
  8494. this.wireframe = false;
  8495. this.wireframeLinewidth = 1;
  8496. this.wireframeLinecap = 'round';
  8497. this.wireframeLinejoin = 'round';
  8498. this.vertexColors = THREE.NoColors;
  8499. this.skinning = false;
  8500. this.morphTargets = false;
  8501. this.morphNormals = false;
  8502. this.setValues( parameters );
  8503. };
  8504. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8505. THREE.MeshLambertMaterial.prototype.clone = function () {
  8506. var material = new THREE.MeshLambertMaterial();
  8507. THREE.Material.prototype.clone.call( this, material );
  8508. material.color.copy( this.color );
  8509. material.ambient.copy( this.ambient );
  8510. material.emissive.copy( this.emissive );
  8511. material.wrapAround = this.wrapAround;
  8512. material.wrapRGB.copy( this.wrapRGB );
  8513. material.map = this.map;
  8514. material.lightMap = this.lightMap;
  8515. material.specularMap = this.specularMap;
  8516. material.envMap = this.envMap;
  8517. material.combine = this.combine;
  8518. material.reflectivity = this.reflectivity;
  8519. material.refractionRatio = this.refractionRatio;
  8520. material.fog = this.fog;
  8521. material.shading = this.shading;
  8522. material.wireframe = this.wireframe;
  8523. material.wireframeLinewidth = this.wireframeLinewidth;
  8524. material.wireframeLinecap = this.wireframeLinecap;
  8525. material.wireframeLinejoin = this.wireframeLinejoin;
  8526. material.vertexColors = this.vertexColors;
  8527. material.skinning = this.skinning;
  8528. material.morphTargets = this.morphTargets;
  8529. material.morphNormals = this.morphNormals;
  8530. return material;
  8531. };
  8532. /**
  8533. * @author mrdoob / http://mrdoob.com/
  8534. * @author alteredq / http://alteredqualia.com/
  8535. *
  8536. * parameters = {
  8537. * color: <hex>,
  8538. * ambient: <hex>,
  8539. * emissive: <hex>,
  8540. * specular: <hex>,
  8541. * shininess: <float>,
  8542. * opacity: <float>,
  8543. *
  8544. * map: new THREE.Texture( <Image> ),
  8545. *
  8546. * lightMap: new THREE.Texture( <Image> ),
  8547. *
  8548. * bumpMap: new THREE.Texture( <Image> ),
  8549. * bumpScale: <float>,
  8550. *
  8551. * normalMap: new THREE.Texture( <Image> ),
  8552. * normalScale: <Vector2>,
  8553. *
  8554. * specularMap: new THREE.Texture( <Image> ),
  8555. *
  8556. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8557. * combine: THREE.Multiply,
  8558. * reflectivity: <float>,
  8559. * refractionRatio: <float>,
  8560. *
  8561. * shading: THREE.SmoothShading,
  8562. * blending: THREE.NormalBlending,
  8563. * depthTest: <bool>,
  8564. * depthWrite: <bool>,
  8565. *
  8566. * wireframe: <boolean>,
  8567. * wireframeLinewidth: <float>,
  8568. *
  8569. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8570. *
  8571. * skinning: <bool>,
  8572. * morphTargets: <bool>,
  8573. * morphNormals: <bool>,
  8574. *
  8575. * fog: <bool>
  8576. * }
  8577. */
  8578. THREE.MeshPhongMaterial = function ( parameters ) {
  8579. THREE.Material.call( this );
  8580. this.color = new THREE.Color( 0xffffff ); // diffuse
  8581. this.ambient = new THREE.Color( 0xffffff );
  8582. this.emissive = new THREE.Color( 0x000000 );
  8583. this.specular = new THREE.Color( 0x111111 );
  8584. this.shininess = 30;
  8585. this.metal = false;
  8586. this.wrapAround = false;
  8587. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8588. this.map = null;
  8589. this.lightMap = null;
  8590. this.bumpMap = null;
  8591. this.bumpScale = 1;
  8592. this.normalMap = null;
  8593. this.normalScale = new THREE.Vector2( 1, 1 );
  8594. this.specularMap = null;
  8595. this.envMap = null;
  8596. this.combine = THREE.MultiplyOperation;
  8597. this.reflectivity = 1;
  8598. this.refractionRatio = 0.98;
  8599. this.fog = true;
  8600. this.shading = THREE.SmoothShading;
  8601. this.wireframe = false;
  8602. this.wireframeLinewidth = 1;
  8603. this.wireframeLinecap = 'round';
  8604. this.wireframeLinejoin = 'round';
  8605. this.vertexColors = THREE.NoColors;
  8606. this.skinning = false;
  8607. this.morphTargets = false;
  8608. this.morphNormals = false;
  8609. this.setValues( parameters );
  8610. };
  8611. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8612. THREE.MeshPhongMaterial.prototype.clone = function () {
  8613. var material = new THREE.MeshPhongMaterial();
  8614. THREE.Material.prototype.clone.call( this, material );
  8615. material.color.copy( this.color );
  8616. material.ambient.copy( this.ambient );
  8617. material.emissive.copy( this.emissive );
  8618. material.specular.copy( this.specular );
  8619. material.shininess = this.shininess;
  8620. material.metal = this.metal;
  8621. material.wrapAround = this.wrapAround;
  8622. material.wrapRGB.copy( this.wrapRGB );
  8623. material.map = this.map;
  8624. material.lightMap = this.lightMap;
  8625. material.bumpMap = this.bumpMap;
  8626. material.bumpScale = this.bumpScale;
  8627. material.normalMap = this.normalMap;
  8628. material.normalScale.copy( this.normalScale );
  8629. material.specularMap = this.specularMap;
  8630. material.envMap = this.envMap;
  8631. material.combine = this.combine;
  8632. material.reflectivity = this.reflectivity;
  8633. material.refractionRatio = this.refractionRatio;
  8634. material.fog = this.fog;
  8635. material.shading = this.shading;
  8636. material.wireframe = this.wireframe;
  8637. material.wireframeLinewidth = this.wireframeLinewidth;
  8638. material.wireframeLinecap = this.wireframeLinecap;
  8639. material.wireframeLinejoin = this.wireframeLinejoin;
  8640. material.vertexColors = this.vertexColors;
  8641. material.skinning = this.skinning;
  8642. material.morphTargets = this.morphTargets;
  8643. material.morphNormals = this.morphNormals;
  8644. return material;
  8645. };
  8646. /**
  8647. * @author mrdoob / http://mrdoob.com/
  8648. * @author alteredq / http://alteredqualia.com/
  8649. *
  8650. * parameters = {
  8651. * opacity: <float>,
  8652. *
  8653. * blending: THREE.NormalBlending,
  8654. * depthTest: <bool>,
  8655. * depthWrite: <bool>,
  8656. *
  8657. * wireframe: <boolean>,
  8658. * wireframeLinewidth: <float>
  8659. * }
  8660. */
  8661. THREE.MeshDepthMaterial = function ( parameters ) {
  8662. THREE.Material.call( this );
  8663. this.wireframe = false;
  8664. this.wireframeLinewidth = 1;
  8665. this.setValues( parameters );
  8666. };
  8667. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8668. THREE.MeshDepthMaterial.prototype.clone = function () {
  8669. var material = new THREE.MeshDepthMaterial();
  8670. THREE.Material.prototype.clone.call( this, material );
  8671. material.wireframe = this.wireframe;
  8672. material.wireframeLinewidth = this.wireframeLinewidth;
  8673. return material;
  8674. };
  8675. /**
  8676. * @author mrdoob / http://mrdoob.com/
  8677. *
  8678. * parameters = {
  8679. * opacity: <float>,
  8680. *
  8681. * shading: THREE.FlatShading,
  8682. * blending: THREE.NormalBlending,
  8683. * depthTest: <bool>,
  8684. * depthWrite: <bool>,
  8685. *
  8686. * wireframe: <boolean>,
  8687. * wireframeLinewidth: <float>
  8688. * }
  8689. */
  8690. THREE.MeshNormalMaterial = function ( parameters ) {
  8691. THREE.Material.call( this, parameters );
  8692. this.shading = THREE.FlatShading;
  8693. this.wireframe = false;
  8694. this.wireframeLinewidth = 1;
  8695. this.morphTargets = false;
  8696. this.setValues( parameters );
  8697. };
  8698. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8699. THREE.MeshNormalMaterial.prototype.clone = function () {
  8700. var material = new THREE.MeshNormalMaterial();
  8701. THREE.Material.prototype.clone.call( this, material );
  8702. material.shading = this.shading;
  8703. material.wireframe = this.wireframe;
  8704. material.wireframeLinewidth = this.wireframeLinewidth;
  8705. return material;
  8706. };
  8707. /**
  8708. * @author mrdoob / http://mrdoob.com/
  8709. */
  8710. THREE.MeshFaceMaterial = function ( materials ) {
  8711. this.materials = materials instanceof Array ? materials : [];
  8712. };
  8713. THREE.MeshFaceMaterial.prototype.clone = function () {
  8714. var material = new THREE.MeshFaceMaterial();
  8715. for ( var i = 0; i < this.materials.length; i ++ ) {
  8716. material.materials.push( this.materials[ i ].clone() );
  8717. }
  8718. return material;
  8719. };
  8720. /**
  8721. * @author mrdoob / http://mrdoob.com/
  8722. * @author alteredq / http://alteredqualia.com/
  8723. *
  8724. * parameters = {
  8725. * color: <hex>,
  8726. * opacity: <float>,
  8727. * map: new THREE.Texture( <Image> ),
  8728. *
  8729. * size: <float>,
  8730. *
  8731. * blending: THREE.NormalBlending,
  8732. * depthTest: <bool>,
  8733. * depthWrite: <bool>,
  8734. *
  8735. * vertexColors: <bool>,
  8736. *
  8737. * fog: <bool>
  8738. * }
  8739. */
  8740. THREE.ParticleSystemMaterial = function ( parameters ) {
  8741. THREE.Material.call( this );
  8742. this.color = new THREE.Color( 0xffffff );
  8743. this.map = null;
  8744. this.size = 1;
  8745. this.sizeAttenuation = true;
  8746. this.vertexColors = false;
  8747. this.fog = true;
  8748. this.setValues( parameters );
  8749. };
  8750. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8751. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8752. var material = new THREE.ParticleSystemMaterial();
  8753. THREE.Material.prototype.clone.call( this, material );
  8754. material.color.copy( this.color );
  8755. material.map = this.map;
  8756. material.size = this.size;
  8757. material.sizeAttenuation = this.sizeAttenuation;
  8758. material.vertexColors = this.vertexColors;
  8759. material.fog = this.fog;
  8760. return material;
  8761. };
  8762. // backwards compatibility
  8763. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8764. /**
  8765. * @author alteredq / http://alteredqualia.com/
  8766. *
  8767. * parameters = {
  8768. * fragmentShader: <string>,
  8769. * vertexShader: <string>,
  8770. *
  8771. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8772. *
  8773. * defines: { "label" : "value" },
  8774. *
  8775. * shading: THREE.SmoothShading,
  8776. * blending: THREE.NormalBlending,
  8777. * depthTest: <bool>,
  8778. * depthWrite: <bool>,
  8779. *
  8780. * wireframe: <boolean>,
  8781. * wireframeLinewidth: <float>,
  8782. *
  8783. * lights: <bool>,
  8784. *
  8785. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8786. *
  8787. * skinning: <bool>,
  8788. * morphTargets: <bool>,
  8789. * morphNormals: <bool>,
  8790. *
  8791. * fog: <bool>
  8792. * }
  8793. */
  8794. THREE.ShaderMaterial = function ( parameters ) {
  8795. THREE.Material.call( this );
  8796. this.fragmentShader = "void main() {}";
  8797. this.vertexShader = "void main() {}";
  8798. this.uniforms = {};
  8799. this.defines = {};
  8800. this.attributes = null;
  8801. this.shading = THREE.SmoothShading;
  8802. this.linewidth = 1;
  8803. this.wireframe = false;
  8804. this.wireframeLinewidth = 1;
  8805. this.fog = false; // set to use scene fog
  8806. this.lights = false; // set to use scene lights
  8807. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8808. this.skinning = false; // set to use skinning attribute streams
  8809. this.morphTargets = false; // set to use morph targets
  8810. this.morphNormals = false; // set to use morph normals
  8811. // When rendered geometry doesn't include these attributes but the material does,
  8812. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8813. this.defaultAttributeValues = {
  8814. "color" : [ 1, 1, 1],
  8815. "uv" : [ 0, 0 ],
  8816. "uv2" : [ 0, 0 ]
  8817. };
  8818. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8819. // should always be used to avoid potentially expensive emulation.
  8820. this.index0AttributeName = "position";
  8821. this.setValues( parameters );
  8822. };
  8823. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8824. THREE.ShaderMaterial.prototype.clone = function () {
  8825. var material = new THREE.ShaderMaterial();
  8826. THREE.Material.prototype.clone.call( this, material );
  8827. material.fragmentShader = this.fragmentShader;
  8828. material.vertexShader = this.vertexShader;
  8829. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8830. material.attributes = this.attributes;
  8831. material.defines = this.defines;
  8832. material.shading = this.shading;
  8833. material.wireframe = this.wireframe;
  8834. material.wireframeLinewidth = this.wireframeLinewidth;
  8835. material.fog = this.fog;
  8836. material.lights = this.lights;
  8837. material.vertexColors = this.vertexColors;
  8838. material.skinning = this.skinning;
  8839. material.morphTargets = this.morphTargets;
  8840. material.morphNormals = this.morphNormals;
  8841. return material;
  8842. };
  8843. /**
  8844. * @author alteredq / http://alteredqualia.com/
  8845. *
  8846. * parameters = {
  8847. * color: <hex>,
  8848. * opacity: <float>,
  8849. * map: new THREE.Texture( <Image> ),
  8850. *
  8851. * blending: THREE.NormalBlending,
  8852. * depthTest: <bool>,
  8853. * depthWrite: <bool>,
  8854. *
  8855. * uvOffset: new THREE.Vector2(),
  8856. * uvScale: new THREE.Vector2(),
  8857. *
  8858. * fog: <bool>
  8859. * }
  8860. */
  8861. THREE.SpriteMaterial = function ( parameters ) {
  8862. THREE.Material.call( this );
  8863. // defaults
  8864. this.color = new THREE.Color( 0xffffff );
  8865. this.map = null;
  8866. this.rotation = 0;
  8867. this.fog = false;
  8868. // set parameters
  8869. this.setValues( parameters );
  8870. };
  8871. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8872. THREE.SpriteMaterial.prototype.clone = function () {
  8873. var material = new THREE.SpriteMaterial();
  8874. THREE.Material.prototype.clone.call( this, material );
  8875. material.color.copy( this.color );
  8876. material.map = this.map;
  8877. material.rotation = this.rotation;
  8878. material.fog = this.fog;
  8879. return material;
  8880. };
  8881. /**
  8882. * @author mrdoob / http://mrdoob.com/
  8883. *
  8884. * parameters = {
  8885. * color: <hex>,
  8886. * program: <function>,
  8887. * opacity: <float>,
  8888. * blending: THREE.NormalBlending
  8889. * }
  8890. */
  8891. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8892. THREE.Material.call( this );
  8893. this.color = new THREE.Color( 0xffffff );
  8894. this.program = function ( context, color ) {};
  8895. this.setValues( parameters );
  8896. };
  8897. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8898. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8899. var material = new THREE.SpriteCanvasMaterial();
  8900. THREE.Material.prototype.clone.call( this, material );
  8901. material.color.copy( this.color );
  8902. material.program = this.program;
  8903. return material;
  8904. };
  8905. // backwards compatibility
  8906. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8907. /**
  8908. * @author mrdoob / http://mrdoob.com/
  8909. * @author alteredq / http://alteredqualia.com/
  8910. * @author szimek / https://github.com/szimek/
  8911. */
  8912. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8913. this.id = THREE.TextureIdCount ++;
  8914. this.uuid = THREE.Math.generateUUID();
  8915. this.name = '';
  8916. this.image = image;
  8917. this.mipmaps = [];
  8918. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8919. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8920. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8921. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8922. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8923. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8924. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8925. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8926. this.offset = new THREE.Vector2( 0, 0 );
  8927. this.repeat = new THREE.Vector2( 1, 1 );
  8928. this.generateMipmaps = true;
  8929. this.premultiplyAlpha = false;
  8930. this.flipY = true;
  8931. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8932. this._needsUpdate = false;
  8933. this.onUpdate = null;
  8934. };
  8935. THREE.Texture.prototype = {
  8936. constructor: THREE.Texture,
  8937. get needsUpdate () {
  8938. return this._needsUpdate;
  8939. },
  8940. set needsUpdate ( value ) {
  8941. if ( value === true ) this.update();
  8942. this._needsUpdate = value;
  8943. },
  8944. clone: function ( texture ) {
  8945. if ( texture === undefined ) texture = new THREE.Texture();
  8946. texture.image = this.image;
  8947. texture.mipmaps = this.mipmaps.slice(0);
  8948. texture.mapping = this.mapping;
  8949. texture.wrapS = this.wrapS;
  8950. texture.wrapT = this.wrapT;
  8951. texture.magFilter = this.magFilter;
  8952. texture.minFilter = this.minFilter;
  8953. texture.anisotropy = this.anisotropy;
  8954. texture.format = this.format;
  8955. texture.type = this.type;
  8956. texture.offset.copy( this.offset );
  8957. texture.repeat.copy( this.repeat );
  8958. texture.generateMipmaps = this.generateMipmaps;
  8959. texture.premultiplyAlpha = this.premultiplyAlpha;
  8960. texture.flipY = this.flipY;
  8961. texture.unpackAlignment = this.unpackAlignment;
  8962. return texture;
  8963. },
  8964. update: function () {
  8965. this.dispatchEvent( { type: 'update' } );
  8966. },
  8967. dispose: function () {
  8968. this.dispatchEvent( { type: 'dispose' } );
  8969. }
  8970. };
  8971. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8972. THREE.TextureIdCount = 0;
  8973. /**
  8974. * @author alteredq / http://alteredqualia.com/
  8975. */
  8976. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8977. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8978. this.image = { width: width, height: height };
  8979. this.mipmaps = mipmaps;
  8980. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8981. };
  8982. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8983. THREE.CompressedTexture.prototype.clone = function () {
  8984. var texture = new THREE.CompressedTexture();
  8985. THREE.Texture.prototype.clone.call( this, texture );
  8986. return texture;
  8987. };
  8988. /**
  8989. * @author alteredq / http://alteredqualia.com/
  8990. */
  8991. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8992. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8993. this.image = { data: data, width: width, height: height };
  8994. };
  8995. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8996. THREE.DataTexture.prototype.clone = function () {
  8997. var texture = new THREE.DataTexture();
  8998. THREE.Texture.prototype.clone.call( this, texture );
  8999. return texture;
  9000. };
  9001. /**
  9002. * @author alteredq / http://alteredqualia.com/
  9003. */
  9004. THREE.ParticleSystem = function ( geometry, material ) {
  9005. THREE.Object3D.call( this );
  9006. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9007. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  9008. this.sortParticles = false;
  9009. this.frustumCulled = false;
  9010. };
  9011. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  9012. THREE.ParticleSystem.prototype.clone = function ( object ) {
  9013. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  9014. object.sortParticles = this.sortParticles;
  9015. THREE.Object3D.prototype.clone.call( this, object );
  9016. return object;
  9017. };
  9018. /**
  9019. * @author mrdoob / http://mrdoob.com/
  9020. */
  9021. THREE.Line = function ( geometry, material, type ) {
  9022. THREE.Object3D.call( this );
  9023. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9024. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  9025. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  9026. };
  9027. THREE.LineStrip = 0;
  9028. THREE.LinePieces = 1;
  9029. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  9030. THREE.Line.prototype.clone = function ( object ) {
  9031. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  9032. THREE.Object3D.prototype.clone.call( this, object );
  9033. return object;
  9034. };
  9035. /**
  9036. * @author mrdoob / http://mrdoob.com/
  9037. * @author alteredq / http://alteredqualia.com/
  9038. * @author mikael emtinger / http://gomo.se/
  9039. * @author jonobr1 / http://jonobr1.com/
  9040. */
  9041. THREE.Mesh = function ( geometry, material ) {
  9042. THREE.Object3D.call( this );
  9043. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9044. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9045. this.updateMorphTargets();
  9046. };
  9047. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9048. THREE.Mesh.prototype.updateMorphTargets = function () {
  9049. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9050. this.morphTargetBase = -1;
  9051. this.morphTargetForcedOrder = [];
  9052. this.morphTargetInfluences = [];
  9053. this.morphTargetDictionary = {};
  9054. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9055. this.morphTargetInfluences.push( 0 );
  9056. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9057. }
  9058. }
  9059. };
  9060. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9061. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9062. return this.morphTargetDictionary[ name ];
  9063. }
  9064. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  9065. return 0;
  9066. };
  9067. THREE.Mesh.prototype.clone = function ( object ) {
  9068. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9069. THREE.Object3D.prototype.clone.call( this, object );
  9070. return object;
  9071. };
  9072. /**
  9073. * @author mikael emtinger / http://gomo.se/
  9074. * @author alteredq / http://alteredqualia.com/
  9075. */
  9076. THREE.Bone = function( belongsToSkin ) {
  9077. THREE.Object3D.call( this );
  9078. this.skin = belongsToSkin;
  9079. this.skinMatrix = new THREE.Matrix4();
  9080. };
  9081. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9082. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  9083. // update local
  9084. if ( this.matrixAutoUpdate ) {
  9085. forceUpdate |= this.updateMatrix();
  9086. }
  9087. // update skin matrix
  9088. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  9089. if( parentSkinMatrix ) {
  9090. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  9091. } else {
  9092. this.skinMatrix.copy( this.matrix );
  9093. }
  9094. this.matrixWorldNeedsUpdate = false;
  9095. forceUpdate = true;
  9096. }
  9097. // update children
  9098. var child, i, l = this.children.length;
  9099. for ( i = 0; i < l; i ++ ) {
  9100. this.children[ i ].update( this.skinMatrix, forceUpdate );
  9101. }
  9102. };
  9103. /**
  9104. * @author mikael emtinger / http://gomo.se/
  9105. * @author alteredq / http://alteredqualia.com/
  9106. */
  9107. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9108. THREE.Mesh.call( this, geometry, material );
  9109. //
  9110. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9111. // init bones
  9112. this.identityMatrix = new THREE.Matrix4();
  9113. this.bones = [];
  9114. this.boneMatrices = [];
  9115. var b, bone, gbone, p, q, s;
  9116. if ( this.geometry && this.geometry.bones !== undefined ) {
  9117. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  9118. gbone = this.geometry.bones[ b ];
  9119. p = gbone.pos;
  9120. q = gbone.rotq;
  9121. s = gbone.scl;
  9122. bone = this.addBone();
  9123. bone.name = gbone.name;
  9124. bone.position.set( p[0], p[1], p[2] );
  9125. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  9126. if ( s !== undefined ) {
  9127. bone.scale.set( s[0], s[1], s[2] );
  9128. } else {
  9129. bone.scale.set( 1, 1, 1 );
  9130. }
  9131. }
  9132. for ( b = 0; b < this.bones.length; b ++ ) {
  9133. gbone = this.geometry.bones[ b ];
  9134. bone = this.bones[ b ];
  9135. if ( gbone.parent === -1 ) {
  9136. this.add( bone );
  9137. } else {
  9138. this.bones[ gbone.parent ].add( bone );
  9139. }
  9140. }
  9141. //
  9142. var nBones = this.bones.length;
  9143. if ( this.useVertexTexture ) {
  9144. // layout (1 matrix = 4 pixels)
  9145. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9146. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9147. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9148. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9149. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9150. var size;
  9151. if ( nBones > 256 )
  9152. size = 64;
  9153. else if ( nBones > 64 )
  9154. size = 32;
  9155. else if ( nBones > 16 )
  9156. size = 16;
  9157. else
  9158. size = 8;
  9159. this.boneTextureWidth = size;
  9160. this.boneTextureHeight = size;
  9161. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9162. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9163. this.boneTexture.minFilter = THREE.NearestFilter;
  9164. this.boneTexture.magFilter = THREE.NearestFilter;
  9165. this.boneTexture.generateMipmaps = false;
  9166. this.boneTexture.flipY = false;
  9167. } else {
  9168. this.boneMatrices = new Float32Array( 16 * nBones );
  9169. }
  9170. this.pose();
  9171. }
  9172. };
  9173. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9174. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  9175. if ( bone === undefined ) {
  9176. bone = new THREE.Bone( this );
  9177. }
  9178. this.bones.push( bone );
  9179. return bone;
  9180. };
  9181. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  9182. var offsetMatrix = new THREE.Matrix4();
  9183. return function ( force ) {
  9184. this.matrixAutoUpdate && this.updateMatrix();
  9185. // update matrixWorld
  9186. if ( this.matrixWorldNeedsUpdate || force ) {
  9187. if ( this.parent ) {
  9188. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9189. } else {
  9190. this.matrixWorld.copy( this.matrix );
  9191. }
  9192. this.matrixWorldNeedsUpdate = false;
  9193. force = true;
  9194. }
  9195. // update children
  9196. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9197. var child = this.children[ i ];
  9198. if ( child instanceof THREE.Bone ) {
  9199. child.update( this.identityMatrix, false );
  9200. } else {
  9201. child.updateMatrixWorld( true );
  9202. }
  9203. }
  9204. // make a snapshot of the bones' rest position
  9205. if ( this.boneInverses == undefined ) {
  9206. this.boneInverses = [];
  9207. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9208. var inverse = new THREE.Matrix4();
  9209. inverse.getInverse( this.bones[ b ].skinMatrix );
  9210. this.boneInverses.push( inverse );
  9211. }
  9212. }
  9213. // flatten bone matrices to array
  9214. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9215. // compute the offset between the current and the original transform;
  9216. // TODO: we could get rid of this multiplication step if the skinMatrix
  9217. // was already representing the offset; however, this requires some
  9218. // major changes to the animation system
  9219. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  9220. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9221. }
  9222. if ( this.useVertexTexture ) {
  9223. this.boneTexture.needsUpdate = true;
  9224. }
  9225. };
  9226. }();
  9227. THREE.SkinnedMesh.prototype.pose = function () {
  9228. this.updateMatrixWorld( true );
  9229. this.normalizeSkinWeights();
  9230. };
  9231. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9232. if ( this.geometry instanceof THREE.Geometry ) {
  9233. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9234. var sw = this.geometry.skinWeights[ i ];
  9235. var scale = 1.0 / sw.lengthManhattan();
  9236. if ( scale !== Infinity ) {
  9237. sw.multiplyScalar( scale );
  9238. } else {
  9239. sw.set( 1 ); // this will be normalized by the shader anyway
  9240. }
  9241. }
  9242. } else {
  9243. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9244. }
  9245. };
  9246. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  9247. if ( object === undefined ) {
  9248. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9249. }
  9250. THREE.Mesh.prototype.clone.call( this, object );
  9251. return object;
  9252. };
  9253. /**
  9254. * @author alteredq / http://alteredqualia.com/
  9255. */
  9256. THREE.MorphAnimMesh = function ( geometry, material ) {
  9257. THREE.Mesh.call( this, geometry, material );
  9258. // API
  9259. this.duration = 1000; // milliseconds
  9260. this.mirroredLoop = false;
  9261. this.time = 0;
  9262. // internals
  9263. this.lastKeyframe = 0;
  9264. this.currentKeyframe = 0;
  9265. this.direction = 1;
  9266. this.directionBackwards = false;
  9267. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9268. };
  9269. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9270. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9271. this.startKeyframe = start;
  9272. this.endKeyframe = end;
  9273. this.length = this.endKeyframe - this.startKeyframe + 1;
  9274. };
  9275. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9276. this.direction = 1;
  9277. this.directionBackwards = false;
  9278. };
  9279. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9280. this.direction = -1;
  9281. this.directionBackwards = true;
  9282. };
  9283. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9284. var geometry = this.geometry;
  9285. if ( ! geometry.animations ) geometry.animations = {};
  9286. var firstAnimation, animations = geometry.animations;
  9287. var pattern = /([a-z]+)(\d+)/;
  9288. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9289. var morph = geometry.morphTargets[ i ];
  9290. var parts = morph.name.match( pattern );
  9291. if ( parts && parts.length > 1 ) {
  9292. var label = parts[ 1 ];
  9293. var num = parts[ 2 ];
  9294. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  9295. var animation = animations[ label ];
  9296. if ( i < animation.start ) animation.start = i;
  9297. if ( i > animation.end ) animation.end = i;
  9298. if ( ! firstAnimation ) firstAnimation = label;
  9299. }
  9300. }
  9301. geometry.firstAnimation = firstAnimation;
  9302. };
  9303. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9304. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9305. this.geometry.animations[ label ] = { start: start, end: end };
  9306. };
  9307. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9308. var animation = this.geometry.animations[ label ];
  9309. if ( animation ) {
  9310. this.setFrameRange( animation.start, animation.end );
  9311. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9312. this.time = 0;
  9313. } else {
  9314. console.warn( "animation[" + label + "] undefined" );
  9315. }
  9316. };
  9317. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9318. var frameTime = this.duration / this.length;
  9319. this.time += this.direction * delta;
  9320. if ( this.mirroredLoop ) {
  9321. if ( this.time > this.duration || this.time < 0 ) {
  9322. this.direction *= -1;
  9323. if ( this.time > this.duration ) {
  9324. this.time = this.duration;
  9325. this.directionBackwards = true;
  9326. }
  9327. if ( this.time < 0 ) {
  9328. this.time = 0;
  9329. this.directionBackwards = false;
  9330. }
  9331. }
  9332. } else {
  9333. this.time = this.time % this.duration;
  9334. if ( this.time < 0 ) this.time += this.duration;
  9335. }
  9336. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9337. if ( keyframe !== this.currentKeyframe ) {
  9338. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9339. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9340. this.morphTargetInfluences[ keyframe ] = 0;
  9341. this.lastKeyframe = this.currentKeyframe;
  9342. this.currentKeyframe = keyframe;
  9343. }
  9344. var mix = ( this.time % frameTime ) / frameTime;
  9345. if ( this.directionBackwards ) {
  9346. mix = 1 - mix;
  9347. }
  9348. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9349. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9350. };
  9351. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9352. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9353. object.duration = this.duration;
  9354. object.mirroredLoop = this.mirroredLoop;
  9355. object.time = this.time;
  9356. object.lastKeyframe = this.lastKeyframe;
  9357. object.currentKeyframe = this.currentKeyframe;
  9358. object.direction = this.direction;
  9359. object.directionBackwards = this.directionBackwards;
  9360. THREE.Mesh.prototype.clone.call( this, object );
  9361. return object;
  9362. };
  9363. /**
  9364. * @author mikael emtinger / http://gomo.se/
  9365. * @author alteredq / http://alteredqualia.com/
  9366. * @author mrdoob / http://mrdoob.com/
  9367. */
  9368. THREE.LOD = function () {
  9369. THREE.Object3D.call( this );
  9370. this.objects = [];
  9371. };
  9372. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9373. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9374. if ( distance === undefined ) distance = 0;
  9375. distance = Math.abs( distance );
  9376. for ( var l = 0; l < this.objects.length; l ++ ) {
  9377. if ( distance < this.objects[ l ].distance ) {
  9378. break;
  9379. }
  9380. }
  9381. this.objects.splice( l, 0, { distance: distance, object: object } );
  9382. this.add( object );
  9383. };
  9384. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9385. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9386. if ( distance < this.objects[ i ].distance ) {
  9387. break;
  9388. }
  9389. }
  9390. return this.objects[ i - 1 ].object;
  9391. };
  9392. THREE.LOD.prototype.update = function () {
  9393. var v1 = new THREE.Vector3();
  9394. var v2 = new THREE.Vector3();
  9395. return function ( camera ) {
  9396. if ( this.objects.length > 1 ) {
  9397. v1.setFromMatrixPosition( camera.matrixWorld );
  9398. v2.setFromMatrixPosition( this.matrixWorld );
  9399. var distance = v1.distanceTo( v2 );
  9400. this.objects[ 0 ].object.visible = true;
  9401. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9402. if ( distance >= this.objects[ i ].distance ) {
  9403. this.objects[ i - 1 ].object.visible = false;
  9404. this.objects[ i ].object.visible = true;
  9405. } else {
  9406. break;
  9407. }
  9408. }
  9409. for( ; i < l; i ++ ) {
  9410. this.objects[ i ].object.visible = false;
  9411. }
  9412. }
  9413. };
  9414. }();
  9415. THREE.LOD.prototype.clone = function ( object ) {
  9416. if ( object === undefined ) object = new THREE.LOD();
  9417. THREE.Object3D.prototype.clone.call( this, object );
  9418. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9419. var x = this.objects[i].object.clone();
  9420. x.visible = i === 0;
  9421. object.addLevel( x, this.objects[i].distance );
  9422. }
  9423. return object;
  9424. };
  9425. /**
  9426. * @author mikael emtinger / http://gomo.se/
  9427. * @author alteredq / http://alteredqualia.com/
  9428. */
  9429. THREE.Sprite = ( function () {
  9430. var geometry = new THREE.BufferGeometry();
  9431. geometry.addAttribute( 'position', new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] ), 3 );
  9432. return function ( material ) {
  9433. THREE.Object3D.call( this );
  9434. this.geometry = geometry;
  9435. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9436. };
  9437. } )();
  9438. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9439. /*
  9440. * Custom update matrix
  9441. */
  9442. THREE.Sprite.prototype.updateMatrix = function () {
  9443. this.matrix.compose( this.position, this.quaternion, this.scale );
  9444. this.matrixWorldNeedsUpdate = true;
  9445. };
  9446. THREE.Sprite.prototype.clone = function ( object ) {
  9447. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9448. THREE.Object3D.prototype.clone.call( this, object );
  9449. return object;
  9450. };
  9451. // Backwards compatibility
  9452. THREE.Particle = THREE.Sprite;
  9453. /**
  9454. * @author mrdoob / http://mrdoob.com/
  9455. */
  9456. THREE.Scene = function () {
  9457. THREE.Object3D.call( this );
  9458. this.fog = null;
  9459. this.overrideMaterial = null;
  9460. this.autoUpdate = true; // checked by the renderer
  9461. this.matrixAutoUpdate = false;
  9462. this.__lights = [];
  9463. this.__objectsAdded = [];
  9464. this.__objectsRemoved = [];
  9465. };
  9466. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9467. THREE.Scene.prototype.__addObject = function ( object ) {
  9468. if ( object instanceof THREE.Light ) {
  9469. if ( this.__lights.indexOf( object ) === - 1 ) {
  9470. this.__lights.push( object );
  9471. }
  9472. if ( object.target && object.target.parent === undefined ) {
  9473. this.add( object.target );
  9474. }
  9475. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9476. this.__objectsAdded.push( object );
  9477. // check if previously removed
  9478. var i = this.__objectsRemoved.indexOf( object );
  9479. if ( i !== -1 ) {
  9480. this.__objectsRemoved.splice( i, 1 );
  9481. }
  9482. }
  9483. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9484. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9485. for ( var c = 0; c < object.children.length; c ++ ) {
  9486. this.__addObject( object.children[ c ] );
  9487. }
  9488. };
  9489. THREE.Scene.prototype.__removeObject = function ( object ) {
  9490. if ( object instanceof THREE.Light ) {
  9491. var i = this.__lights.indexOf( object );
  9492. if ( i !== -1 ) {
  9493. this.__lights.splice( i, 1 );
  9494. }
  9495. if ( object.shadowCascadeArray ) {
  9496. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9497. this.__removeObject( object.shadowCascadeArray[ x ] );
  9498. }
  9499. }
  9500. } else if ( !( object instanceof THREE.Camera ) ) {
  9501. this.__objectsRemoved.push( object );
  9502. // check if previously added
  9503. var i = this.__objectsAdded.indexOf( object );
  9504. if ( i !== -1 ) {
  9505. this.__objectsAdded.splice( i, 1 );
  9506. }
  9507. }
  9508. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9509. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9510. for ( var c = 0; c < object.children.length; c ++ ) {
  9511. this.__removeObject( object.children[ c ] );
  9512. }
  9513. };
  9514. THREE.Scene.prototype.clone = function ( object ) {
  9515. if ( object === undefined ) object = new THREE.Scene();
  9516. THREE.Object3D.prototype.clone.call(this, object);
  9517. if ( this.fog !== null ) object.fog = this.fog.clone();
  9518. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9519. object.autoUpdate = this.autoUpdate;
  9520. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9521. return object;
  9522. };
  9523. /**
  9524. * @author mrdoob / http://mrdoob.com/
  9525. * @author alteredq / http://alteredqualia.com/
  9526. */
  9527. THREE.Fog = function ( color, near, far ) {
  9528. this.name = '';
  9529. this.color = new THREE.Color( color );
  9530. this.near = ( near !== undefined ) ? near : 1;
  9531. this.far = ( far !== undefined ) ? far : 1000;
  9532. };
  9533. THREE.Fog.prototype.clone = function () {
  9534. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9535. };
  9536. /**
  9537. * @author mrdoob / http://mrdoob.com/
  9538. * @author alteredq / http://alteredqualia.com/
  9539. */
  9540. THREE.FogExp2 = function ( color, density ) {
  9541. this.name = '';
  9542. this.color = new THREE.Color( color );
  9543. this.density = ( density !== undefined ) ? density : 0.00025;
  9544. };
  9545. THREE.FogExp2.prototype.clone = function () {
  9546. return new THREE.FogExp2( this.color.getHex(), this.density );
  9547. };
  9548. /**
  9549. * @author mrdoob / http://mrdoob.com/
  9550. */
  9551. THREE.CanvasRenderer = function ( parameters ) {
  9552. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9553. var smoothstep = THREE.Math.smoothstep;
  9554. parameters = parameters || {};
  9555. var _this = this,
  9556. _renderData, _elements, _lights,
  9557. _projector = new THREE.Projector(),
  9558. _canvas = parameters.canvas !== undefined
  9559. ? parameters.canvas
  9560. : document.createElement( 'canvas' ),
  9561. _canvasWidth = _canvas.width,
  9562. _canvasHeight = _canvas.height,
  9563. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9564. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9565. _context = _canvas.getContext( '2d', {
  9566. alpha: parameters.alpha === true
  9567. } ),
  9568. _clearColor = new THREE.Color( 0x000000 ),
  9569. _clearAlpha = 0,
  9570. _contextGlobalAlpha = 1,
  9571. _contextGlobalCompositeOperation = 0,
  9572. _contextStrokeStyle = null,
  9573. _contextFillStyle = null,
  9574. _contextLineWidth = null,
  9575. _contextLineCap = null,
  9576. _contextLineJoin = null,
  9577. _contextDashSize = null,
  9578. _contextGapSize = 0,
  9579. _camera,
  9580. _v1, _v2, _v3, _v4,
  9581. _v5 = new THREE.RenderableVertex(),
  9582. _v6 = new THREE.RenderableVertex(),
  9583. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9584. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9585. _color = new THREE.Color(),
  9586. _color1 = new THREE.Color(),
  9587. _color2 = new THREE.Color(),
  9588. _color3 = new THREE.Color(),
  9589. _color4 = new THREE.Color(),
  9590. _diffuseColor = new THREE.Color(),
  9591. _emissiveColor = new THREE.Color(),
  9592. _lightColor = new THREE.Color(),
  9593. _patterns = {},
  9594. _image, _uvs,
  9595. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9596. _clipBox = new THREE.Box2(),
  9597. _clearBox = new THREE.Box2(),
  9598. _elemBox = new THREE.Box2(),
  9599. _ambientLight = new THREE.Color(),
  9600. _directionalLights = new THREE.Color(),
  9601. _pointLights = new THREE.Color(),
  9602. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9603. _centroid = new THREE.Vector3(),
  9604. _normal = new THREE.Vector3(),
  9605. _normalViewMatrix = new THREE.Matrix3();
  9606. // dash+gap fallbacks for Firefox and everything else
  9607. if ( _context.setLineDash === undefined ) {
  9608. if ( _context.mozDash !== undefined ) {
  9609. _context.setLineDash = function ( values ) {
  9610. _context.mozDash = values[ 0 ] !== null ? values : null;
  9611. }
  9612. } else {
  9613. _context.setLineDash = function () {}
  9614. }
  9615. }
  9616. this.domElement = _canvas;
  9617. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9618. ? parameters.devicePixelRatio
  9619. : self.devicePixelRatio !== undefined
  9620. ? self.devicePixelRatio
  9621. : 1;
  9622. this.autoClear = true;
  9623. this.sortObjects = true;
  9624. this.sortElements = true;
  9625. this.info = {
  9626. render: {
  9627. vertices: 0,
  9628. faces: 0
  9629. }
  9630. }
  9631. // WebGLRenderer compatibility
  9632. this.supportsVertexTextures = function () {};
  9633. this.setFaceCulling = function () {};
  9634. this.setSize = function ( width, height, updateStyle ) {
  9635. _canvasWidth = width * this.devicePixelRatio;
  9636. _canvasHeight = height * this.devicePixelRatio;
  9637. _canvas.width = _canvasWidth;
  9638. _canvas.height = _canvasHeight;
  9639. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9640. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9641. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9642. _canvas.style.width = width + 'px';
  9643. _canvas.style.height = height + 'px';
  9644. }
  9645. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  9646. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9647. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9648. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9649. _contextGlobalAlpha = 1;
  9650. _contextGlobalCompositeOperation = 0;
  9651. _contextStrokeStyle = null;
  9652. _contextFillStyle = null;
  9653. _contextLineWidth = null;
  9654. _contextLineCap = null;
  9655. _contextLineJoin = null;
  9656. this.setViewport( 0, 0, width, height );
  9657. };
  9658. this.setViewport = function ( x, y, width, height ) {
  9659. _context.setTransform( width / _canvasWidth, 0, 0, - height / _canvasHeight, x, _canvasHeight - y );
  9660. _context.translate( _canvasWidthHalf, _canvasHeightHalf );
  9661. };
  9662. this.setScissor = function () {};
  9663. this.enableScissorTest = function () {};
  9664. this.setClearColor = function ( color, alpha ) {
  9665. _clearColor.set( color );
  9666. _clearAlpha = alpha !== undefined ? alpha : 1;
  9667. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9668. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9669. };
  9670. this.setClearColorHex = function ( hex, alpha ) {
  9671. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9672. this.setClearColor( hex, alpha );
  9673. };
  9674. this.getMaxAnisotropy = function () {
  9675. return 0;
  9676. };
  9677. this.clear = function () {
  9678. if ( _clearBox.empty() === false ) {
  9679. _clearBox.intersect( _clipBox );
  9680. _clearBox.expandByScalar( 2 );
  9681. if ( _clearAlpha < 1 ) {
  9682. _context.clearRect(
  9683. _clearBox.min.x | 0,
  9684. _clearBox.min.y | 0,
  9685. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9686. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9687. );
  9688. }
  9689. if ( _clearAlpha > 0 ) {
  9690. setBlending( THREE.NormalBlending );
  9691. setOpacity( 1 );
  9692. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9693. _context.fillRect(
  9694. _clearBox.min.x | 0,
  9695. _clearBox.min.y | 0,
  9696. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9697. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9698. );
  9699. }
  9700. _clearBox.makeEmpty();
  9701. }
  9702. };
  9703. // compatibility
  9704. this.clearColor = function () {};
  9705. this.clearDepth = function () {};
  9706. this.clearStencil = function () {};
  9707. this.render = function ( scene, camera ) {
  9708. if ( camera instanceof THREE.Camera === false ) {
  9709. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9710. return;
  9711. }
  9712. if ( this.autoClear === true ) this.clear();
  9713. _this.info.render.vertices = 0;
  9714. _this.info.render.faces = 0;
  9715. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9716. _elements = _renderData.elements;
  9717. _lights = _renderData.lights;
  9718. _camera = camera;
  9719. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  9720. /* DEBUG
  9721. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9722. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9723. */
  9724. calculateLights();
  9725. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  9726. var element = _elements[ e ];
  9727. var material = element.material;
  9728. if ( material === undefined || material.visible === false ) continue;
  9729. _elemBox.makeEmpty();
  9730. if ( element instanceof THREE.RenderableSprite ) {
  9731. _v1 = element;
  9732. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9733. renderSprite( _v1, element, material );
  9734. } else if ( element instanceof THREE.RenderableLine ) {
  9735. _v1 = element.v1; _v2 = element.v2;
  9736. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9737. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9738. _elemBox.setFromPoints( [
  9739. _v1.positionScreen,
  9740. _v2.positionScreen
  9741. ] );
  9742. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9743. renderLine( _v1, _v2, element, material );
  9744. }
  9745. } else if ( element instanceof THREE.RenderableFace ) {
  9746. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9747. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9748. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9749. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9750. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9751. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9752. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9753. if ( material.overdraw > 0 ) {
  9754. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9755. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9756. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9757. }
  9758. _elemBox.setFromPoints( [
  9759. _v1.positionScreen,
  9760. _v2.positionScreen,
  9761. _v3.positionScreen
  9762. ] );
  9763. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9764. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9765. }
  9766. }
  9767. /* DEBUG
  9768. setLineWidth( 1 );
  9769. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9770. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9771. */
  9772. _clearBox.union( _elemBox );
  9773. }
  9774. /* DEBUG
  9775. setLineWidth( 1 );
  9776. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9777. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9778. */
  9779. // _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9780. };
  9781. //
  9782. function calculateLights() {
  9783. _ambientLight.setRGB( 0, 0, 0 );
  9784. _directionalLights.setRGB( 0, 0, 0 );
  9785. _pointLights.setRGB( 0, 0, 0 );
  9786. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9787. var light = _lights[ l ];
  9788. var lightColor = light.color;
  9789. if ( light instanceof THREE.AmbientLight ) {
  9790. _ambientLight.add( lightColor );
  9791. } else if ( light instanceof THREE.DirectionalLight ) {
  9792. // for sprites
  9793. _directionalLights.add( lightColor );
  9794. } else if ( light instanceof THREE.PointLight ) {
  9795. // for sprites
  9796. _pointLights.add( lightColor );
  9797. }
  9798. }
  9799. }
  9800. function calculateLight( position, normal, color ) {
  9801. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9802. var light = _lights[ l ];
  9803. _lightColor.copy( light.color );
  9804. if ( light instanceof THREE.DirectionalLight ) {
  9805. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9806. var amount = normal.dot( lightPosition );
  9807. if ( amount <= 0 ) continue;
  9808. amount *= light.intensity;
  9809. color.add( _lightColor.multiplyScalar( amount ) );
  9810. } else if ( light instanceof THREE.PointLight ) {
  9811. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9812. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9813. if ( amount <= 0 ) continue;
  9814. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9815. if ( amount == 0 ) continue;
  9816. amount *= light.intensity;
  9817. color.add( _lightColor.multiplyScalar( amount ) );
  9818. }
  9819. }
  9820. }
  9821. function renderSprite( v1, element, material ) {
  9822. setOpacity( material.opacity );
  9823. setBlending( material.blending );
  9824. var scaleX = element.scale.x * _canvasWidthHalf;
  9825. var scaleY = element.scale.y * _canvasHeightHalf;
  9826. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9827. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9828. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9829. if ( material instanceof THREE.SpriteMaterial ||
  9830. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9831. var texture = material.map;
  9832. if ( texture !== null ) {
  9833. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9834. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9835. textureToPattern( texture );
  9836. }
  9837. texture.addEventListener( 'update', onTextureUpdate );
  9838. }
  9839. var pattern = _patterns[ texture.id ];
  9840. if ( pattern !== undefined ) {
  9841. setFillStyle( pattern );
  9842. } else {
  9843. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  9844. }
  9845. //
  9846. var bitmap = texture.image;
  9847. var ox = bitmap.width * texture.offset.x;
  9848. var oy = bitmap.height * texture.offset.y;
  9849. var sx = bitmap.width * texture.repeat.x;
  9850. var sy = bitmap.height * texture.repeat.y;
  9851. var cx = scaleX / sx;
  9852. var cy = scaleY / sy;
  9853. _context.save();
  9854. _context.translate( v1.x, v1.y );
  9855. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9856. _context.translate( - scaleX / 2, - scaleY / 2 );
  9857. _context.scale( cx, cy );
  9858. _context.translate( - ox, - oy );
  9859. _context.fillRect( ox, oy, sx, sy );
  9860. _context.restore();
  9861. } else { // no texture
  9862. setFillStyle( material.color.getStyle() );
  9863. _context.save();
  9864. _context.translate( v1.x, v1.y );
  9865. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9866. _context.scale( scaleX, - scaleY );
  9867. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9868. _context.restore();
  9869. }
  9870. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9871. setStrokeStyle( material.color.getStyle() );
  9872. setFillStyle( material.color.getStyle() );
  9873. _context.save();
  9874. _context.translate( v1.x, v1.y );
  9875. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9876. _context.scale( scaleX, scaleY );
  9877. material.program( _context );
  9878. _context.restore();
  9879. }
  9880. /* DEBUG
  9881. setStrokeStyle( 'rgb(255,255,0)' );
  9882. _context.beginPath();
  9883. _context.moveTo( v1.x - 10, v1.y );
  9884. _context.lineTo( v1.x + 10, v1.y );
  9885. _context.moveTo( v1.x, v1.y - 10 );
  9886. _context.lineTo( v1.x, v1.y + 10 );
  9887. _context.stroke();
  9888. */
  9889. }
  9890. function renderLine( v1, v2, element, material ) {
  9891. setOpacity( material.opacity );
  9892. setBlending( material.blending );
  9893. _context.beginPath();
  9894. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9895. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9896. if ( material instanceof THREE.LineBasicMaterial ) {
  9897. setLineWidth( material.linewidth );
  9898. setLineCap( material.linecap );
  9899. setLineJoin( material.linejoin );
  9900. if ( material.vertexColors !== THREE.VertexColors ) {
  9901. setStrokeStyle( material.color.getStyle() );
  9902. } else {
  9903. var colorStyle1 = element.vertexColors[0].getStyle();
  9904. var colorStyle2 = element.vertexColors[1].getStyle();
  9905. if ( colorStyle1 === colorStyle2 ) {
  9906. setStrokeStyle( colorStyle1 );
  9907. } else {
  9908. try {
  9909. var grad = _context.createLinearGradient(
  9910. v1.positionScreen.x,
  9911. v1.positionScreen.y,
  9912. v2.positionScreen.x,
  9913. v2.positionScreen.y
  9914. );
  9915. grad.addColorStop( 0, colorStyle1 );
  9916. grad.addColorStop( 1, colorStyle2 );
  9917. } catch ( exception ) {
  9918. grad = colorStyle1;
  9919. }
  9920. setStrokeStyle( grad );
  9921. }
  9922. }
  9923. _context.stroke();
  9924. _elemBox.expandByScalar( material.linewidth * 2 );
  9925. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9926. setLineWidth( material.linewidth );
  9927. setLineCap( material.linecap );
  9928. setLineJoin( material.linejoin );
  9929. setStrokeStyle( material.color.getStyle() );
  9930. setDashAndGap( material.dashSize, material.gapSize );
  9931. _context.stroke();
  9932. _elemBox.expandByScalar( material.linewidth * 2 );
  9933. setDashAndGap( null, null );
  9934. }
  9935. }
  9936. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9937. _this.info.render.vertices += 3;
  9938. _this.info.render.faces ++;
  9939. setOpacity( material.opacity );
  9940. setBlending( material.blending );
  9941. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9942. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9943. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9944. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9945. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9946. _diffuseColor.copy( material.color );
  9947. _emissiveColor.copy( material.emissive );
  9948. if ( material.vertexColors === THREE.FaceColors ) {
  9949. _diffuseColor.multiply( element.color );
  9950. }
  9951. _color.copy( _ambientLight );
  9952. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  9953. calculateLight( _centroid, element.normalModel, _color );
  9954. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9955. material.wireframe === true
  9956. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9957. : fillPath( _color );
  9958. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9959. if ( material.map !== null ) {
  9960. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9961. _uvs = element.uvs[ 0 ];
  9962. 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 );
  9963. }
  9964. } else if ( material.envMap !== null ) {
  9965. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9966. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9967. _uv1x = 0.5 * _normal.x + 0.5;
  9968. _uv1y = 0.5 * _normal.y + 0.5;
  9969. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9970. _uv2x = 0.5 * _normal.x + 0.5;
  9971. _uv2y = 0.5 * _normal.y + 0.5;
  9972. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9973. _uv3x = 0.5 * _normal.x + 0.5;
  9974. _uv3y = 0.5 * _normal.y + 0.5;
  9975. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9976. } else if ( material.envMap.mapping instanceof THREE.SphericalRefractionMapping ) {
  9977. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  9978. _uv1x = - 0.5 * _normal.x + 0.5;
  9979. _uv1y = - 0.5 * _normal.y + 0.5;
  9980. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  9981. _uv2x = - 0.5 * _normal.x + 0.5;
  9982. _uv2y = - 0.5 * _normal.y + 0.5;
  9983. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  9984. _uv3x = - 0.5 * _normal.x + 0.5;
  9985. _uv3y = - 0.5 * _normal.y + 0.5;
  9986. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9987. }
  9988. } else {
  9989. _color.copy( material.color );
  9990. if ( material.vertexColors === THREE.FaceColors ) {
  9991. _color.multiply( element.color );
  9992. }
  9993. material.wireframe === true
  9994. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9995. : fillPath( _color );
  9996. }
  9997. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9998. _color.r = _color.g = _color.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _camera.near, _camera.far );
  9999. material.wireframe === true
  10000. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10001. : fillPath( _color );
  10002. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  10003. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  10004. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  10005. material.wireframe === true
  10006. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10007. : fillPath( _color );
  10008. }
  10009. }
  10010. //
  10011. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  10012. _context.beginPath();
  10013. _context.moveTo( x0, y0 );
  10014. _context.lineTo( x1, y1 );
  10015. _context.lineTo( x2, y2 );
  10016. _context.closePath();
  10017. }
  10018. function strokePath( color, linewidth, linecap, linejoin ) {
  10019. setLineWidth( linewidth );
  10020. setLineCap( linecap );
  10021. setLineJoin( linejoin );
  10022. setStrokeStyle( color.getStyle() );
  10023. _context.stroke();
  10024. _elemBox.expandByScalar( linewidth * 2 );
  10025. }
  10026. function fillPath( color ) {
  10027. setFillStyle( color.getStyle() );
  10028. _context.fill();
  10029. }
  10030. function onTextureUpdate ( event ) {
  10031. textureToPattern( event.target );
  10032. }
  10033. function textureToPattern( texture ) {
  10034. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  10035. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  10036. var image = texture.image;
  10037. var canvas = document.createElement( 'canvas' );
  10038. canvas.width = image.width;
  10039. canvas.height = image.height;
  10040. var context = canvas.getContext( '2d' );
  10041. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  10042. context.drawImage( image, 0, 0 );
  10043. _patterns[ texture.id ] = _context.createPattern(
  10044. canvas, repeatX === true && repeatY === true
  10045. ? 'repeat'
  10046. : repeatX === true && repeatY === false
  10047. ? 'repeat-x'
  10048. : repeatX === false && repeatY === true
  10049. ? 'repeat-y'
  10050. : 'no-repeat'
  10051. );
  10052. }
  10053. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  10054. if ( texture instanceof THREE.DataTexture ) return;
  10055. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10056. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10057. textureToPattern( texture );
  10058. }
  10059. texture.addEventListener( 'update', onTextureUpdate );
  10060. }
  10061. var pattern = _patterns[ texture.id ];
  10062. if ( pattern !== undefined ) {
  10063. setFillStyle( pattern );
  10064. } else {
  10065. setFillStyle( 'rgba(0,0,0,1)' );
  10066. _context.fill();
  10067. return;
  10068. }
  10069. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10070. var a, b, c, d, e, f, det, idet,
  10071. offsetX = texture.offset.x / texture.repeat.x,
  10072. offsetY = texture.offset.y / texture.repeat.y,
  10073. width = texture.image.width * texture.repeat.x,
  10074. height = texture.image.height * texture.repeat.y;
  10075. u0 = ( u0 + offsetX ) * width;
  10076. v0 = ( v0 + offsetY ) * height;
  10077. u1 = ( u1 + offsetX ) * width;
  10078. v1 = ( v1 + offsetY ) * height;
  10079. u2 = ( u2 + offsetX ) * width;
  10080. v2 = ( v2 + offsetY ) * height;
  10081. x1 -= x0; y1 -= y0;
  10082. x2 -= x0; y2 -= y0;
  10083. u1 -= u0; v1 -= v0;
  10084. u2 -= u0; v2 -= v0;
  10085. det = u1 * v2 - u2 * v1;
  10086. if ( det === 0 ) return;
  10087. idet = 1 / det;
  10088. a = ( v2 * x1 - v1 * x2 ) * idet;
  10089. b = ( v2 * y1 - v1 * y2 ) * idet;
  10090. c = ( u1 * x2 - u2 * x1 ) * idet;
  10091. d = ( u1 * y2 - u2 * y1 ) * idet;
  10092. e = x0 - a * u0 - c * v0;
  10093. f = y0 - b * u0 - d * v0;
  10094. _context.save();
  10095. _context.transform( a, b, c, d, e, f );
  10096. _context.fill();
  10097. _context.restore();
  10098. }
  10099. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  10100. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10101. var a, b, c, d, e, f, det, idet,
  10102. width = image.width - 1,
  10103. height = image.height - 1;
  10104. u0 *= width; v0 *= height;
  10105. u1 *= width; v1 *= height;
  10106. u2 *= width; v2 *= height;
  10107. x1 -= x0; y1 -= y0;
  10108. x2 -= x0; y2 -= y0;
  10109. u1 -= u0; v1 -= v0;
  10110. u2 -= u0; v2 -= v0;
  10111. det = u1 * v2 - u2 * v1;
  10112. idet = 1 / det;
  10113. a = ( v2 * x1 - v1 * x2 ) * idet;
  10114. b = ( v2 * y1 - v1 * y2 ) * idet;
  10115. c = ( u1 * x2 - u2 * x1 ) * idet;
  10116. d = ( u1 * y2 - u2 * y1 ) * idet;
  10117. e = x0 - a * u0 - c * v0;
  10118. f = y0 - b * u0 - d * v0;
  10119. _context.save();
  10120. _context.transform( a, b, c, d, e, f );
  10121. _context.clip();
  10122. _context.drawImage( image, 0, 0 );
  10123. _context.restore();
  10124. }
  10125. // Hide anti-alias gaps
  10126. function expand( v1, v2, pixels ) {
  10127. var x = v2.x - v1.x, y = v2.y - v1.y,
  10128. det = x * x + y * y, idet;
  10129. if ( det === 0 ) return;
  10130. idet = pixels / Math.sqrt( det );
  10131. x *= idet; y *= idet;
  10132. v2.x += x; v2.y += y;
  10133. v1.x -= x; v1.y -= y;
  10134. }
  10135. // Context cached methods.
  10136. function setOpacity( value ) {
  10137. if ( _contextGlobalAlpha !== value ) {
  10138. _context.globalAlpha = value;
  10139. _contextGlobalAlpha = value;
  10140. }
  10141. }
  10142. function setBlending( value ) {
  10143. if ( _contextGlobalCompositeOperation !== value ) {
  10144. if ( value === THREE.NormalBlending ) {
  10145. _context.globalCompositeOperation = 'source-over';
  10146. } else if ( value === THREE.AdditiveBlending ) {
  10147. _context.globalCompositeOperation = 'lighter';
  10148. } else if ( value === THREE.SubtractiveBlending ) {
  10149. _context.globalCompositeOperation = 'darker';
  10150. }
  10151. _contextGlobalCompositeOperation = value;
  10152. }
  10153. }
  10154. function setLineWidth( value ) {
  10155. if ( _contextLineWidth !== value ) {
  10156. _context.lineWidth = value;
  10157. _contextLineWidth = value;
  10158. }
  10159. }
  10160. function setLineCap( value ) {
  10161. // "butt", "round", "square"
  10162. if ( _contextLineCap !== value ) {
  10163. _context.lineCap = value;
  10164. _contextLineCap = value;
  10165. }
  10166. }
  10167. function setLineJoin( value ) {
  10168. // "round", "bevel", "miter"
  10169. if ( _contextLineJoin !== value ) {
  10170. _context.lineJoin = value;
  10171. _contextLineJoin = value;
  10172. }
  10173. }
  10174. function setStrokeStyle( value ) {
  10175. if ( _contextStrokeStyle !== value ) {
  10176. _context.strokeStyle = value;
  10177. _contextStrokeStyle = value;
  10178. }
  10179. }
  10180. function setFillStyle( value ) {
  10181. if ( _contextFillStyle !== value ) {
  10182. _context.fillStyle = value;
  10183. _contextFillStyle = value;
  10184. }
  10185. }
  10186. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  10187. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  10188. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  10189. _contextDashSize = dashSizeValue;
  10190. _contextGapSize = gapSizeValue;
  10191. }
  10192. }
  10193. };
  10194. /**
  10195. * Shader chunks for WebLG Shader library
  10196. *
  10197. * @author alteredq / http://alteredqualia.com/
  10198. * @author mrdoob / http://mrdoob.com/
  10199. * @author mikael emtinger / http://gomo.se/
  10200. */
  10201. THREE.ShaderChunk = {
  10202. // FOG
  10203. fog_pars_fragment: [
  10204. "#ifdef USE_FOG",
  10205. " uniform vec3 fogColor;",
  10206. " #ifdef FOG_EXP2",
  10207. " uniform float fogDensity;",
  10208. " #else",
  10209. " uniform float fogNear;",
  10210. " uniform float fogFar;",
  10211. " #endif",
  10212. "#endif"
  10213. ].join("\n"),
  10214. fog_fragment: [
  10215. "#ifdef USE_FOG",
  10216. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10217. " #ifdef FOG_EXP2",
  10218. " const float LOG2 = 1.442695;",
  10219. " float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  10220. " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  10221. " #else",
  10222. " float fogFactor = smoothstep( fogNear, fogFar, depth );",
  10223. " #endif",
  10224. " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  10225. "#endif"
  10226. ].join("\n"),
  10227. // ENVIRONMENT MAP
  10228. envmap_pars_fragment: [
  10229. "#ifdef USE_ENVMAP",
  10230. " uniform float reflectivity;",
  10231. " uniform samplerCube envMap;",
  10232. " uniform float flipEnvMap;",
  10233. " uniform int combine;",
  10234. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10235. " uniform bool useRefract;",
  10236. " uniform float refractionRatio;",
  10237. " #else",
  10238. " varying vec3 vReflect;",
  10239. " #endif",
  10240. "#endif"
  10241. ].join("\n"),
  10242. envmap_fragment: [
  10243. "#ifdef USE_ENVMAP",
  10244. " vec3 reflectVec;",
  10245. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10246. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10247. " if ( useRefract ) {",
  10248. " reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  10249. " } else { ",
  10250. " reflectVec = reflect( cameraToVertex, normal );",
  10251. " }",
  10252. " #else",
  10253. " reflectVec = vReflect;",
  10254. " #endif",
  10255. " #ifdef DOUBLE_SIDED",
  10256. " float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10257. " vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10258. " #else",
  10259. " vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10260. " #endif",
  10261. " #ifdef GAMMA_INPUT",
  10262. " cubeColor.xyz *= cubeColor.xyz;",
  10263. " #endif",
  10264. " if ( combine == 1 ) {",
  10265. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  10266. " } else if ( combine == 2 ) {",
  10267. " gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  10268. " } else {",
  10269. " gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  10270. " }",
  10271. "#endif"
  10272. ].join("\n"),
  10273. envmap_pars_vertex: [
  10274. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10275. " varying vec3 vReflect;",
  10276. " uniform float refractionRatio;",
  10277. " uniform bool useRefract;",
  10278. "#endif"
  10279. ].join("\n"),
  10280. worldpos_vertex : [
  10281. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  10282. " #ifdef USE_SKINNING",
  10283. " vec4 worldPosition = modelMatrix * skinned;",
  10284. " #endif",
  10285. " #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10286. " vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  10287. " #endif",
  10288. " #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10289. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10290. " #endif",
  10291. "#endif"
  10292. ].join("\n"),
  10293. envmap_vertex : [
  10294. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10295. " vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10296. " worldNormal = normalize( worldNormal );",
  10297. " vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10298. " if ( useRefract ) {",
  10299. " vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10300. " } else {",
  10301. " vReflect = reflect( cameraToVertex, worldNormal );",
  10302. " }",
  10303. "#endif"
  10304. ].join("\n"),
  10305. // COLOR MAP (particles)
  10306. map_particle_pars_fragment: [
  10307. "#ifdef USE_MAP",
  10308. " uniform sampler2D map;",
  10309. "#endif"
  10310. ].join("\n"),
  10311. map_particle_fragment: [
  10312. "#ifdef USE_MAP",
  10313. " gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10314. "#endif"
  10315. ].join("\n"),
  10316. // COLOR MAP (triangles)
  10317. map_pars_vertex: [
  10318. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10319. " varying vec2 vUv;",
  10320. " uniform vec4 offsetRepeat;",
  10321. "#endif"
  10322. ].join("\n"),
  10323. map_pars_fragment: [
  10324. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10325. " varying vec2 vUv;",
  10326. "#endif",
  10327. "#ifdef USE_MAP",
  10328. " uniform sampler2D map;",
  10329. "#endif"
  10330. ].join("\n"),
  10331. map_vertex: [
  10332. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10333. " vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10334. "#endif"
  10335. ].join("\n"),
  10336. map_fragment: [
  10337. "#ifdef USE_MAP",
  10338. " vec4 texelColor = texture2D( map, vUv );",
  10339. " #ifdef GAMMA_INPUT",
  10340. " texelColor.xyz *= texelColor.xyz;",
  10341. " #endif",
  10342. " gl_FragColor = gl_FragColor * texelColor;",
  10343. "#endif"
  10344. ].join("\n"),
  10345. // LIGHT MAP
  10346. lightmap_pars_fragment: [
  10347. "#ifdef USE_LIGHTMAP",
  10348. " varying vec2 vUv2;",
  10349. " uniform sampler2D lightMap;",
  10350. "#endif"
  10351. ].join("\n"),
  10352. lightmap_pars_vertex: [
  10353. "#ifdef USE_LIGHTMAP",
  10354. " varying vec2 vUv2;",
  10355. "#endif"
  10356. ].join("\n"),
  10357. lightmap_fragment: [
  10358. "#ifdef USE_LIGHTMAP",
  10359. " gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10360. "#endif"
  10361. ].join("\n"),
  10362. lightmap_vertex: [
  10363. "#ifdef USE_LIGHTMAP",
  10364. " vUv2 = uv2;",
  10365. "#endif"
  10366. ].join("\n"),
  10367. // BUMP MAP
  10368. bumpmap_pars_fragment: [
  10369. "#ifdef USE_BUMPMAP",
  10370. " uniform sampler2D bumpMap;",
  10371. " uniform float bumpScale;",
  10372. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10373. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10374. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10375. " vec2 dHdxy_fwd() {",
  10376. " vec2 dSTdx = dFdx( vUv );",
  10377. " vec2 dSTdy = dFdy( vUv );",
  10378. " float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10379. " float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10380. " float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10381. " return vec2( dBx, dBy );",
  10382. " }",
  10383. " vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10384. " vec3 vSigmaX = dFdx( surf_pos );",
  10385. " vec3 vSigmaY = dFdy( surf_pos );",
  10386. " vec3 vN = surf_norm;", // normalized
  10387. " vec3 R1 = cross( vSigmaY, vN );",
  10388. " vec3 R2 = cross( vN, vSigmaX );",
  10389. " float fDet = dot( vSigmaX, R1 );",
  10390. " vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10391. " return normalize( abs( fDet ) * surf_norm - vGrad );",
  10392. " }",
  10393. "#endif"
  10394. ].join("\n"),
  10395. // NORMAL MAP
  10396. normalmap_pars_fragment: [
  10397. "#ifdef USE_NORMALMAP",
  10398. " uniform sampler2D normalMap;",
  10399. " uniform vec2 normalScale;",
  10400. // Per-Pixel Tangent Space Normal Mapping
  10401. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10402. " vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10403. " vec3 q0 = dFdx( eye_pos.xyz );",
  10404. " vec3 q1 = dFdy( eye_pos.xyz );",
  10405. " vec2 st0 = dFdx( vUv.st );",
  10406. " vec2 st1 = dFdy( vUv.st );",
  10407. " vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10408. " vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10409. " vec3 N = normalize( surf_norm );",
  10410. " vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10411. " mapN.xy = normalScale * mapN.xy;",
  10412. " mat3 tsn = mat3( S, T, N );",
  10413. " return normalize( tsn * mapN );",
  10414. " }",
  10415. "#endif"
  10416. ].join("\n"),
  10417. // SPECULAR MAP
  10418. specularmap_pars_fragment: [
  10419. "#ifdef USE_SPECULARMAP",
  10420. " uniform sampler2D specularMap;",
  10421. "#endif"
  10422. ].join("\n"),
  10423. specularmap_fragment: [
  10424. "float specularStrength;",
  10425. "#ifdef USE_SPECULARMAP",
  10426. " vec4 texelSpecular = texture2D( specularMap, vUv );",
  10427. " specularStrength = texelSpecular.r;",
  10428. "#else",
  10429. " specularStrength = 1.0;",
  10430. "#endif"
  10431. ].join("\n"),
  10432. // LIGHTS LAMBERT
  10433. lights_lambert_pars_vertex: [
  10434. "uniform vec3 ambient;",
  10435. "uniform vec3 diffuse;",
  10436. "uniform vec3 emissive;",
  10437. "uniform vec3 ambientLightColor;",
  10438. "#if MAX_DIR_LIGHTS > 0",
  10439. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10440. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10441. "#endif",
  10442. "#if MAX_HEMI_LIGHTS > 0",
  10443. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10444. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10445. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10446. "#endif",
  10447. "#if MAX_POINT_LIGHTS > 0",
  10448. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10449. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10450. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10451. "#endif",
  10452. "#if MAX_SPOT_LIGHTS > 0",
  10453. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10454. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10455. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10456. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10457. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10458. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10459. "#endif",
  10460. "#ifdef WRAP_AROUND",
  10461. " uniform vec3 wrapRGB;",
  10462. "#endif"
  10463. ].join("\n"),
  10464. lights_lambert_vertex: [
  10465. "vLightFront = vec3( 0.0 );",
  10466. "#ifdef DOUBLE_SIDED",
  10467. " vLightBack = vec3( 0.0 );",
  10468. "#endif",
  10469. "transformedNormal = normalize( transformedNormal );",
  10470. "#if MAX_DIR_LIGHTS > 0",
  10471. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10472. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10473. " vec3 dirVector = normalize( lDirection.xyz );",
  10474. " float dotProduct = dot( transformedNormal, dirVector );",
  10475. " vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10476. " #ifdef DOUBLE_SIDED",
  10477. " vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10478. " #ifdef WRAP_AROUND",
  10479. " vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10480. " #endif",
  10481. " #endif",
  10482. " #ifdef WRAP_AROUND",
  10483. " vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10484. " directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10485. " #ifdef DOUBLE_SIDED",
  10486. " directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10487. " #endif",
  10488. " #endif",
  10489. " vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10490. " #ifdef DOUBLE_SIDED",
  10491. " vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10492. " #endif",
  10493. "}",
  10494. "#endif",
  10495. "#if MAX_POINT_LIGHTS > 0",
  10496. " for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10497. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10498. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10499. " float lDistance = 1.0;",
  10500. " if ( pointLightDistance[ i ] > 0.0 )",
  10501. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10502. " lVector = normalize( lVector );",
  10503. " float dotProduct = dot( transformedNormal, lVector );",
  10504. " vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10505. " #ifdef DOUBLE_SIDED",
  10506. " vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10507. " #ifdef WRAP_AROUND",
  10508. " vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10509. " #endif",
  10510. " #endif",
  10511. " #ifdef WRAP_AROUND",
  10512. " vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10513. " pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10514. " #ifdef DOUBLE_SIDED",
  10515. " pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10516. " #endif",
  10517. " #endif",
  10518. " vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10519. " #ifdef DOUBLE_SIDED",
  10520. " vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10521. " #endif",
  10522. " }",
  10523. "#endif",
  10524. "#if MAX_SPOT_LIGHTS > 0",
  10525. " for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10526. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10527. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10528. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10529. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10530. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10531. " float lDistance = 1.0;",
  10532. " if ( spotLightDistance[ i ] > 0.0 )",
  10533. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10534. " lVector = normalize( lVector );",
  10535. " float dotProduct = dot( transformedNormal, lVector );",
  10536. " vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10537. " #ifdef DOUBLE_SIDED",
  10538. " vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10539. " #ifdef WRAP_AROUND",
  10540. " vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10541. " #endif",
  10542. " #endif",
  10543. " #ifdef WRAP_AROUND",
  10544. " vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10545. " spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10546. " #ifdef DOUBLE_SIDED",
  10547. " spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10548. " #endif",
  10549. " #endif",
  10550. " vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10551. " #ifdef DOUBLE_SIDED",
  10552. " vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10553. " #endif",
  10554. " }",
  10555. " }",
  10556. "#endif",
  10557. "#if MAX_HEMI_LIGHTS > 0",
  10558. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10559. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10560. " vec3 lVector = normalize( lDirection.xyz );",
  10561. " float dotProduct = dot( transformedNormal, lVector );",
  10562. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10563. " float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10564. " vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10565. " #ifdef DOUBLE_SIDED",
  10566. " vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10567. " #endif",
  10568. " }",
  10569. "#endif",
  10570. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10571. "#ifdef DOUBLE_SIDED",
  10572. " vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10573. "#endif"
  10574. ].join("\n"),
  10575. // LIGHTS PHONG
  10576. lights_phong_pars_vertex: [
  10577. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10578. " varying vec3 vWorldPosition;",
  10579. "#endif"
  10580. ].join("\n"),
  10581. lights_phong_vertex: [
  10582. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10583. " vWorldPosition = worldPosition.xyz;",
  10584. "#endif"
  10585. ].join("\n"),
  10586. lights_phong_pars_fragment: [
  10587. "uniform vec3 ambientLightColor;",
  10588. "#if MAX_DIR_LIGHTS > 0",
  10589. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10590. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10591. "#endif",
  10592. "#if MAX_HEMI_LIGHTS > 0",
  10593. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10594. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10595. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10596. "#endif",
  10597. "#if MAX_POINT_LIGHTS > 0",
  10598. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10599. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10600. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10601. "#endif",
  10602. "#if MAX_SPOT_LIGHTS > 0",
  10603. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10604. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10605. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10606. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10607. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10608. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10609. "#endif",
  10610. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10611. " varying vec3 vWorldPosition;",
  10612. "#endif",
  10613. "#ifdef WRAP_AROUND",
  10614. " uniform vec3 wrapRGB;",
  10615. "#endif",
  10616. "varying vec3 vViewPosition;",
  10617. "varying vec3 vNormal;"
  10618. ].join("\n"),
  10619. lights_phong_fragment: [
  10620. "vec3 normal = normalize( vNormal );",
  10621. "vec3 viewPosition = normalize( vViewPosition );",
  10622. "#ifdef DOUBLE_SIDED",
  10623. " normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10624. "#endif",
  10625. "#ifdef USE_NORMALMAP",
  10626. " normal = perturbNormal2Arb( -vViewPosition, normal );",
  10627. "#elif defined( USE_BUMPMAP )",
  10628. " normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10629. "#endif",
  10630. "#if MAX_POINT_LIGHTS > 0",
  10631. " vec3 pointDiffuse = vec3( 0.0 );",
  10632. " vec3 pointSpecular = vec3( 0.0 );",
  10633. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10634. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10635. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10636. " float lDistance = 1.0;",
  10637. " if ( pointLightDistance[ i ] > 0.0 )",
  10638. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10639. " lVector = normalize( lVector );",
  10640. // diffuse
  10641. " float dotProduct = dot( normal, lVector );",
  10642. " #ifdef WRAP_AROUND",
  10643. " float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10644. " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10645. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10646. " #else",
  10647. " float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10648. " #endif",
  10649. " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10650. // specular
  10651. " vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10652. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10653. " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10654. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10655. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10656. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  10657. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10658. " }",
  10659. "#endif",
  10660. "#if MAX_SPOT_LIGHTS > 0",
  10661. " vec3 spotDiffuse = vec3( 0.0 );",
  10662. " vec3 spotSpecular = vec3( 0.0 );",
  10663. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10664. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10665. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10666. " float lDistance = 1.0;",
  10667. " if ( spotLightDistance[ i ] > 0.0 )",
  10668. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10669. " lVector = normalize( lVector );",
  10670. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10671. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10672. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10673. // diffuse
  10674. " float dotProduct = dot( normal, lVector );",
  10675. " #ifdef WRAP_AROUND",
  10676. " float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10677. " float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10678. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10679. " #else",
  10680. " float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10681. " #endif",
  10682. " spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10683. // specular
  10684. " vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10685. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10686. " float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10687. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10688. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10689. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  10690. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10691. " }",
  10692. " }",
  10693. "#endif",
  10694. "#if MAX_DIR_LIGHTS > 0",
  10695. " vec3 dirDiffuse = vec3( 0.0 );",
  10696. " vec3 dirSpecular = vec3( 0.0 );" ,
  10697. " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10698. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10699. " vec3 dirVector = normalize( lDirection.xyz );",
  10700. // diffuse
  10701. " float dotProduct = dot( normal, dirVector );",
  10702. " #ifdef WRAP_AROUND",
  10703. " float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10704. " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10705. " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10706. " #else",
  10707. " float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10708. " #endif",
  10709. " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10710. // specular
  10711. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10712. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10713. " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10714. /*
  10715. // fresnel term from skin shader
  10716. " const float F0 = 0.128;",
  10717. " float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10718. " float exponential = pow( base, 5.0 );",
  10719. " float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10720. */
  10721. /*
  10722. // fresnel term from fresnel shader
  10723. " const float mFresnelBias = 0.08;",
  10724. " const float mFresnelScale = 0.3;",
  10725. " const float mFresnelPower = 5.0;",
  10726. " float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10727. */
  10728. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10729. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10730. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10731. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  10732. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10733. " }",
  10734. "#endif",
  10735. "#if MAX_HEMI_LIGHTS > 0",
  10736. " vec3 hemiDiffuse = vec3( 0.0 );",
  10737. " vec3 hemiSpecular = vec3( 0.0 );" ,
  10738. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10739. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10740. " vec3 lVector = normalize( lDirection.xyz );",
  10741. // diffuse
  10742. " float dotProduct = dot( normal, lVector );",
  10743. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10744. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10745. " hemiDiffuse += diffuse * hemiColor;",
  10746. // specular (sky light)
  10747. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10748. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10749. " float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10750. // specular (ground light)
  10751. " vec3 lVectorGround = -lVector;",
  10752. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10753. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10754. " float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10755. " float dotProductGround = dot( normal, lVectorGround );",
  10756. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10757. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10758. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  10759. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  10760. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10761. " }",
  10762. "#endif",
  10763. "vec3 totalDiffuse = vec3( 0.0 );",
  10764. "vec3 totalSpecular = vec3( 0.0 );",
  10765. "#if MAX_DIR_LIGHTS > 0",
  10766. " totalDiffuse += dirDiffuse;",
  10767. " totalSpecular += dirSpecular;",
  10768. "#endif",
  10769. "#if MAX_HEMI_LIGHTS > 0",
  10770. " totalDiffuse += hemiDiffuse;",
  10771. " totalSpecular += hemiSpecular;",
  10772. "#endif",
  10773. "#if MAX_POINT_LIGHTS > 0",
  10774. " totalDiffuse += pointDiffuse;",
  10775. " totalSpecular += pointSpecular;",
  10776. "#endif",
  10777. "#if MAX_SPOT_LIGHTS > 0",
  10778. " totalDiffuse += spotDiffuse;",
  10779. " totalSpecular += spotSpecular;",
  10780. "#endif",
  10781. "#ifdef METAL",
  10782. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10783. "#else",
  10784. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10785. "#endif"
  10786. ].join("\n"),
  10787. // VERTEX COLORS
  10788. color_pars_fragment: [
  10789. "#ifdef USE_COLOR",
  10790. " varying vec3 vColor;",
  10791. "#endif"
  10792. ].join("\n"),
  10793. color_fragment: [
  10794. "#ifdef USE_COLOR",
  10795. " gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10796. "#endif"
  10797. ].join("\n"),
  10798. color_pars_vertex: [
  10799. "#ifdef USE_COLOR",
  10800. " varying vec3 vColor;",
  10801. "#endif"
  10802. ].join("\n"),
  10803. color_vertex: [
  10804. "#ifdef USE_COLOR",
  10805. " #ifdef GAMMA_INPUT",
  10806. " vColor = color * color;",
  10807. " #else",
  10808. " vColor = color;",
  10809. " #endif",
  10810. "#endif"
  10811. ].join("\n"),
  10812. // SKINNING
  10813. skinning_pars_vertex: [
  10814. "#ifdef USE_SKINNING",
  10815. " #ifdef BONE_TEXTURE",
  10816. " uniform sampler2D boneTexture;",
  10817. " uniform int boneTextureWidth;",
  10818. " uniform int boneTextureHeight;",
  10819. " mat4 getBoneMatrix( const in float i ) {",
  10820. " float j = i * 4.0;",
  10821. " float x = mod( j, float( boneTextureWidth ) );",
  10822. " float y = floor( j / float( boneTextureWidth ) );",
  10823. " float dx = 1.0 / float( boneTextureWidth );",
  10824. " float dy = 1.0 / float( boneTextureHeight );",
  10825. " y = dy * ( y + 0.5 );",
  10826. " vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10827. " vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10828. " vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10829. " vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10830. " mat4 bone = mat4( v1, v2, v3, v4 );",
  10831. " return bone;",
  10832. " }",
  10833. " #else",
  10834. " uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10835. " mat4 getBoneMatrix( const in float i ) {",
  10836. " mat4 bone = boneGlobalMatrices[ int(i) ];",
  10837. " return bone;",
  10838. " }",
  10839. " #endif",
  10840. "#endif"
  10841. ].join("\n"),
  10842. skinbase_vertex: [
  10843. "#ifdef USE_SKINNING",
  10844. " mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10845. " mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10846. " mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  10847. " mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  10848. "#endif"
  10849. ].join("\n"),
  10850. skinning_vertex: [
  10851. "#ifdef USE_SKINNING",
  10852. " #ifdef USE_MORPHTARGETS",
  10853. " vec4 skinVertex = vec4( morphed, 1.0 );",
  10854. " #else",
  10855. " vec4 skinVertex = vec4( position, 1.0 );",
  10856. " #endif",
  10857. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10858. " skinned += boneMatY * skinVertex * skinWeight.y;",
  10859. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  10860. " skinned += boneMatW * skinVertex * skinWeight.w;",
  10861. "#endif"
  10862. ].join("\n"),
  10863. // MORPHING
  10864. morphtarget_pars_vertex: [
  10865. "#ifdef USE_MORPHTARGETS",
  10866. " #ifndef USE_MORPHNORMALS",
  10867. " uniform float morphTargetInfluences[ 8 ];",
  10868. " #else",
  10869. " uniform float morphTargetInfluences[ 4 ];",
  10870. " #endif",
  10871. "#endif"
  10872. ].join("\n"),
  10873. morphtarget_vertex: [
  10874. "#ifdef USE_MORPHTARGETS",
  10875. " vec3 morphed = vec3( 0.0 );",
  10876. " morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10877. " morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10878. " morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10879. " morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10880. " #ifndef USE_MORPHNORMALS",
  10881. " morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10882. " morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10883. " morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10884. " morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10885. " #endif",
  10886. " morphed += position;",
  10887. "#endif"
  10888. ].join("\n"),
  10889. default_vertex : [
  10890. "vec4 mvPosition;",
  10891. "#ifdef USE_SKINNING",
  10892. " mvPosition = modelViewMatrix * skinned;",
  10893. "#endif",
  10894. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10895. " mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10896. "#endif",
  10897. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10898. " mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10899. "#endif",
  10900. "gl_Position = projectionMatrix * mvPosition;"
  10901. ].join("\n"),
  10902. morphnormal_vertex: [
  10903. "#ifdef USE_MORPHNORMALS",
  10904. " vec3 morphedNormal = vec3( 0.0 );",
  10905. " morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10906. " morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10907. " morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10908. " morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10909. " morphedNormal += normal;",
  10910. "#endif"
  10911. ].join("\n"),
  10912. skinnormal_vertex: [
  10913. "#ifdef USE_SKINNING",
  10914. " mat4 skinMatrix = skinWeight.x * boneMatX;",
  10915. " skinMatrix += skinWeight.y * boneMatY;",
  10916. " #ifdef USE_MORPHNORMALS",
  10917. " vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10918. " #else",
  10919. " vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10920. " #endif",
  10921. "#endif"
  10922. ].join("\n"),
  10923. defaultnormal_vertex: [
  10924. "vec3 objectNormal;",
  10925. "#ifdef USE_SKINNING",
  10926. " objectNormal = skinnedNormal.xyz;",
  10927. "#endif",
  10928. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10929. " objectNormal = morphedNormal;",
  10930. "#endif",
  10931. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10932. " objectNormal = normal;",
  10933. "#endif",
  10934. "#ifdef FLIP_SIDED",
  10935. " objectNormal = -objectNormal;",
  10936. "#endif",
  10937. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10938. ].join("\n"),
  10939. // SHADOW MAP
  10940. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10941. // http://spidergl.org/example.php?id=6
  10942. // http://fabiensanglard.net/shadowmapping
  10943. shadowmap_pars_fragment: [
  10944. "#ifdef USE_SHADOWMAP",
  10945. " uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10946. " uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10947. " uniform float shadowDarkness[ MAX_SHADOWS ];",
  10948. " uniform float shadowBias[ MAX_SHADOWS ];",
  10949. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10950. " float unpackDepth( const in vec4 rgba_depth ) {",
  10951. " 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 );",
  10952. " float depth = dot( rgba_depth, bit_shift );",
  10953. " return depth;",
  10954. " }",
  10955. "#endif"
  10956. ].join("\n"),
  10957. shadowmap_fragment: [
  10958. "#ifdef USE_SHADOWMAP",
  10959. " #ifdef SHADOWMAP_DEBUG",
  10960. " vec3 frustumColors[3];",
  10961. " frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10962. " frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10963. " frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10964. " #endif",
  10965. " #ifdef SHADOWMAP_CASCADE",
  10966. " int inFrustumCount = 0;",
  10967. " #endif",
  10968. " float fDepth;",
  10969. " vec3 shadowColor = vec3( 1.0 );",
  10970. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10971. " vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10972. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10973. // "if ( all( something, something ) )" using this instead
  10974. " bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10975. " bool inFrustum = all( inFrustumVec );",
  10976. // don't shadow pixels outside of light frustum
  10977. // use just first frustum (for cascades)
  10978. // don't shadow pixels behind far plane of light frustum
  10979. " #ifdef SHADOWMAP_CASCADE",
  10980. " inFrustumCount += int( inFrustum );",
  10981. " bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10982. " #else",
  10983. " bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10984. " #endif",
  10985. " bool frustumTest = all( frustumTestVec );",
  10986. " if ( frustumTest ) {",
  10987. " shadowCoord.z += shadowBias[ i ];",
  10988. " #if defined( SHADOWMAP_TYPE_PCF )",
  10989. // Percentage-close filtering
  10990. // (9 pixel kernel)
  10991. // http://fabiensanglard.net/shadowmappingPCF/
  10992. " float shadow = 0.0;",
  10993. /*
  10994. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10995. // must enroll loop manually
  10996. " for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10997. " for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10998. " vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10999. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  11000. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  11001. " float fDepth = unpackDepth( rgbaDepth );",
  11002. " if ( fDepth < shadowCoord.z )",
  11003. " shadow += 1.0;",
  11004. " }",
  11005. " shadow /= 9.0;",
  11006. */
  11007. " const float shadowDelta = 1.0 / 9.0;",
  11008. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11009. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11010. " float dx0 = -1.25 * xPixelOffset;",
  11011. " float dy0 = -1.25 * yPixelOffset;",
  11012. " float dx1 = 1.25 * xPixelOffset;",
  11013. " float dy1 = 1.25 * yPixelOffset;",
  11014. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11015. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11016. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11017. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11018. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11019. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11020. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11021. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11022. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11023. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11024. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11025. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11026. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11027. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11028. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11029. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11030. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11031. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11032. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11033. " #elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  11034. // Percentage-close filtering
  11035. // (9 pixel kernel)
  11036. // http://fabiensanglard.net/shadowmappingPCF/
  11037. " float shadow = 0.0;",
  11038. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11039. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11040. " float dx0 = -1.0 * xPixelOffset;",
  11041. " float dy0 = -1.0 * yPixelOffset;",
  11042. " float dx1 = 1.0 * xPixelOffset;",
  11043. " float dy1 = 1.0 * yPixelOffset;",
  11044. " mat3 shadowKernel;",
  11045. " mat3 depthKernel;",
  11046. " depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11047. " depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11048. " depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11049. " depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11050. " depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11051. " depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11052. " depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11053. " depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11054. " depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11055. " vec3 shadowZ = vec3( shadowCoord.z );",
  11056. " shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  11057. " shadowKernel[0] *= vec3(0.25);",
  11058. " shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  11059. " shadowKernel[1] *= vec3(0.25);",
  11060. " shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  11061. " shadowKernel[2] *= vec3(0.25);",
  11062. " vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  11063. " shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  11064. " shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  11065. " vec4 shadowValues;",
  11066. " shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  11067. " shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  11068. " shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  11069. " shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  11070. " shadow = dot( shadowValues, vec4( 1.0 ) );",
  11071. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11072. " #else",
  11073. " vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  11074. " float fDepth = unpackDepth( rgbaDepth );",
  11075. " if ( fDepth < shadowCoord.z )",
  11076. // spot with multiple shadows is darker
  11077. " shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  11078. // spot with multiple shadows has the same color as single shadow spot
  11079. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  11080. " #endif",
  11081. " }",
  11082. " #ifdef SHADOWMAP_DEBUG",
  11083. " #ifdef SHADOWMAP_CASCADE",
  11084. " if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  11085. " #else",
  11086. " if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  11087. " #endif",
  11088. " #endif",
  11089. " }",
  11090. " #ifdef GAMMA_OUTPUT",
  11091. " shadowColor *= shadowColor;",
  11092. " #endif",
  11093. " gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  11094. "#endif"
  11095. ].join("\n"),
  11096. shadowmap_pars_vertex: [
  11097. "#ifdef USE_SHADOWMAP",
  11098. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11099. " uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  11100. "#endif"
  11101. ].join("\n"),
  11102. shadowmap_vertex: [
  11103. "#ifdef USE_SHADOWMAP",
  11104. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11105. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11106. " }",
  11107. "#endif"
  11108. ].join("\n"),
  11109. // ALPHATEST
  11110. alphatest_fragment: [
  11111. "#ifdef ALPHATEST",
  11112. " if ( gl_FragColor.a < ALPHATEST ) discard;",
  11113. "#endif"
  11114. ].join("\n"),
  11115. // LINEAR SPACE
  11116. linear_to_gamma_fragment: [
  11117. "#ifdef GAMMA_OUTPUT",
  11118. " gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  11119. "#endif"
  11120. ].join("\n")
  11121. };
  11122. /**
  11123. * Uniform Utilities
  11124. */
  11125. THREE.UniformsUtils = {
  11126. merge: function ( uniforms ) {
  11127. var u, p, tmp, merged = {};
  11128. for ( u = 0; u < uniforms.length; u ++ ) {
  11129. tmp = this.clone( uniforms[ u ] );
  11130. for ( p in tmp ) {
  11131. merged[ p ] = tmp[ p ];
  11132. }
  11133. }
  11134. return merged;
  11135. },
  11136. clone: function ( uniforms_src ) {
  11137. var u, p, parameter, parameter_src, uniforms_dst = {};
  11138. for ( u in uniforms_src ) {
  11139. uniforms_dst[ u ] = {};
  11140. for ( p in uniforms_src[ u ] ) {
  11141. parameter_src = uniforms_src[ u ][ p ];
  11142. if ( parameter_src instanceof THREE.Color ||
  11143. parameter_src instanceof THREE.Vector2 ||
  11144. parameter_src instanceof THREE.Vector3 ||
  11145. parameter_src instanceof THREE.Vector4 ||
  11146. parameter_src instanceof THREE.Matrix4 ||
  11147. parameter_src instanceof THREE.Texture ) {
  11148. uniforms_dst[ u ][ p ] = parameter_src.clone();
  11149. } else if ( parameter_src instanceof Array ) {
  11150. uniforms_dst[ u ][ p ] = parameter_src.slice();
  11151. } else {
  11152. uniforms_dst[ u ][ p ] = parameter_src;
  11153. }
  11154. }
  11155. }
  11156. return uniforms_dst;
  11157. }
  11158. };
  11159. /**
  11160. * Uniforms library for shared webgl shaders
  11161. */
  11162. THREE.UniformsLib = {
  11163. common: {
  11164. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11165. "opacity" : { type: "f", value: 1.0 },
  11166. "map" : { type: "t", value: null },
  11167. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  11168. "lightMap" : { type: "t", value: null },
  11169. "specularMap" : { type: "t", value: null },
  11170. "envMap" : { type: "t", value: null },
  11171. "flipEnvMap" : { type: "f", value: -1 },
  11172. "useRefract" : { type: "i", value: 0 },
  11173. "reflectivity" : { type: "f", value: 1.0 },
  11174. "refractionRatio" : { type: "f", value: 0.98 },
  11175. "combine" : { type: "i", value: 0 },
  11176. "morphTargetInfluences" : { type: "f", value: 0 }
  11177. },
  11178. bump: {
  11179. "bumpMap" : { type: "t", value: null },
  11180. "bumpScale" : { type: "f", value: 1 }
  11181. },
  11182. normalmap: {
  11183. "normalMap" : { type: "t", value: null },
  11184. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  11185. },
  11186. fog : {
  11187. "fogDensity" : { type: "f", value: 0.00025 },
  11188. "fogNear" : { type: "f", value: 1 },
  11189. "fogFar" : { type: "f", value: 2000 },
  11190. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11191. },
  11192. lights: {
  11193. "ambientLightColor" : { type: "fv", value: [] },
  11194. "directionalLightDirection" : { type: "fv", value: [] },
  11195. "directionalLightColor" : { type: "fv", value: [] },
  11196. "hemisphereLightDirection" : { type: "fv", value: [] },
  11197. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  11198. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  11199. "pointLightColor" : { type: "fv", value: [] },
  11200. "pointLightPosition" : { type: "fv", value: [] },
  11201. "pointLightDistance" : { type: "fv1", value: [] },
  11202. "spotLightColor" : { type: "fv", value: [] },
  11203. "spotLightPosition" : { type: "fv", value: [] },
  11204. "spotLightDirection" : { type: "fv", value: [] },
  11205. "spotLightDistance" : { type: "fv1", value: [] },
  11206. "spotLightAngleCos" : { type: "fv1", value: [] },
  11207. "spotLightExponent" : { type: "fv1", value: [] }
  11208. },
  11209. particle: {
  11210. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11211. "opacity" : { type: "f", value: 1.0 },
  11212. "size" : { type: "f", value: 1.0 },
  11213. "scale" : { type: "f", value: 1.0 },
  11214. "map" : { type: "t", value: null },
  11215. "fogDensity" : { type: "f", value: 0.00025 },
  11216. "fogNear" : { type: "f", value: 1 },
  11217. "fogFar" : { type: "f", value: 2000 },
  11218. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11219. },
  11220. shadowmap: {
  11221. "shadowMap": { type: "tv", value: [] },
  11222. "shadowMapSize": { type: "v2v", value: [] },
  11223. "shadowBias" : { type: "fv1", value: [] },
  11224. "shadowDarkness": { type: "fv1", value: [] },
  11225. "shadowMatrix" : { type: "m4v", value: [] }
  11226. }
  11227. };
  11228. /**
  11229. * Webgl Shader Library for three.js
  11230. *
  11231. * @author alteredq / http://alteredqualia.com/
  11232. * @author mrdoob / http://mrdoob.com/
  11233. * @author mikael emtinger / http://gomo.se/
  11234. */
  11235. THREE.ShaderLib = {
  11236. 'basic': {
  11237. uniforms: THREE.UniformsUtils.merge( [
  11238. THREE.UniformsLib[ "common" ],
  11239. THREE.UniformsLib[ "fog" ],
  11240. THREE.UniformsLib[ "shadowmap" ]
  11241. ] ),
  11242. vertexShader: [
  11243. THREE.ShaderChunk[ "map_pars_vertex" ],
  11244. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11245. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11246. THREE.ShaderChunk[ "color_pars_vertex" ],
  11247. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11248. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11249. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11250. "void main() {",
  11251. THREE.ShaderChunk[ "map_vertex" ],
  11252. THREE.ShaderChunk[ "lightmap_vertex" ],
  11253. THREE.ShaderChunk[ "color_vertex" ],
  11254. THREE.ShaderChunk[ "skinbase_vertex" ],
  11255. " #ifdef USE_ENVMAP",
  11256. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11257. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11258. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11259. " #endif",
  11260. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11261. THREE.ShaderChunk[ "skinning_vertex" ],
  11262. THREE.ShaderChunk[ "default_vertex" ],
  11263. THREE.ShaderChunk[ "worldpos_vertex" ],
  11264. THREE.ShaderChunk[ "envmap_vertex" ],
  11265. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11266. "}"
  11267. ].join("\n"),
  11268. fragmentShader: [
  11269. "uniform vec3 diffuse;",
  11270. "uniform float opacity;",
  11271. THREE.ShaderChunk[ "color_pars_fragment" ],
  11272. THREE.ShaderChunk[ "map_pars_fragment" ],
  11273. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11274. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11275. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11276. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11277. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11278. "void main() {",
  11279. " gl_FragColor = vec4( diffuse, opacity );",
  11280. THREE.ShaderChunk[ "map_fragment" ],
  11281. THREE.ShaderChunk[ "alphatest_fragment" ],
  11282. THREE.ShaderChunk[ "specularmap_fragment" ],
  11283. THREE.ShaderChunk[ "lightmap_fragment" ],
  11284. THREE.ShaderChunk[ "color_fragment" ],
  11285. THREE.ShaderChunk[ "envmap_fragment" ],
  11286. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11287. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11288. THREE.ShaderChunk[ "fog_fragment" ],
  11289. "}"
  11290. ].join("\n")
  11291. },
  11292. 'lambert': {
  11293. uniforms: THREE.UniformsUtils.merge( [
  11294. THREE.UniformsLib[ "common" ],
  11295. THREE.UniformsLib[ "fog" ],
  11296. THREE.UniformsLib[ "lights" ],
  11297. THREE.UniformsLib[ "shadowmap" ],
  11298. {
  11299. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11300. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11301. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11302. }
  11303. ] ),
  11304. vertexShader: [
  11305. "#define LAMBERT",
  11306. "varying vec3 vLightFront;",
  11307. "#ifdef DOUBLE_SIDED",
  11308. " varying vec3 vLightBack;",
  11309. "#endif",
  11310. THREE.ShaderChunk[ "map_pars_vertex" ],
  11311. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11312. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11313. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11314. THREE.ShaderChunk[ "color_pars_vertex" ],
  11315. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11316. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11317. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11318. "void main() {",
  11319. THREE.ShaderChunk[ "map_vertex" ],
  11320. THREE.ShaderChunk[ "lightmap_vertex" ],
  11321. THREE.ShaderChunk[ "color_vertex" ],
  11322. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11323. THREE.ShaderChunk[ "skinbase_vertex" ],
  11324. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11325. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11326. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11327. THREE.ShaderChunk[ "skinning_vertex" ],
  11328. THREE.ShaderChunk[ "default_vertex" ],
  11329. THREE.ShaderChunk[ "worldpos_vertex" ],
  11330. THREE.ShaderChunk[ "envmap_vertex" ],
  11331. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11332. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11333. "}"
  11334. ].join("\n"),
  11335. fragmentShader: [
  11336. "uniform float opacity;",
  11337. "varying vec3 vLightFront;",
  11338. "#ifdef DOUBLE_SIDED",
  11339. " varying vec3 vLightBack;",
  11340. "#endif",
  11341. THREE.ShaderChunk[ "color_pars_fragment" ],
  11342. THREE.ShaderChunk[ "map_pars_fragment" ],
  11343. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11344. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11345. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11346. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11347. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11348. "void main() {",
  11349. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11350. THREE.ShaderChunk[ "map_fragment" ],
  11351. THREE.ShaderChunk[ "alphatest_fragment" ],
  11352. THREE.ShaderChunk[ "specularmap_fragment" ],
  11353. " #ifdef DOUBLE_SIDED",
  11354. //"float isFront = float( gl_FrontFacing );",
  11355. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11356. " if ( gl_FrontFacing )",
  11357. " gl_FragColor.xyz *= vLightFront;",
  11358. " else",
  11359. " gl_FragColor.xyz *= vLightBack;",
  11360. " #else",
  11361. " gl_FragColor.xyz *= vLightFront;",
  11362. " #endif",
  11363. THREE.ShaderChunk[ "lightmap_fragment" ],
  11364. THREE.ShaderChunk[ "color_fragment" ],
  11365. THREE.ShaderChunk[ "envmap_fragment" ],
  11366. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11367. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11368. THREE.ShaderChunk[ "fog_fragment" ],
  11369. "}"
  11370. ].join("\n")
  11371. },
  11372. 'phong': {
  11373. uniforms: THREE.UniformsUtils.merge( [
  11374. THREE.UniformsLib[ "common" ],
  11375. THREE.UniformsLib[ "bump" ],
  11376. THREE.UniformsLib[ "normalmap" ],
  11377. THREE.UniformsLib[ "fog" ],
  11378. THREE.UniformsLib[ "lights" ],
  11379. THREE.UniformsLib[ "shadowmap" ],
  11380. {
  11381. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11382. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11383. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11384. "shininess": { type: "f", value: 30 },
  11385. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11386. }
  11387. ] ),
  11388. vertexShader: [
  11389. "#define PHONG",
  11390. "varying vec3 vViewPosition;",
  11391. "varying vec3 vNormal;",
  11392. THREE.ShaderChunk[ "map_pars_vertex" ],
  11393. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11394. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11395. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11396. THREE.ShaderChunk[ "color_pars_vertex" ],
  11397. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11398. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11399. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11400. "void main() {",
  11401. THREE.ShaderChunk[ "map_vertex" ],
  11402. THREE.ShaderChunk[ "lightmap_vertex" ],
  11403. THREE.ShaderChunk[ "color_vertex" ],
  11404. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11405. THREE.ShaderChunk[ "skinbase_vertex" ],
  11406. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11407. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11408. " vNormal = normalize( transformedNormal );",
  11409. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11410. THREE.ShaderChunk[ "skinning_vertex" ],
  11411. THREE.ShaderChunk[ "default_vertex" ],
  11412. " vViewPosition = -mvPosition.xyz;",
  11413. THREE.ShaderChunk[ "worldpos_vertex" ],
  11414. THREE.ShaderChunk[ "envmap_vertex" ],
  11415. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11416. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11417. "}"
  11418. ].join("\n"),
  11419. fragmentShader: [
  11420. "uniform vec3 diffuse;",
  11421. "uniform float opacity;",
  11422. "uniform vec3 ambient;",
  11423. "uniform vec3 emissive;",
  11424. "uniform vec3 specular;",
  11425. "uniform float shininess;",
  11426. THREE.ShaderChunk[ "color_pars_fragment" ],
  11427. THREE.ShaderChunk[ "map_pars_fragment" ],
  11428. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11429. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11430. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11431. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11432. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11433. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11434. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11435. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11436. "void main() {",
  11437. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11438. THREE.ShaderChunk[ "map_fragment" ],
  11439. THREE.ShaderChunk[ "alphatest_fragment" ],
  11440. THREE.ShaderChunk[ "specularmap_fragment" ],
  11441. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11442. THREE.ShaderChunk[ "lightmap_fragment" ],
  11443. THREE.ShaderChunk[ "color_fragment" ],
  11444. THREE.ShaderChunk[ "envmap_fragment" ],
  11445. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11446. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11447. THREE.ShaderChunk[ "fog_fragment" ],
  11448. "}"
  11449. ].join("\n")
  11450. },
  11451. 'particle_basic': {
  11452. uniforms: THREE.UniformsUtils.merge( [
  11453. THREE.UniformsLib[ "particle" ],
  11454. THREE.UniformsLib[ "shadowmap" ]
  11455. ] ),
  11456. vertexShader: [
  11457. "uniform float size;",
  11458. "uniform float scale;",
  11459. THREE.ShaderChunk[ "color_pars_vertex" ],
  11460. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11461. "void main() {",
  11462. THREE.ShaderChunk[ "color_vertex" ],
  11463. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11464. " #ifdef USE_SIZEATTENUATION",
  11465. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11466. " #else",
  11467. " gl_PointSize = size;",
  11468. " #endif",
  11469. " gl_Position = projectionMatrix * mvPosition;",
  11470. THREE.ShaderChunk[ "worldpos_vertex" ],
  11471. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11472. "}"
  11473. ].join("\n"),
  11474. fragmentShader: [
  11475. "uniform vec3 psColor;",
  11476. "uniform float opacity;",
  11477. THREE.ShaderChunk[ "color_pars_fragment" ],
  11478. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11479. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11480. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11481. "void main() {",
  11482. " gl_FragColor = vec4( psColor, opacity );",
  11483. THREE.ShaderChunk[ "map_particle_fragment" ],
  11484. THREE.ShaderChunk[ "alphatest_fragment" ],
  11485. THREE.ShaderChunk[ "color_fragment" ],
  11486. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11487. THREE.ShaderChunk[ "fog_fragment" ],
  11488. "}"
  11489. ].join("\n")
  11490. },
  11491. 'dashed': {
  11492. uniforms: THREE.UniformsUtils.merge( [
  11493. THREE.UniformsLib[ "common" ],
  11494. THREE.UniformsLib[ "fog" ],
  11495. {
  11496. "scale": { type: "f", value: 1 },
  11497. "dashSize": { type: "f", value: 1 },
  11498. "totalSize": { type: "f", value: 2 }
  11499. }
  11500. ] ),
  11501. vertexShader: [
  11502. "uniform float scale;",
  11503. "attribute float lineDistance;",
  11504. "varying float vLineDistance;",
  11505. THREE.ShaderChunk[ "color_pars_vertex" ],
  11506. "void main() {",
  11507. THREE.ShaderChunk[ "color_vertex" ],
  11508. " vLineDistance = scale * lineDistance;",
  11509. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11510. " gl_Position = projectionMatrix * mvPosition;",
  11511. "}"
  11512. ].join("\n"),
  11513. fragmentShader: [
  11514. "uniform vec3 diffuse;",
  11515. "uniform float opacity;",
  11516. "uniform float dashSize;",
  11517. "uniform float totalSize;",
  11518. "varying float vLineDistance;",
  11519. THREE.ShaderChunk[ "color_pars_fragment" ],
  11520. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11521. "void main() {",
  11522. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11523. " discard;",
  11524. " }",
  11525. " gl_FragColor = vec4( diffuse, opacity );",
  11526. THREE.ShaderChunk[ "color_fragment" ],
  11527. THREE.ShaderChunk[ "fog_fragment" ],
  11528. "}"
  11529. ].join("\n")
  11530. },
  11531. 'depth': {
  11532. uniforms: {
  11533. "mNear": { type: "f", value: 1.0 },
  11534. "mFar" : { type: "f", value: 2000.0 },
  11535. "opacity" : { type: "f", value: 1.0 }
  11536. },
  11537. vertexShader: [
  11538. "void main() {",
  11539. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11540. "}"
  11541. ].join("\n"),
  11542. fragmentShader: [
  11543. "uniform float mNear;",
  11544. "uniform float mFar;",
  11545. "uniform float opacity;",
  11546. "void main() {",
  11547. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11548. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11549. " gl_FragColor = vec4( vec3( color ), opacity );",
  11550. "}"
  11551. ].join("\n")
  11552. },
  11553. 'normal': {
  11554. uniforms: {
  11555. "opacity" : { type: "f", value: 1.0 }
  11556. },
  11557. vertexShader: [
  11558. "varying vec3 vNormal;",
  11559. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11560. "void main() {",
  11561. " vNormal = normalize( normalMatrix * normal );",
  11562. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11563. THREE.ShaderChunk[ "default_vertex" ],
  11564. "}"
  11565. ].join("\n"),
  11566. fragmentShader: [
  11567. "uniform float opacity;",
  11568. "varying vec3 vNormal;",
  11569. "void main() {",
  11570. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11571. "}"
  11572. ].join("\n")
  11573. },
  11574. /* -------------------------------------------------------------------------
  11575. // Normal map shader
  11576. // - Blinn-Phong
  11577. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11578. // - point and directional lights (use with "lights: true" material option)
  11579. ------------------------------------------------------------------------- */
  11580. 'normalmap' : {
  11581. uniforms: THREE.UniformsUtils.merge( [
  11582. THREE.UniformsLib[ "fog" ],
  11583. THREE.UniformsLib[ "lights" ],
  11584. THREE.UniformsLib[ "shadowmap" ],
  11585. {
  11586. "enableAO" : { type: "i", value: 0 },
  11587. "enableDiffuse" : { type: "i", value: 0 },
  11588. "enableSpecular" : { type: "i", value: 0 },
  11589. "enableReflection": { type: "i", value: 0 },
  11590. "enableDisplacement": { type: "i", value: 0 },
  11591. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11592. "tDiffuse" : { type: "t", value: null },
  11593. "tCube" : { type: "t", value: null },
  11594. "tNormal" : { type: "t", value: null },
  11595. "tSpecular" : { type: "t", value: null },
  11596. "tAO" : { type: "t", value: null },
  11597. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11598. "uDisplacementBias": { type: "f", value: 0.0 },
  11599. "uDisplacementScale": { type: "f", value: 1.0 },
  11600. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11601. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11602. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11603. "shininess": { type: "f", value: 30 },
  11604. "opacity": { type: "f", value: 1 },
  11605. "useRefract": { type: "i", value: 0 },
  11606. "refractionRatio": { type: "f", value: 0.98 },
  11607. "reflectivity": { type: "f", value: 0.5 },
  11608. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11609. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11610. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11611. }
  11612. ] ),
  11613. fragmentShader: [
  11614. "uniform vec3 ambient;",
  11615. "uniform vec3 diffuse;",
  11616. "uniform vec3 specular;",
  11617. "uniform float shininess;",
  11618. "uniform float opacity;",
  11619. "uniform bool enableDiffuse;",
  11620. "uniform bool enableSpecular;",
  11621. "uniform bool enableAO;",
  11622. "uniform bool enableReflection;",
  11623. "uniform sampler2D tDiffuse;",
  11624. "uniform sampler2D tNormal;",
  11625. "uniform sampler2D tSpecular;",
  11626. "uniform sampler2D tAO;",
  11627. "uniform samplerCube tCube;",
  11628. "uniform vec2 uNormalScale;",
  11629. "uniform bool useRefract;",
  11630. "uniform float refractionRatio;",
  11631. "uniform float reflectivity;",
  11632. "varying vec3 vTangent;",
  11633. "varying vec3 vBinormal;",
  11634. "varying vec3 vNormal;",
  11635. "varying vec2 vUv;",
  11636. "uniform vec3 ambientLightColor;",
  11637. "#if MAX_DIR_LIGHTS > 0",
  11638. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11639. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11640. "#endif",
  11641. "#if MAX_HEMI_LIGHTS > 0",
  11642. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11643. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11644. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11645. "#endif",
  11646. "#if MAX_POINT_LIGHTS > 0",
  11647. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11648. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11649. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11650. "#endif",
  11651. "#if MAX_SPOT_LIGHTS > 0",
  11652. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11653. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11654. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11655. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11656. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11657. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11658. "#endif",
  11659. "#ifdef WRAP_AROUND",
  11660. " uniform vec3 wrapRGB;",
  11661. "#endif",
  11662. "varying vec3 vWorldPosition;",
  11663. "varying vec3 vViewPosition;",
  11664. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11665. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11666. "void main() {",
  11667. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11668. " vec3 specularTex = vec3( 1.0 );",
  11669. " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11670. " normalTex.xy *= uNormalScale;",
  11671. " normalTex = normalize( normalTex );",
  11672. " if( enableDiffuse ) {",
  11673. " #ifdef GAMMA_INPUT",
  11674. " vec4 texelColor = texture2D( tDiffuse, vUv );",
  11675. " texelColor.xyz *= texelColor.xyz;",
  11676. " gl_FragColor = gl_FragColor * texelColor;",
  11677. " #else",
  11678. " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11679. " #endif",
  11680. " }",
  11681. " if( enableAO ) {",
  11682. " #ifdef GAMMA_INPUT",
  11683. " vec4 aoColor = texture2D( tAO, vUv );",
  11684. " aoColor.xyz *= aoColor.xyz;",
  11685. " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11686. " #else",
  11687. " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11688. " #endif",
  11689. " }",
  11690. " if( enableSpecular )",
  11691. " specularTex = texture2D( tSpecular, vUv ).xyz;",
  11692. " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11693. " vec3 finalNormal = tsb * normalTex;",
  11694. " #ifdef FLIP_SIDED",
  11695. " finalNormal = -finalNormal;",
  11696. " #endif",
  11697. " vec3 normal = normalize( finalNormal );",
  11698. " vec3 viewPosition = normalize( vViewPosition );",
  11699. // point lights
  11700. " #if MAX_POINT_LIGHTS > 0",
  11701. " vec3 pointDiffuse = vec3( 0.0 );",
  11702. " vec3 pointSpecular = vec3( 0.0 );",
  11703. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11704. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11705. " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11706. " float pointDistance = 1.0;",
  11707. " if ( pointLightDistance[ i ] > 0.0 )",
  11708. " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11709. " pointVector = normalize( pointVector );",
  11710. // diffuse
  11711. " #ifdef WRAP_AROUND",
  11712. " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11713. " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11714. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11715. " #else",
  11716. " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11717. " #endif",
  11718. " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11719. // specular
  11720. " vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11721. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11722. " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11723. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11724. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11725. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11726. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11727. " }",
  11728. " #endif",
  11729. // spot lights
  11730. " #if MAX_SPOT_LIGHTS > 0",
  11731. " vec3 spotDiffuse = vec3( 0.0 );",
  11732. " vec3 spotSpecular = vec3( 0.0 );",
  11733. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11734. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11735. " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11736. " float spotDistance = 1.0;",
  11737. " if ( spotLightDistance[ i ] > 0.0 )",
  11738. " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11739. " spotVector = normalize( spotVector );",
  11740. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11741. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11742. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11743. // diffuse
  11744. " #ifdef WRAP_AROUND",
  11745. " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11746. " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11747. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11748. " #else",
  11749. " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11750. " #endif",
  11751. " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11752. // specular
  11753. " vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11754. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11755. " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11756. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11757. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11758. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11759. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11760. " }",
  11761. " }",
  11762. " #endif",
  11763. // directional lights
  11764. " #if MAX_DIR_LIGHTS > 0",
  11765. " vec3 dirDiffuse = vec3( 0.0 );",
  11766. " vec3 dirSpecular = vec3( 0.0 );",
  11767. " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11768. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11769. " vec3 dirVector = normalize( lDirection.xyz );",
  11770. // diffuse
  11771. " #ifdef WRAP_AROUND",
  11772. " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11773. " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11774. " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11775. " #else",
  11776. " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11777. " #endif",
  11778. " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11779. // specular
  11780. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11781. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11782. " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11783. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11784. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11785. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11786. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11787. " }",
  11788. " #endif",
  11789. // hemisphere lights
  11790. " #if MAX_HEMI_LIGHTS > 0",
  11791. " vec3 hemiDiffuse = vec3( 0.0 );",
  11792. " vec3 hemiSpecular = vec3( 0.0 );" ,
  11793. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11794. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11795. " vec3 lVector = normalize( lDirection.xyz );",
  11796. // diffuse
  11797. " float dotProduct = dot( normal, lVector );",
  11798. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11799. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11800. " hemiDiffuse += diffuse * hemiColor;",
  11801. // specular (sky light)
  11802. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11803. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11804. " float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11805. // specular (ground light)
  11806. " vec3 lVectorGround = -lVector;",
  11807. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11808. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11809. " float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11810. " float dotProductGround = dot( normal, lVectorGround );",
  11811. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11812. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11813. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11814. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11815. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11816. " }",
  11817. " #endif",
  11818. // all lights contribution summation
  11819. " vec3 totalDiffuse = vec3( 0.0 );",
  11820. " vec3 totalSpecular = vec3( 0.0 );",
  11821. " #if MAX_DIR_LIGHTS > 0",
  11822. " totalDiffuse += dirDiffuse;",
  11823. " totalSpecular += dirSpecular;",
  11824. " #endif",
  11825. " #if MAX_HEMI_LIGHTS > 0",
  11826. " totalDiffuse += hemiDiffuse;",
  11827. " totalSpecular += hemiSpecular;",
  11828. " #endif",
  11829. " #if MAX_POINT_LIGHTS > 0",
  11830. " totalDiffuse += pointDiffuse;",
  11831. " totalSpecular += pointSpecular;",
  11832. " #endif",
  11833. " #if MAX_SPOT_LIGHTS > 0",
  11834. " totalDiffuse += spotDiffuse;",
  11835. " totalSpecular += spotSpecular;",
  11836. " #endif",
  11837. " #ifdef METAL",
  11838. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11839. " #else",
  11840. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11841. " #endif",
  11842. " if ( enableReflection ) {",
  11843. " vec3 vReflect;",
  11844. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11845. " if ( useRefract ) {",
  11846. " vReflect = refract( cameraToVertex, normal, refractionRatio );",
  11847. " } else {",
  11848. " vReflect = reflect( cameraToVertex, normal );",
  11849. " }",
  11850. " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11851. " #ifdef GAMMA_INPUT",
  11852. " cubeColor.xyz *= cubeColor.xyz;",
  11853. " #endif",
  11854. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  11855. " }",
  11856. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11857. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11858. THREE.ShaderChunk[ "fog_fragment" ],
  11859. "}"
  11860. ].join("\n"),
  11861. vertexShader: [
  11862. "attribute vec4 tangent;",
  11863. "uniform vec2 uOffset;",
  11864. "uniform vec2 uRepeat;",
  11865. "uniform bool enableDisplacement;",
  11866. "#ifdef VERTEX_TEXTURES",
  11867. " uniform sampler2D tDisplacement;",
  11868. " uniform float uDisplacementScale;",
  11869. " uniform float uDisplacementBias;",
  11870. "#endif",
  11871. "varying vec3 vTangent;",
  11872. "varying vec3 vBinormal;",
  11873. "varying vec3 vNormal;",
  11874. "varying vec2 vUv;",
  11875. "varying vec3 vWorldPosition;",
  11876. "varying vec3 vViewPosition;",
  11877. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11878. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11879. "void main() {",
  11880. THREE.ShaderChunk[ "skinbase_vertex" ],
  11881. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11882. // normal, tangent and binormal vectors
  11883. " #ifdef USE_SKINNING",
  11884. " vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11885. " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11886. " vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11887. " #else",
  11888. " vNormal = normalize( normalMatrix * normal );",
  11889. " vTangent = normalize( normalMatrix * tangent.xyz );",
  11890. " #endif",
  11891. " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11892. " vUv = uv * uRepeat + uOffset;",
  11893. // displacement mapping
  11894. " vec3 displacedPosition;",
  11895. " #ifdef VERTEX_TEXTURES",
  11896. " if ( enableDisplacement ) {",
  11897. " vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11898. " float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11899. " displacedPosition = position + normalize( normal ) * df;",
  11900. " } else {",
  11901. " #ifdef USE_SKINNING",
  11902. " vec4 skinVertex = vec4( position, 1.0 );",
  11903. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11904. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11905. " displacedPosition = skinned.xyz;",
  11906. " #else",
  11907. " displacedPosition = position;",
  11908. " #endif",
  11909. " }",
  11910. " #else",
  11911. " #ifdef USE_SKINNING",
  11912. " vec4 skinVertex = vec4( position, 1.0 );",
  11913. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11914. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11915. " displacedPosition = skinned.xyz;",
  11916. " #else",
  11917. " displacedPosition = position;",
  11918. " #endif",
  11919. " #endif",
  11920. //
  11921. " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11922. " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11923. " gl_Position = projectionMatrix * mvPosition;",
  11924. //
  11925. " vWorldPosition = worldPosition.xyz;",
  11926. " vViewPosition = -mvPosition.xyz;",
  11927. // shadows
  11928. " #ifdef USE_SHADOWMAP",
  11929. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11930. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11931. " }",
  11932. " #endif",
  11933. "}"
  11934. ].join("\n")
  11935. },
  11936. /* -------------------------------------------------------------------------
  11937. // Cube map shader
  11938. ------------------------------------------------------------------------- */
  11939. 'cube': {
  11940. uniforms: { "tCube": { type: "t", value: null },
  11941. "tFlip": { type: "f", value: -1 } },
  11942. vertexShader: [
  11943. "varying vec3 vWorldPosition;",
  11944. "void main() {",
  11945. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11946. " vWorldPosition = worldPosition.xyz;",
  11947. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11948. "}"
  11949. ].join("\n"),
  11950. fragmentShader: [
  11951. "uniform samplerCube tCube;",
  11952. "uniform float tFlip;",
  11953. "varying vec3 vWorldPosition;",
  11954. "void main() {",
  11955. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11956. "}"
  11957. ].join("\n")
  11958. },
  11959. // Depth encoding into RGBA texture
  11960. // based on SpiderGL shadow map example
  11961. // http://spidergl.org/example.php?id=6
  11962. // originally from
  11963. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11964. // see also here:
  11965. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11966. 'depthRGBA': {
  11967. uniforms: {},
  11968. vertexShader: [
  11969. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11970. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11971. "void main() {",
  11972. THREE.ShaderChunk[ "skinbase_vertex" ],
  11973. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11974. THREE.ShaderChunk[ "skinning_vertex" ],
  11975. THREE.ShaderChunk[ "default_vertex" ],
  11976. "}"
  11977. ].join("\n"),
  11978. fragmentShader: [
  11979. "vec4 pack_depth( const in float depth ) {",
  11980. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11981. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11982. " vec4 res = fract( depth * bit_shift );",
  11983. " res -= res.xxyz * bit_mask;",
  11984. " return res;",
  11985. "}",
  11986. "void main() {",
  11987. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11988. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11989. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11990. //"gl_FragData[ 0 ] = pack_depth( z );",
  11991. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11992. "}"
  11993. ].join("\n")
  11994. }
  11995. };
  11996. /**
  11997. * @author supereggbert / http://www.paulbrunt.co.uk/
  11998. * @author mrdoob / http://mrdoob.com/
  11999. * @author alteredq / http://alteredqualia.com/
  12000. * @author szimek / https://github.com/szimek/
  12001. */
  12002. THREE.WebGLRenderer = function ( parameters ) {
  12003. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  12004. parameters = parameters || {};
  12005. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  12006. _context = parameters.context !== undefined ? parameters.context : null,
  12007. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  12008. _buffers = {},
  12009. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12010. _depth = parameters.depth !== undefined ? parameters.depth : true,
  12011. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12012. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12013. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12014. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12015. _clearColor = new THREE.Color( 0x000000 ),
  12016. _clearAlpha = 0;
  12017. // public properties
  12018. this.domElement = _canvas;
  12019. this.context = null;
  12020. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  12021. ? parameters.devicePixelRatio
  12022. : self.devicePixelRatio !== undefined
  12023. ? self.devicePixelRatio
  12024. : 1;
  12025. // clearing
  12026. this.autoClear = true;
  12027. this.autoClearColor = true;
  12028. this.autoClearDepth = true;
  12029. this.autoClearStencil = true;
  12030. // scene graph
  12031. this.sortObjects = true;
  12032. this.autoUpdateObjects = true;
  12033. // physically based shading
  12034. this.gammaInput = false;
  12035. this.gammaOutput = false;
  12036. // shadow map
  12037. this.shadowMapEnabled = false;
  12038. this.shadowMapAutoUpdate = true;
  12039. this.shadowMapType = THREE.PCFShadowMap;
  12040. this.shadowMapCullFace = THREE.CullFaceFront;
  12041. this.shadowMapDebug = false;
  12042. this.shadowMapCascade = false;
  12043. // morphs
  12044. this.maxMorphTargets = 8;
  12045. this.maxMorphNormals = 4;
  12046. // flags
  12047. this.autoScaleCubemaps = true;
  12048. // custom render plugins
  12049. this.renderPluginsPre = [];
  12050. this.renderPluginsPost = [];
  12051. // info
  12052. this.info = {
  12053. memory: {
  12054. programs: 0,
  12055. geometries: 0,
  12056. textures: 0
  12057. },
  12058. render: {
  12059. calls: 0,
  12060. vertices: 0,
  12061. faces: 0,
  12062. points: 0
  12063. }
  12064. };
  12065. // internal properties
  12066. var _this = this,
  12067. _programs = [],
  12068. // internal state cache
  12069. _currentProgram = null,
  12070. _currentFramebuffer = null,
  12071. _currentMaterialId = -1,
  12072. _currentGeometryGroupHash = null,
  12073. _currentCamera = null,
  12074. _usedTextureUnits = 0,
  12075. // GL state cache
  12076. _oldDoubleSided = -1,
  12077. _oldFlipSided = -1,
  12078. _oldBlending = -1,
  12079. _oldBlendEquation = -1,
  12080. _oldBlendSrc = -1,
  12081. _oldBlendDst = -1,
  12082. _oldDepthTest = -1,
  12083. _oldDepthWrite = -1,
  12084. _oldPolygonOffset = null,
  12085. _oldPolygonOffsetFactor = null,
  12086. _oldPolygonOffsetUnits = null,
  12087. _oldLineWidth = null,
  12088. _viewportX = 0,
  12089. _viewportY = 0,
  12090. _viewportWidth = _canvas.width,
  12091. _viewportHeight = _canvas.height,
  12092. _currentWidth = 0,
  12093. _currentHeight = 0,
  12094. _newAttributes = new Uint8Array( 16 ),
  12095. _enabledAttributes = new Uint8Array( 16 ),
  12096. // frustum
  12097. _frustum = new THREE.Frustum(),
  12098. // camera matrices cache
  12099. _projScreenMatrix = new THREE.Matrix4(),
  12100. _projScreenMatrixPS = new THREE.Matrix4(),
  12101. _vector3 = new THREE.Vector3(),
  12102. // light arrays cache
  12103. _direction = new THREE.Vector3(),
  12104. _lightsNeedUpdate = true,
  12105. _lights = {
  12106. ambient: [ 0, 0, 0 ],
  12107. directional: { length: 0, colors: new Array(), positions: new Array() },
  12108. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  12109. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  12110. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  12111. };
  12112. // initialize
  12113. var _gl;
  12114. var _glExtensionTextureFloat;
  12115. var _glExtensionTextureFloatLinear;
  12116. var _glExtensionStandardDerivatives;
  12117. var _glExtensionTextureFilterAnisotropic;
  12118. var _glExtensionCompressedTextureS3TC;
  12119. var _glExtensionElementIndexUint;
  12120. initGL();
  12121. setDefaultGLState();
  12122. this.context = _gl;
  12123. // GPU capabilities
  12124. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12125. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12126. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12127. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12128. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12129. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12130. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12131. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12132. //
  12133. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12134. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12135. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12136. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12137. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12138. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12139. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  12140. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  12141. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  12142. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  12143. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  12144. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  12145. // clamp precision to maximum available
  12146. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12147. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12148. if ( _precision === "highp" && ! highpAvailable ) {
  12149. if ( mediumpAvailable ) {
  12150. _precision = "mediump";
  12151. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  12152. } else {
  12153. _precision = "lowp";
  12154. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  12155. }
  12156. }
  12157. if ( _precision === "mediump" && ! mediumpAvailable ) {
  12158. _precision = "lowp";
  12159. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  12160. }
  12161. // API
  12162. this.getContext = function () {
  12163. return _gl;
  12164. };
  12165. this.supportsVertexTextures = function () {
  12166. return _supportsVertexTextures;
  12167. };
  12168. this.supportsFloatTextures = function () {
  12169. return _glExtensionTextureFloat;
  12170. };
  12171. this.supportsStandardDerivatives = function () {
  12172. return _glExtensionStandardDerivatives;
  12173. };
  12174. this.supportsCompressedTextureS3TC = function () {
  12175. return _glExtensionCompressedTextureS3TC;
  12176. };
  12177. this.getMaxAnisotropy = function () {
  12178. return _maxAnisotropy;
  12179. };
  12180. this.getPrecision = function () {
  12181. return _precision;
  12182. };
  12183. this.setSize = function ( width, height, updateStyle ) {
  12184. _canvas.width = width * this.devicePixelRatio;
  12185. _canvas.height = height * this.devicePixelRatio;
  12186. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  12187. _canvas.style.width = width + 'px';
  12188. _canvas.style.height = height + 'px';
  12189. }
  12190. this.setViewport( 0, 0, width, height );
  12191. };
  12192. this.setViewport = function ( x, y, width, height ) {
  12193. _viewportX = x * this.devicePixelRatio;
  12194. _viewportY = y * this.devicePixelRatio;
  12195. _viewportWidth = width * this.devicePixelRatio;
  12196. _viewportHeight = height * this.devicePixelRatio;
  12197. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12198. };
  12199. this.setScissor = function ( x, y, width, height ) {
  12200. _gl.scissor(
  12201. x * this.devicePixelRatio,
  12202. y * this.devicePixelRatio,
  12203. width * this.devicePixelRatio,
  12204. height * this.devicePixelRatio
  12205. );
  12206. };
  12207. this.enableScissorTest = function ( enable ) {
  12208. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12209. };
  12210. // Clearing
  12211. this.setClearColor = function ( color, alpha ) {
  12212. _clearColor.set( color );
  12213. _clearAlpha = alpha !== undefined ? alpha : 1;
  12214. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12215. };
  12216. this.setClearColorHex = function ( hex, alpha ) {
  12217. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  12218. this.setClearColor( hex, alpha );
  12219. };
  12220. this.getClearColor = function () {
  12221. return _clearColor;
  12222. };
  12223. this.getClearAlpha = function () {
  12224. return _clearAlpha;
  12225. };
  12226. this.clear = function ( color, depth, stencil ) {
  12227. var bits = 0;
  12228. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12229. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12230. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12231. _gl.clear( bits );
  12232. };
  12233. this.clearColor = function () {
  12234. _gl.clear( _gl.COLOR_BUFFER_BIT );
  12235. };
  12236. this.clearDepth = function () {
  12237. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  12238. };
  12239. this.clearStencil = function () {
  12240. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  12241. };
  12242. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12243. this.setRenderTarget( renderTarget );
  12244. this.clear( color, depth, stencil );
  12245. };
  12246. // Plugins
  12247. this.addPostPlugin = function ( plugin ) {
  12248. plugin.init( this );
  12249. this.renderPluginsPost.push( plugin );
  12250. };
  12251. this.addPrePlugin = function ( plugin ) {
  12252. plugin.init( this );
  12253. this.renderPluginsPre.push( plugin );
  12254. };
  12255. // Rendering
  12256. this.updateShadowMap = function ( scene, camera ) {
  12257. _currentProgram = null;
  12258. _oldBlending = -1;
  12259. _oldDepthTest = -1;
  12260. _oldDepthWrite = -1;
  12261. _currentGeometryGroupHash = -1;
  12262. _currentMaterialId = -1;
  12263. _lightsNeedUpdate = true;
  12264. _oldDoubleSided = -1;
  12265. _oldFlipSided = -1;
  12266. this.shadowMapPlugin.update( scene, camera );
  12267. };
  12268. // Internal functions
  12269. // Buffer allocation
  12270. function createParticleBuffers ( geometry ) {
  12271. geometry.__webglVertexBuffer = _gl.createBuffer();
  12272. geometry.__webglColorBuffer = _gl.createBuffer();
  12273. _this.info.memory.geometries ++;
  12274. };
  12275. function createLineBuffers ( geometry ) {
  12276. geometry.__webglVertexBuffer = _gl.createBuffer();
  12277. geometry.__webglColorBuffer = _gl.createBuffer();
  12278. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12279. _this.info.memory.geometries ++;
  12280. };
  12281. function createMeshBuffers ( geometryGroup ) {
  12282. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12283. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12284. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12285. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12286. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12287. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12288. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12289. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12290. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12291. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12292. var m, ml;
  12293. if ( geometryGroup.numMorphTargets ) {
  12294. geometryGroup.__webglMorphTargetsBuffers = [];
  12295. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12296. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12297. }
  12298. }
  12299. if ( geometryGroup.numMorphNormals ) {
  12300. geometryGroup.__webglMorphNormalsBuffers = [];
  12301. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12302. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12303. }
  12304. }
  12305. _this.info.memory.geometries ++;
  12306. };
  12307. // Events
  12308. var onGeometryDispose = function ( event ) {
  12309. var geometry = event.target;
  12310. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12311. deallocateGeometry( geometry );
  12312. };
  12313. var onTextureDispose = function ( event ) {
  12314. var texture = event.target;
  12315. texture.removeEventListener( 'dispose', onTextureDispose );
  12316. deallocateTexture( texture );
  12317. _this.info.memory.textures --;
  12318. };
  12319. var onRenderTargetDispose = function ( event ) {
  12320. var renderTarget = event.target;
  12321. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12322. deallocateRenderTarget( renderTarget );
  12323. _this.info.memory.textures --;
  12324. };
  12325. var onMaterialDispose = function ( event ) {
  12326. var material = event.target;
  12327. material.removeEventListener( 'dispose', onMaterialDispose );
  12328. deallocateMaterial( material );
  12329. };
  12330. // Buffer deallocation
  12331. var deleteBuffers = function ( geometry ) {
  12332. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12333. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12334. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12335. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12336. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12337. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12338. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12339. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12340. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12341. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12342. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12343. // custom attributes
  12344. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12345. for ( var id in geometry.__webglCustomAttributesList ) {
  12346. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12347. }
  12348. }
  12349. _this.info.memory.geometries --;
  12350. };
  12351. var deallocateGeometry = function ( geometry ) {
  12352. geometry.__webglInit = undefined;
  12353. if ( geometry instanceof THREE.BufferGeometry ) {
  12354. var attributes = geometry.attributes;
  12355. for ( var key in attributes ) {
  12356. if ( attributes[ key ].buffer !== undefined ) {
  12357. _gl.deleteBuffer( attributes[ key ].buffer );
  12358. }
  12359. }
  12360. _this.info.memory.geometries --;
  12361. } else {
  12362. if ( geometry.geometryGroups !== undefined ) {
  12363. for ( var g in geometry.geometryGroups ) {
  12364. var geometryGroup = geometry.geometryGroups[ g ];
  12365. if ( geometryGroup.numMorphTargets !== undefined ) {
  12366. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12367. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12368. }
  12369. }
  12370. if ( geometryGroup.numMorphNormals !== undefined ) {
  12371. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12372. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12373. }
  12374. }
  12375. deleteBuffers( geometryGroup );
  12376. }
  12377. } else {
  12378. deleteBuffers( geometry );
  12379. }
  12380. }
  12381. };
  12382. var deallocateTexture = function ( texture ) {
  12383. if ( texture.image && texture.image.__webglTextureCube ) {
  12384. // cube texture
  12385. _gl.deleteTexture( texture.image.__webglTextureCube );
  12386. } else {
  12387. // 2D texture
  12388. if ( ! texture.__webglInit ) return;
  12389. texture.__webglInit = false;
  12390. _gl.deleteTexture( texture.__webglTexture );
  12391. }
  12392. };
  12393. var deallocateRenderTarget = function ( renderTarget ) {
  12394. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12395. _gl.deleteTexture( renderTarget.__webglTexture );
  12396. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12397. for ( var i = 0; i < 6; i ++ ) {
  12398. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12399. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12400. }
  12401. } else {
  12402. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12403. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12404. }
  12405. };
  12406. var deallocateMaterial = function ( material ) {
  12407. var program = material.program;
  12408. if ( program === undefined ) return;
  12409. material.program = undefined;
  12410. // only deallocate GL program if this was the last use of shared program
  12411. // assumed there is only single copy of any program in the _programs list
  12412. // (that's how it's constructed)
  12413. var i, il, programInfo;
  12414. var deleteProgram = false;
  12415. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12416. programInfo = _programs[ i ];
  12417. if ( programInfo.program === program ) {
  12418. programInfo.usedTimes --;
  12419. if ( programInfo.usedTimes === 0 ) {
  12420. deleteProgram = true;
  12421. }
  12422. break;
  12423. }
  12424. }
  12425. if ( deleteProgram === true ) {
  12426. // avoid using array.splice, this is costlier than creating new array from scratch
  12427. var newPrograms = [];
  12428. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12429. programInfo = _programs[ i ];
  12430. if ( programInfo.program !== program ) {
  12431. newPrograms.push( programInfo );
  12432. }
  12433. }
  12434. _programs = newPrograms;
  12435. _gl.deleteProgram( program );
  12436. _this.info.memory.programs --;
  12437. }
  12438. };
  12439. // Buffer initialization
  12440. function initCustomAttributes ( geometry, object ) {
  12441. var nvertices = geometry.vertices.length;
  12442. var material = object.material;
  12443. if ( material.attributes ) {
  12444. if ( geometry.__webglCustomAttributesList === undefined ) {
  12445. geometry.__webglCustomAttributesList = [];
  12446. }
  12447. for ( var a in material.attributes ) {
  12448. var attribute = material.attributes[ a ];
  12449. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12450. attribute.__webglInitialized = true;
  12451. var size = 1; // "f" and "i"
  12452. if ( attribute.type === "v2" ) size = 2;
  12453. else if ( attribute.type === "v3" ) size = 3;
  12454. else if ( attribute.type === "v4" ) size = 4;
  12455. else if ( attribute.type === "c" ) size = 3;
  12456. attribute.size = size;
  12457. attribute.array = new Float32Array( nvertices * size );
  12458. attribute.buffer = _gl.createBuffer();
  12459. attribute.buffer.belongsToAttribute = a;
  12460. attribute.needsUpdate = true;
  12461. }
  12462. geometry.__webglCustomAttributesList.push( attribute );
  12463. }
  12464. }
  12465. };
  12466. function initParticleBuffers ( geometry, object ) {
  12467. var nvertices = geometry.vertices.length;
  12468. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12469. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12470. geometry.__sortArray = [];
  12471. geometry.__webglParticleCount = nvertices;
  12472. initCustomAttributes ( geometry, object );
  12473. };
  12474. function initLineBuffers ( geometry, object ) {
  12475. var nvertices = geometry.vertices.length;
  12476. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12477. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12478. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12479. geometry.__webglLineCount = nvertices;
  12480. initCustomAttributes ( geometry, object );
  12481. };
  12482. function initMeshBuffers ( geometryGroup, object ) {
  12483. var geometry = object.geometry,
  12484. faces3 = geometryGroup.faces3,
  12485. nvertices = faces3.length * 3,
  12486. ntris = faces3.length * 1,
  12487. nlines = faces3.length * 3,
  12488. material = getBufferMaterial( object, geometryGroup ),
  12489. uvType = bufferGuessUVType( material ),
  12490. normalType = bufferGuessNormalType( material ),
  12491. vertexColorType = bufferGuessVertexColorType( material );
  12492. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12493. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12494. if ( normalType ) {
  12495. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12496. }
  12497. if ( geometry.hasTangents ) {
  12498. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12499. }
  12500. if ( vertexColorType ) {
  12501. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12502. }
  12503. if ( uvType ) {
  12504. if ( geometry.faceVertexUvs.length > 0 ) {
  12505. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12506. }
  12507. if ( geometry.faceVertexUvs.length > 1 ) {
  12508. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12509. }
  12510. }
  12511. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12512. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12513. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12514. }
  12515. var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  12516. geometryGroup.__typeArray = UintArray;
  12517. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  12518. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  12519. var m, ml;
  12520. if ( geometryGroup.numMorphTargets ) {
  12521. geometryGroup.__morphTargetsArrays = [];
  12522. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12523. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12524. }
  12525. }
  12526. if ( geometryGroup.numMorphNormals ) {
  12527. geometryGroup.__morphNormalsArrays = [];
  12528. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12529. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12530. }
  12531. }
  12532. geometryGroup.__webglFaceCount = ntris * 3;
  12533. geometryGroup.__webglLineCount = nlines * 2;
  12534. // custom attributes
  12535. if ( material.attributes ) {
  12536. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12537. geometryGroup.__webglCustomAttributesList = [];
  12538. }
  12539. for ( var a in material.attributes ) {
  12540. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12541. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12542. var originalAttribute = material.attributes[ a ];
  12543. var attribute = {};
  12544. for ( var property in originalAttribute ) {
  12545. attribute[ property ] = originalAttribute[ property ];
  12546. }
  12547. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12548. attribute.__webglInitialized = true;
  12549. var size = 1; // "f" and "i"
  12550. if( attribute.type === "v2" ) size = 2;
  12551. else if( attribute.type === "v3" ) size = 3;
  12552. else if( attribute.type === "v4" ) size = 4;
  12553. else if( attribute.type === "c" ) size = 3;
  12554. attribute.size = size;
  12555. attribute.array = new Float32Array( nvertices * size );
  12556. attribute.buffer = _gl.createBuffer();
  12557. attribute.buffer.belongsToAttribute = a;
  12558. originalAttribute.needsUpdate = true;
  12559. attribute.__original = originalAttribute;
  12560. }
  12561. geometryGroup.__webglCustomAttributesList.push( attribute );
  12562. }
  12563. }
  12564. geometryGroup.__inittedArrays = true;
  12565. };
  12566. function getBufferMaterial( object, geometryGroup ) {
  12567. return object.material instanceof THREE.MeshFaceMaterial
  12568. ? object.material.materials[ geometryGroup.materialIndex ]
  12569. : object.material;
  12570. };
  12571. function materialNeedsSmoothNormals ( material ) {
  12572. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12573. };
  12574. function bufferGuessNormalType ( material ) {
  12575. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12576. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12577. return false;
  12578. }
  12579. if ( materialNeedsSmoothNormals( material ) ) {
  12580. return THREE.SmoothShading;
  12581. } else {
  12582. return THREE.FlatShading;
  12583. }
  12584. };
  12585. function bufferGuessVertexColorType( material ) {
  12586. if ( material.vertexColors ) {
  12587. return material.vertexColors;
  12588. }
  12589. return false;
  12590. };
  12591. function bufferGuessUVType( material ) {
  12592. // material must use some texture to require uvs
  12593. if ( material.map ||
  12594. material.lightMap ||
  12595. material.bumpMap ||
  12596. material.normalMap ||
  12597. material.specularMap ||
  12598. material instanceof THREE.ShaderMaterial ) {
  12599. return true;
  12600. }
  12601. return false;
  12602. };
  12603. //
  12604. function initDirectBuffers( geometry ) {
  12605. for ( var name in geometry.attributes ) {
  12606. var bufferType = ( name === "index" ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  12607. var attribute = geometry.attributes[ name ];
  12608. attribute.buffer = _gl.createBuffer();
  12609. _gl.bindBuffer( bufferType, attribute.buffer );
  12610. _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW );
  12611. }
  12612. }
  12613. // Buffer setting
  12614. function setParticleBuffers ( geometry, hint, object ) {
  12615. var v, c, vertex, offset, index, color,
  12616. vertices = geometry.vertices,
  12617. vl = vertices.length,
  12618. colors = geometry.colors,
  12619. cl = colors.length,
  12620. vertexArray = geometry.__vertexArray,
  12621. colorArray = geometry.__colorArray,
  12622. sortArray = geometry.__sortArray,
  12623. dirtyVertices = geometry.verticesNeedUpdate,
  12624. dirtyElements = geometry.elementsNeedUpdate,
  12625. dirtyColors = geometry.colorsNeedUpdate,
  12626. customAttributes = geometry.__webglCustomAttributesList,
  12627. i, il,
  12628. a, ca, cal, value,
  12629. customAttribute;
  12630. if ( object.sortParticles ) {
  12631. _projScreenMatrixPS.copy( _projScreenMatrix );
  12632. _projScreenMatrixPS.multiply( object.matrixWorld );
  12633. for ( v = 0; v < vl; v ++ ) {
  12634. vertex = vertices[ v ];
  12635. _vector3.copy( vertex );
  12636. _vector3.applyProjection( _projScreenMatrixPS );
  12637. sortArray[ v ] = [ _vector3.z, v ];
  12638. }
  12639. sortArray.sort( numericalSort );
  12640. for ( v = 0; v < vl; v ++ ) {
  12641. vertex = vertices[ sortArray[v][1] ];
  12642. offset = v * 3;
  12643. vertexArray[ offset ] = vertex.x;
  12644. vertexArray[ offset + 1 ] = vertex.y;
  12645. vertexArray[ offset + 2 ] = vertex.z;
  12646. }
  12647. for ( c = 0; c < cl; c ++ ) {
  12648. offset = c * 3;
  12649. color = colors[ sortArray[c][1] ];
  12650. colorArray[ offset ] = color.r;
  12651. colorArray[ offset + 1 ] = color.g;
  12652. colorArray[ offset + 2 ] = color.b;
  12653. }
  12654. if ( customAttributes ) {
  12655. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12656. customAttribute = customAttributes[ i ];
  12657. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12658. offset = 0;
  12659. cal = customAttribute.value.length;
  12660. if ( customAttribute.size === 1 ) {
  12661. for ( ca = 0; ca < cal; ca ++ ) {
  12662. index = sortArray[ ca ][ 1 ];
  12663. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12664. }
  12665. } else if ( customAttribute.size === 2 ) {
  12666. for ( ca = 0; ca < cal; ca ++ ) {
  12667. index = sortArray[ ca ][ 1 ];
  12668. value = customAttribute.value[ index ];
  12669. customAttribute.array[ offset ] = value.x;
  12670. customAttribute.array[ offset + 1 ] = value.y;
  12671. offset += 2;
  12672. }
  12673. } else if ( customAttribute.size === 3 ) {
  12674. if ( customAttribute.type === "c" ) {
  12675. for ( ca = 0; ca < cal; ca ++ ) {
  12676. index = sortArray[ ca ][ 1 ];
  12677. value = customAttribute.value[ index ];
  12678. customAttribute.array[ offset ] = value.r;
  12679. customAttribute.array[ offset + 1 ] = value.g;
  12680. customAttribute.array[ offset + 2 ] = value.b;
  12681. offset += 3;
  12682. }
  12683. } else {
  12684. for ( ca = 0; ca < cal; ca ++ ) {
  12685. index = sortArray[ ca ][ 1 ];
  12686. value = customAttribute.value[ index ];
  12687. customAttribute.array[ offset ] = value.x;
  12688. customAttribute.array[ offset + 1 ] = value.y;
  12689. customAttribute.array[ offset + 2 ] = value.z;
  12690. offset += 3;
  12691. }
  12692. }
  12693. } else if ( customAttribute.size === 4 ) {
  12694. for ( ca = 0; ca < cal; ca ++ ) {
  12695. index = sortArray[ ca ][ 1 ];
  12696. value = customAttribute.value[ index ];
  12697. customAttribute.array[ offset ] = value.x;
  12698. customAttribute.array[ offset + 1 ] = value.y;
  12699. customAttribute.array[ offset + 2 ] = value.z;
  12700. customAttribute.array[ offset + 3 ] = value.w;
  12701. offset += 4;
  12702. }
  12703. }
  12704. }
  12705. }
  12706. } else {
  12707. if ( dirtyVertices ) {
  12708. for ( v = 0; v < vl; v ++ ) {
  12709. vertex = vertices[ v ];
  12710. offset = v * 3;
  12711. vertexArray[ offset ] = vertex.x;
  12712. vertexArray[ offset + 1 ] = vertex.y;
  12713. vertexArray[ offset + 2 ] = vertex.z;
  12714. }
  12715. }
  12716. if ( dirtyColors ) {
  12717. for ( c = 0; c < cl; c ++ ) {
  12718. color = colors[ c ];
  12719. offset = c * 3;
  12720. colorArray[ offset ] = color.r;
  12721. colorArray[ offset + 1 ] = color.g;
  12722. colorArray[ offset + 2 ] = color.b;
  12723. }
  12724. }
  12725. if ( customAttributes ) {
  12726. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12727. customAttribute = customAttributes[ i ];
  12728. if ( customAttribute.needsUpdate &&
  12729. ( customAttribute.boundTo === undefined ||
  12730. customAttribute.boundTo === "vertices") ) {
  12731. cal = customAttribute.value.length;
  12732. offset = 0;
  12733. if ( customAttribute.size === 1 ) {
  12734. for ( ca = 0; ca < cal; ca ++ ) {
  12735. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12736. }
  12737. } else if ( customAttribute.size === 2 ) {
  12738. for ( ca = 0; ca < cal; ca ++ ) {
  12739. value = customAttribute.value[ ca ];
  12740. customAttribute.array[ offset ] = value.x;
  12741. customAttribute.array[ offset + 1 ] = value.y;
  12742. offset += 2;
  12743. }
  12744. } else if ( customAttribute.size === 3 ) {
  12745. if ( customAttribute.type === "c" ) {
  12746. for ( ca = 0; ca < cal; ca ++ ) {
  12747. value = customAttribute.value[ ca ];
  12748. customAttribute.array[ offset ] = value.r;
  12749. customAttribute.array[ offset + 1 ] = value.g;
  12750. customAttribute.array[ offset + 2 ] = value.b;
  12751. offset += 3;
  12752. }
  12753. } else {
  12754. for ( ca = 0; ca < cal; ca ++ ) {
  12755. value = customAttribute.value[ ca ];
  12756. customAttribute.array[ offset ] = value.x;
  12757. customAttribute.array[ offset + 1 ] = value.y;
  12758. customAttribute.array[ offset + 2 ] = value.z;
  12759. offset += 3;
  12760. }
  12761. }
  12762. } else if ( customAttribute.size === 4 ) {
  12763. for ( ca = 0; ca < cal; ca ++ ) {
  12764. value = customAttribute.value[ ca ];
  12765. customAttribute.array[ offset ] = value.x;
  12766. customAttribute.array[ offset + 1 ] = value.y;
  12767. customAttribute.array[ offset + 2 ] = value.z;
  12768. customAttribute.array[ offset + 3 ] = value.w;
  12769. offset += 4;
  12770. }
  12771. }
  12772. }
  12773. }
  12774. }
  12775. }
  12776. if ( dirtyVertices || object.sortParticles ) {
  12777. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12778. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12779. }
  12780. if ( dirtyColors || object.sortParticles ) {
  12781. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12782. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12783. }
  12784. if ( customAttributes ) {
  12785. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12786. customAttribute = customAttributes[ i ];
  12787. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12788. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12789. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12790. }
  12791. }
  12792. }
  12793. }
  12794. function setLineBuffers ( geometry, hint ) {
  12795. var v, c, d, vertex, offset, color,
  12796. vertices = geometry.vertices,
  12797. colors = geometry.colors,
  12798. lineDistances = geometry.lineDistances,
  12799. vl = vertices.length,
  12800. cl = colors.length,
  12801. dl = lineDistances.length,
  12802. vertexArray = geometry.__vertexArray,
  12803. colorArray = geometry.__colorArray,
  12804. lineDistanceArray = geometry.__lineDistanceArray,
  12805. dirtyVertices = geometry.verticesNeedUpdate,
  12806. dirtyColors = geometry.colorsNeedUpdate,
  12807. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12808. customAttributes = geometry.__webglCustomAttributesList,
  12809. i, il,
  12810. a, ca, cal, value,
  12811. customAttribute;
  12812. if ( dirtyVertices ) {
  12813. for ( v = 0; v < vl; v ++ ) {
  12814. vertex = vertices[ v ];
  12815. offset = v * 3;
  12816. vertexArray[ offset ] = vertex.x;
  12817. vertexArray[ offset + 1 ] = vertex.y;
  12818. vertexArray[ offset + 2 ] = vertex.z;
  12819. }
  12820. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12821. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12822. }
  12823. if ( dirtyColors ) {
  12824. for ( c = 0; c < cl; c ++ ) {
  12825. color = colors[ c ];
  12826. offset = c * 3;
  12827. colorArray[ offset ] = color.r;
  12828. colorArray[ offset + 1 ] = color.g;
  12829. colorArray[ offset + 2 ] = color.b;
  12830. }
  12831. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12832. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12833. }
  12834. if ( dirtyLineDistances ) {
  12835. for ( d = 0; d < dl; d ++ ) {
  12836. lineDistanceArray[ d ] = lineDistances[ d ];
  12837. }
  12838. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12839. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12840. }
  12841. if ( customAttributes ) {
  12842. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12843. customAttribute = customAttributes[ i ];
  12844. if ( customAttribute.needsUpdate &&
  12845. ( customAttribute.boundTo === undefined ||
  12846. customAttribute.boundTo === "vertices" ) ) {
  12847. offset = 0;
  12848. cal = customAttribute.value.length;
  12849. if ( customAttribute.size === 1 ) {
  12850. for ( ca = 0; ca < cal; ca ++ ) {
  12851. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12852. }
  12853. } else if ( customAttribute.size === 2 ) {
  12854. for ( ca = 0; ca < cal; ca ++ ) {
  12855. value = customAttribute.value[ ca ];
  12856. customAttribute.array[ offset ] = value.x;
  12857. customAttribute.array[ offset + 1 ] = value.y;
  12858. offset += 2;
  12859. }
  12860. } else if ( customAttribute.size === 3 ) {
  12861. if ( customAttribute.type === "c" ) {
  12862. for ( ca = 0; ca < cal; ca ++ ) {
  12863. value = customAttribute.value[ ca ];
  12864. customAttribute.array[ offset ] = value.r;
  12865. customAttribute.array[ offset + 1 ] = value.g;
  12866. customAttribute.array[ offset + 2 ] = value.b;
  12867. offset += 3;
  12868. }
  12869. } else {
  12870. for ( ca = 0; ca < cal; ca ++ ) {
  12871. value = customAttribute.value[ ca ];
  12872. customAttribute.array[ offset ] = value.x;
  12873. customAttribute.array[ offset + 1 ] = value.y;
  12874. customAttribute.array[ offset + 2 ] = value.z;
  12875. offset += 3;
  12876. }
  12877. }
  12878. } else if ( customAttribute.size === 4 ) {
  12879. for ( ca = 0; ca < cal; ca ++ ) {
  12880. value = customAttribute.value[ ca ];
  12881. customAttribute.array[ offset ] = value.x;
  12882. customAttribute.array[ offset + 1 ] = value.y;
  12883. customAttribute.array[ offset + 2 ] = value.z;
  12884. customAttribute.array[ offset + 3 ] = value.w;
  12885. offset += 4;
  12886. }
  12887. }
  12888. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12889. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12890. }
  12891. }
  12892. }
  12893. }
  12894. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12895. if ( ! geometryGroup.__inittedArrays ) {
  12896. return;
  12897. }
  12898. var normalType = bufferGuessNormalType( material ),
  12899. vertexColorType = bufferGuessVertexColorType( material ),
  12900. uvType = bufferGuessUVType( material ),
  12901. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12902. var f, fl, fi, face,
  12903. vertexNormals, faceNormal, normal,
  12904. vertexColors, faceColor,
  12905. vertexTangents,
  12906. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12907. c1, c2, c3, c4,
  12908. sw1, sw2, sw3, sw4,
  12909. si1, si2, si3, si4,
  12910. sa1, sa2, sa3, sa4,
  12911. sb1, sb2, sb3, sb4,
  12912. m, ml, i, il,
  12913. vn, uvi, uv2i,
  12914. vk, vkl, vka,
  12915. nka, chf, faceVertexNormals,
  12916. a,
  12917. vertexIndex = 0,
  12918. offset = 0,
  12919. offset_uv = 0,
  12920. offset_uv2 = 0,
  12921. offset_face = 0,
  12922. offset_normal = 0,
  12923. offset_tangent = 0,
  12924. offset_line = 0,
  12925. offset_color = 0,
  12926. offset_skin = 0,
  12927. offset_morphTarget = 0,
  12928. offset_custom = 0,
  12929. offset_customSrc = 0,
  12930. value,
  12931. vertexArray = geometryGroup.__vertexArray,
  12932. uvArray = geometryGroup.__uvArray,
  12933. uv2Array = geometryGroup.__uv2Array,
  12934. normalArray = geometryGroup.__normalArray,
  12935. tangentArray = geometryGroup.__tangentArray,
  12936. colorArray = geometryGroup.__colorArray,
  12937. skinIndexArray = geometryGroup.__skinIndexArray,
  12938. skinWeightArray = geometryGroup.__skinWeightArray,
  12939. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12940. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12941. customAttributes = geometryGroup.__webglCustomAttributesList,
  12942. customAttribute,
  12943. faceArray = geometryGroup.__faceArray,
  12944. lineArray = geometryGroup.__lineArray,
  12945. geometry = object.geometry, // this is shared for all chunks
  12946. dirtyVertices = geometry.verticesNeedUpdate,
  12947. dirtyElements = geometry.elementsNeedUpdate,
  12948. dirtyUvs = geometry.uvsNeedUpdate,
  12949. dirtyNormals = geometry.normalsNeedUpdate,
  12950. dirtyTangents = geometry.tangentsNeedUpdate,
  12951. dirtyColors = geometry.colorsNeedUpdate,
  12952. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12953. vertices = geometry.vertices,
  12954. chunk_faces3 = geometryGroup.faces3,
  12955. obj_faces = geometry.faces,
  12956. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12957. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12958. obj_colors = geometry.colors,
  12959. obj_skinIndices = geometry.skinIndices,
  12960. obj_skinWeights = geometry.skinWeights,
  12961. morphTargets = geometry.morphTargets,
  12962. morphNormals = geometry.morphNormals;
  12963. if ( dirtyVertices ) {
  12964. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12965. face = obj_faces[ chunk_faces3[ f ] ];
  12966. v1 = vertices[ face.a ];
  12967. v2 = vertices[ face.b ];
  12968. v3 = vertices[ face.c ];
  12969. vertexArray[ offset ] = v1.x;
  12970. vertexArray[ offset + 1 ] = v1.y;
  12971. vertexArray[ offset + 2 ] = v1.z;
  12972. vertexArray[ offset + 3 ] = v2.x;
  12973. vertexArray[ offset + 4 ] = v2.y;
  12974. vertexArray[ offset + 5 ] = v2.z;
  12975. vertexArray[ offset + 6 ] = v3.x;
  12976. vertexArray[ offset + 7 ] = v3.y;
  12977. vertexArray[ offset + 8 ] = v3.z;
  12978. offset += 9;
  12979. }
  12980. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12981. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12982. }
  12983. if ( dirtyMorphTargets ) {
  12984. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12985. offset_morphTarget = 0;
  12986. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12987. chf = chunk_faces3[ f ];
  12988. face = obj_faces[ chf ];
  12989. // morph positions
  12990. v1 = morphTargets[ vk ].vertices[ face.a ];
  12991. v2 = morphTargets[ vk ].vertices[ face.b ];
  12992. v3 = morphTargets[ vk ].vertices[ face.c ];
  12993. vka = morphTargetsArrays[ vk ];
  12994. vka[ offset_morphTarget ] = v1.x;
  12995. vka[ offset_morphTarget + 1 ] = v1.y;
  12996. vka[ offset_morphTarget + 2 ] = v1.z;
  12997. vka[ offset_morphTarget + 3 ] = v2.x;
  12998. vka[ offset_morphTarget + 4 ] = v2.y;
  12999. vka[ offset_morphTarget + 5 ] = v2.z;
  13000. vka[ offset_morphTarget + 6 ] = v3.x;
  13001. vka[ offset_morphTarget + 7 ] = v3.y;
  13002. vka[ offset_morphTarget + 8 ] = v3.z;
  13003. // morph normals
  13004. if ( material.morphNormals ) {
  13005. if ( needsSmoothNormals ) {
  13006. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  13007. n1 = faceVertexNormals.a;
  13008. n2 = faceVertexNormals.b;
  13009. n3 = faceVertexNormals.c;
  13010. } else {
  13011. n1 = morphNormals[ vk ].faceNormals[ chf ];
  13012. n2 = n1;
  13013. n3 = n1;
  13014. }
  13015. nka = morphNormalsArrays[ vk ];
  13016. nka[ offset_morphTarget ] = n1.x;
  13017. nka[ offset_morphTarget + 1 ] = n1.y;
  13018. nka[ offset_morphTarget + 2 ] = n1.z;
  13019. nka[ offset_morphTarget + 3 ] = n2.x;
  13020. nka[ offset_morphTarget + 4 ] = n2.y;
  13021. nka[ offset_morphTarget + 5 ] = n2.z;
  13022. nka[ offset_morphTarget + 6 ] = n3.x;
  13023. nka[ offset_morphTarget + 7 ] = n3.y;
  13024. nka[ offset_morphTarget + 8 ] = n3.z;
  13025. }
  13026. //
  13027. offset_morphTarget += 9;
  13028. }
  13029. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  13030. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  13031. if ( material.morphNormals ) {
  13032. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  13033. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  13034. }
  13035. }
  13036. }
  13037. if ( obj_skinWeights.length ) {
  13038. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13039. face = obj_faces[ chunk_faces3[ f ] ];
  13040. // weights
  13041. sw1 = obj_skinWeights[ face.a ];
  13042. sw2 = obj_skinWeights[ face.b ];
  13043. sw3 = obj_skinWeights[ face.c ];
  13044. skinWeightArray[ offset_skin ] = sw1.x;
  13045. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  13046. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  13047. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  13048. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  13049. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  13050. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  13051. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  13052. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  13053. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  13054. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  13055. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  13056. // indices
  13057. si1 = obj_skinIndices[ face.a ];
  13058. si2 = obj_skinIndices[ face.b ];
  13059. si3 = obj_skinIndices[ face.c ];
  13060. skinIndexArray[ offset_skin ] = si1.x;
  13061. skinIndexArray[ offset_skin + 1 ] = si1.y;
  13062. skinIndexArray[ offset_skin + 2 ] = si1.z;
  13063. skinIndexArray[ offset_skin + 3 ] = si1.w;
  13064. skinIndexArray[ offset_skin + 4 ] = si2.x;
  13065. skinIndexArray[ offset_skin + 5 ] = si2.y;
  13066. skinIndexArray[ offset_skin + 6 ] = si2.z;
  13067. skinIndexArray[ offset_skin + 7 ] = si2.w;
  13068. skinIndexArray[ offset_skin + 8 ] = si3.x;
  13069. skinIndexArray[ offset_skin + 9 ] = si3.y;
  13070. skinIndexArray[ offset_skin + 10 ] = si3.z;
  13071. skinIndexArray[ offset_skin + 11 ] = si3.w;
  13072. offset_skin += 12;
  13073. }
  13074. if ( offset_skin > 0 ) {
  13075. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13076. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  13077. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13078. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  13079. }
  13080. }
  13081. if ( dirtyColors && vertexColorType ) {
  13082. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13083. face = obj_faces[ chunk_faces3[ f ] ];
  13084. vertexColors = face.vertexColors;
  13085. faceColor = face.color;
  13086. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  13087. c1 = vertexColors[ 0 ];
  13088. c2 = vertexColors[ 1 ];
  13089. c3 = vertexColors[ 2 ];
  13090. } else {
  13091. c1 = faceColor;
  13092. c2 = faceColor;
  13093. c3 = faceColor;
  13094. }
  13095. colorArray[ offset_color ] = c1.r;
  13096. colorArray[ offset_color + 1 ] = c1.g;
  13097. colorArray[ offset_color + 2 ] = c1.b;
  13098. colorArray[ offset_color + 3 ] = c2.r;
  13099. colorArray[ offset_color + 4 ] = c2.g;
  13100. colorArray[ offset_color + 5 ] = c2.b;
  13101. colorArray[ offset_color + 6 ] = c3.r;
  13102. colorArray[ offset_color + 7 ] = c3.g;
  13103. colorArray[ offset_color + 8 ] = c3.b;
  13104. offset_color += 9;
  13105. }
  13106. if ( offset_color > 0 ) {
  13107. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13108. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13109. }
  13110. }
  13111. if ( dirtyTangents && geometry.hasTangents ) {
  13112. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13113. face = obj_faces[ chunk_faces3[ f ] ];
  13114. vertexTangents = face.vertexTangents;
  13115. t1 = vertexTangents[ 0 ];
  13116. t2 = vertexTangents[ 1 ];
  13117. t3 = vertexTangents[ 2 ];
  13118. tangentArray[ offset_tangent ] = t1.x;
  13119. tangentArray[ offset_tangent + 1 ] = t1.y;
  13120. tangentArray[ offset_tangent + 2 ] = t1.z;
  13121. tangentArray[ offset_tangent + 3 ] = t1.w;
  13122. tangentArray[ offset_tangent + 4 ] = t2.x;
  13123. tangentArray[ offset_tangent + 5 ] = t2.y;
  13124. tangentArray[ offset_tangent + 6 ] = t2.z;
  13125. tangentArray[ offset_tangent + 7 ] = t2.w;
  13126. tangentArray[ offset_tangent + 8 ] = t3.x;
  13127. tangentArray[ offset_tangent + 9 ] = t3.y;
  13128. tangentArray[ offset_tangent + 10 ] = t3.z;
  13129. tangentArray[ offset_tangent + 11 ] = t3.w;
  13130. offset_tangent += 12;
  13131. }
  13132. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13133. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  13134. }
  13135. if ( dirtyNormals && normalType ) {
  13136. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13137. face = obj_faces[ chunk_faces3[ f ] ];
  13138. vertexNormals = face.vertexNormals;
  13139. faceNormal = face.normal;
  13140. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  13141. for ( i = 0; i < 3; i ++ ) {
  13142. vn = vertexNormals[ i ];
  13143. normalArray[ offset_normal ] = vn.x;
  13144. normalArray[ offset_normal + 1 ] = vn.y;
  13145. normalArray[ offset_normal + 2 ] = vn.z;
  13146. offset_normal += 3;
  13147. }
  13148. } else {
  13149. for ( i = 0; i < 3; i ++ ) {
  13150. normalArray[ offset_normal ] = faceNormal.x;
  13151. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13152. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13153. offset_normal += 3;
  13154. }
  13155. }
  13156. }
  13157. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13158. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  13159. }
  13160. if ( dirtyUvs && obj_uvs && uvType ) {
  13161. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13162. fi = chunk_faces3[ f ];
  13163. uv = obj_uvs[ fi ];
  13164. if ( uv === undefined ) continue;
  13165. for ( i = 0; i < 3; i ++ ) {
  13166. uvi = uv[ i ];
  13167. uvArray[ offset_uv ] = uvi.x;
  13168. uvArray[ offset_uv + 1 ] = uvi.y;
  13169. offset_uv += 2;
  13170. }
  13171. }
  13172. if ( offset_uv > 0 ) {
  13173. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13174. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  13175. }
  13176. }
  13177. if ( dirtyUvs && obj_uvs2 && uvType ) {
  13178. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13179. fi = chunk_faces3[ f ];
  13180. uv2 = obj_uvs2[ fi ];
  13181. if ( uv2 === undefined ) continue;
  13182. for ( i = 0; i < 3; i ++ ) {
  13183. uv2i = uv2[ i ];
  13184. uv2Array[ offset_uv2 ] = uv2i.x;
  13185. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13186. offset_uv2 += 2;
  13187. }
  13188. }
  13189. if ( offset_uv2 > 0 ) {
  13190. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13191. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  13192. }
  13193. }
  13194. if ( dirtyElements ) {
  13195. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13196. faceArray[ offset_face ] = vertexIndex;
  13197. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13198. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  13199. offset_face += 3;
  13200. lineArray[ offset_line ] = vertexIndex;
  13201. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13202. lineArray[ offset_line + 2 ] = vertexIndex;
  13203. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13204. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13205. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13206. offset_line += 6;
  13207. vertexIndex += 3;
  13208. }
  13209. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13210. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13211. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13212. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13213. }
  13214. if ( customAttributes ) {
  13215. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13216. customAttribute = customAttributes[ i ];
  13217. if ( ! customAttribute.__original.needsUpdate ) continue;
  13218. offset_custom = 0;
  13219. offset_customSrc = 0;
  13220. if ( customAttribute.size === 1 ) {
  13221. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13222. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13223. face = obj_faces[ chunk_faces3[ f ] ];
  13224. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13225. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13226. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13227. offset_custom += 3;
  13228. }
  13229. } else if ( customAttribute.boundTo === "faces" ) {
  13230. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13231. value = customAttribute.value[ chunk_faces3[ f ] ];
  13232. customAttribute.array[ offset_custom ] = value;
  13233. customAttribute.array[ offset_custom + 1 ] = value;
  13234. customAttribute.array[ offset_custom + 2 ] = value;
  13235. offset_custom += 3;
  13236. }
  13237. }
  13238. } else if ( customAttribute.size === 2 ) {
  13239. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13240. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13241. face = obj_faces[ chunk_faces3[ f ] ];
  13242. v1 = customAttribute.value[ face.a ];
  13243. v2 = customAttribute.value[ face.b ];
  13244. v3 = customAttribute.value[ face.c ];
  13245. customAttribute.array[ offset_custom ] = v1.x;
  13246. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13247. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13248. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13249. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13250. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13251. offset_custom += 6;
  13252. }
  13253. } else if ( customAttribute.boundTo === "faces" ) {
  13254. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13255. value = customAttribute.value[ chunk_faces3[ f ] ];
  13256. v1 = value;
  13257. v2 = value;
  13258. v3 = value;
  13259. customAttribute.array[ offset_custom ] = v1.x;
  13260. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13261. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13262. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13263. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13264. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13265. offset_custom += 6;
  13266. }
  13267. }
  13268. } else if ( customAttribute.size === 3 ) {
  13269. var pp;
  13270. if ( customAttribute.type === "c" ) {
  13271. pp = [ "r", "g", "b" ];
  13272. } else {
  13273. pp = [ "x", "y", "z" ];
  13274. }
  13275. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13276. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13277. face = obj_faces[ chunk_faces3[ f ] ];
  13278. v1 = customAttribute.value[ face.a ];
  13279. v2 = customAttribute.value[ face.b ];
  13280. v3 = customAttribute.value[ face.c ];
  13281. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13282. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13283. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13284. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13285. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13286. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13287. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13288. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13289. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13290. offset_custom += 9;
  13291. }
  13292. } else if ( customAttribute.boundTo === "faces" ) {
  13293. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13294. value = customAttribute.value[ chunk_faces3[ f ] ];
  13295. v1 = value;
  13296. v2 = value;
  13297. v3 = value;
  13298. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13299. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13300. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13301. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13302. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13303. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13304. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13305. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13306. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13307. offset_custom += 9;
  13308. }
  13309. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13310. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13311. value = customAttribute.value[ chunk_faces3[ f ] ];
  13312. v1 = value[ 0 ];
  13313. v2 = value[ 1 ];
  13314. v3 = value[ 2 ];
  13315. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13316. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13317. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13318. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13319. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13320. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13321. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13322. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13323. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13324. offset_custom += 9;
  13325. }
  13326. }
  13327. } else if ( customAttribute.size === 4 ) {
  13328. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13329. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13330. face = obj_faces[ chunk_faces3[ f ] ];
  13331. v1 = customAttribute.value[ face.a ];
  13332. v2 = customAttribute.value[ face.b ];
  13333. v3 = customAttribute.value[ face.c ];
  13334. customAttribute.array[ offset_custom ] = v1.x;
  13335. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13336. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13337. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13338. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13339. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13340. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13341. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13342. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13343. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13344. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13345. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13346. offset_custom += 12;
  13347. }
  13348. } else if ( customAttribute.boundTo === "faces" ) {
  13349. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13350. value = customAttribute.value[ chunk_faces3[ f ] ];
  13351. v1 = value;
  13352. v2 = value;
  13353. v3 = value;
  13354. customAttribute.array[ offset_custom ] = v1.x;
  13355. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13356. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13357. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13358. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13359. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13360. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13361. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13362. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13363. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13364. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13365. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13366. offset_custom += 12;
  13367. }
  13368. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13369. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13370. value = customAttribute.value[ chunk_faces3[ f ] ];
  13371. v1 = value[ 0 ];
  13372. v2 = value[ 1 ];
  13373. v3 = value[ 2 ];
  13374. customAttribute.array[ offset_custom ] = v1.x;
  13375. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13376. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13377. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13378. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13379. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13380. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13381. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13382. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13383. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13384. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13385. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13386. offset_custom += 12;
  13387. }
  13388. }
  13389. }
  13390. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13391. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13392. }
  13393. }
  13394. if ( dispose ) {
  13395. delete geometryGroup.__inittedArrays;
  13396. delete geometryGroup.__colorArray;
  13397. delete geometryGroup.__normalArray;
  13398. delete geometryGroup.__tangentArray;
  13399. delete geometryGroup.__uvArray;
  13400. delete geometryGroup.__uv2Array;
  13401. delete geometryGroup.__faceArray;
  13402. delete geometryGroup.__vertexArray;
  13403. delete geometryGroup.__lineArray;
  13404. delete geometryGroup.__skinIndexArray;
  13405. delete geometryGroup.__skinWeightArray;
  13406. }
  13407. };
  13408. function setDirectBuffers( geometry, hint ) {
  13409. var attributes = geometry.attributes;
  13410. var attributeName, attributeItem;
  13411. for ( attributeName in attributes ) {
  13412. attributeItem = attributes[ attributeName ];
  13413. if ( attributeItem.needsUpdate ) {
  13414. if ( attributeName === 'index' ) {
  13415. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13416. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13417. } else {
  13418. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13419. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13420. }
  13421. attributeItem.needsUpdate = false;
  13422. }
  13423. }
  13424. }
  13425. // Buffer rendering
  13426. this.renderBufferImmediate = function ( object, program, material ) {
  13427. initAttributes();
  13428. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13429. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13430. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13431. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13432. if ( object.hasPositions ) {
  13433. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13434. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13435. enableAttribute( program.attributes.position );
  13436. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13437. }
  13438. if ( object.hasNormals ) {
  13439. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13440. if ( material.shading === THREE.FlatShading ) {
  13441. var nx, ny, nz,
  13442. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13443. normalArray,
  13444. i, il = object.count * 3;
  13445. for( i = 0; i < il; i += 9 ) {
  13446. normalArray = object.normalArray;
  13447. nax = normalArray[ i ];
  13448. nay = normalArray[ i + 1 ];
  13449. naz = normalArray[ i + 2 ];
  13450. nbx = normalArray[ i + 3 ];
  13451. nby = normalArray[ i + 4 ];
  13452. nbz = normalArray[ i + 5 ];
  13453. ncx = normalArray[ i + 6 ];
  13454. ncy = normalArray[ i + 7 ];
  13455. ncz = normalArray[ i + 8 ];
  13456. nx = ( nax + nbx + ncx ) / 3;
  13457. ny = ( nay + nby + ncy ) / 3;
  13458. nz = ( naz + nbz + ncz ) / 3;
  13459. normalArray[ i ] = nx;
  13460. normalArray[ i + 1 ] = ny;
  13461. normalArray[ i + 2 ] = nz;
  13462. normalArray[ i + 3 ] = nx;
  13463. normalArray[ i + 4 ] = ny;
  13464. normalArray[ i + 5 ] = nz;
  13465. normalArray[ i + 6 ] = nx;
  13466. normalArray[ i + 7 ] = ny;
  13467. normalArray[ i + 8 ] = nz;
  13468. }
  13469. }
  13470. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13471. enableAttribute( program.attributes.normal );
  13472. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13473. }
  13474. if ( object.hasUvs && material.map ) {
  13475. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13476. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13477. enableAttribute( program.attributes.uv );
  13478. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13479. }
  13480. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13481. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13482. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13483. enableAttribute( program.attributes.color );
  13484. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13485. }
  13486. disableUnusedAttributes();
  13487. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13488. object.count = 0;
  13489. };
  13490. function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13491. for ( var attributeName in programAttributes ) {
  13492. var attributePointer = programAttributes[ attributeName ];
  13493. var attributeItem = geometryAttributes[ attributeName ];
  13494. if ( attributePointer >= 0 ) {
  13495. if ( attributeItem ) {
  13496. var attributeSize = attributeItem.itemSize;
  13497. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13498. enableAttribute( attributePointer );
  13499. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13500. } else if ( material.defaultAttributeValues ) {
  13501. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13502. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13503. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13504. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13505. }
  13506. }
  13507. }
  13508. }
  13509. disableUnusedAttributes();
  13510. }
  13511. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13512. if ( material.visible === false ) return;
  13513. var linewidth, a, attribute;
  13514. var attributeItem, attributeName, attributePointer, attributeSize;
  13515. var program = setProgram( camera, lights, fog, material, object );
  13516. var programAttributes = program.attributes;
  13517. var geometryAttributes = geometry.attributes;
  13518. var updateBuffers = false,
  13519. wireframeBit = material.wireframe ? 1 : 0,
  13520. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13521. if ( geometryHash !== _currentGeometryGroupHash ) {
  13522. _currentGeometryGroupHash = geometryHash;
  13523. updateBuffers = true;
  13524. }
  13525. if ( updateBuffers ) {
  13526. initAttributes();
  13527. }
  13528. // render mesh
  13529. if ( object instanceof THREE.Mesh ) {
  13530. var index = geometryAttributes[ "index" ];
  13531. if ( index ) {
  13532. // indexed triangles
  13533. var type, size;
  13534. if ( index.array instanceof Uint32Array ) {
  13535. type = _gl.UNSIGNED_INT;
  13536. size = 4;
  13537. } else {
  13538. type = _gl.UNSIGNED_SHORT;
  13539. size = 2;
  13540. }
  13541. var offsets = geometry.offsets;
  13542. if ( offsets.length === 0 ) {
  13543. if ( updateBuffers ) {
  13544. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13545. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13546. }
  13547. _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 );
  13548. _this.info.render.calls ++;
  13549. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13550. _this.info.render.faces += index.array.length / 3;
  13551. } else {
  13552. // if there is more than 1 chunk
  13553. // must set attribute pointers to use new offsets for each chunk
  13554. // even if geometry and materials didn't change
  13555. updateBuffers = true;
  13556. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13557. var startIndex = offsets[ i ].index;
  13558. if ( updateBuffers ) {
  13559. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13560. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13561. }
  13562. // render indexed triangles
  13563. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size );
  13564. _this.info.render.calls ++;
  13565. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13566. _this.info.render.faces += offsets[ i ].count / 3;
  13567. }
  13568. }
  13569. } else {
  13570. // non-indexed triangles
  13571. if ( updateBuffers ) {
  13572. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13573. }
  13574. var position = geometry.attributes[ "position" ];
  13575. // render non-indexed triangles
  13576. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13577. _this.info.render.calls ++;
  13578. _this.info.render.vertices += position.array.length / 3;
  13579. _this.info.render.faces += position.array.length / 3 / 3;
  13580. }
  13581. } else if ( object instanceof THREE.ParticleSystem ) {
  13582. // render particles
  13583. if ( updateBuffers ) {
  13584. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13585. }
  13586. var position = geometryAttributes[ "position" ];
  13587. // render particles
  13588. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13589. _this.info.render.calls ++;
  13590. _this.info.render.points += position.array.length / 3;
  13591. } else if ( object instanceof THREE.Line ) {
  13592. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13593. setLineWidth( material.linewidth );
  13594. var index = geometryAttributes[ "index" ];
  13595. if ( index ) {
  13596. // indexed lines
  13597. var type, size;
  13598. if ( index.array instanceof Uint32Array ){
  13599. type = _gl.UNSIGNED_INT;
  13600. size = 4;
  13601. } else {
  13602. type = _gl.UNSIGNED_SHORT;
  13603. size = 2;
  13604. }
  13605. var offsets = geometry.offsets;
  13606. if ( offsets.length === 0 ) {
  13607. if ( updateBuffers ) {
  13608. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13609. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13610. }
  13611. _gl.drawElements( _gl.LINES, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  13612. _this.info.render.calls ++;
  13613. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13614. } else {
  13615. // if there is more than 1 chunk
  13616. // must set attribute pointers to use new offsets for each chunk
  13617. // even if geometry and materials didn't change
  13618. if ( offsets.length > 1 ) updateBuffers = true;
  13619. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13620. var startIndex = offsets[ i ].index;
  13621. if ( updateBuffers ) {
  13622. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13623. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13624. }
  13625. // render indexed lines
  13626. _gl.drawElements( _gl.LINES, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  13627. _this.info.render.calls ++;
  13628. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13629. }
  13630. }
  13631. } else {
  13632. // non-indexed lines
  13633. if ( updateBuffers ) {
  13634. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13635. }
  13636. var position = geometryAttributes[ "position" ];
  13637. _gl.drawArrays( primitives, 0, position.array.length / 3 );
  13638. _this.info.render.calls ++;
  13639. _this.info.render.points += position.array.length;
  13640. }
  13641. }
  13642. };
  13643. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13644. if ( material.visible === false ) return;
  13645. var linewidth, a, attribute, i, il;
  13646. var program = setProgram( camera, lights, fog, material, object );
  13647. var attributes = program.attributes;
  13648. var updateBuffers = false,
  13649. wireframeBit = material.wireframe ? 1 : 0,
  13650. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13651. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13652. _currentGeometryGroupHash = geometryGroupHash;
  13653. updateBuffers = true;
  13654. }
  13655. if ( updateBuffers ) {
  13656. initAttributes();
  13657. }
  13658. // vertices
  13659. if ( !material.morphTargets && attributes.position >= 0 ) {
  13660. if ( updateBuffers ) {
  13661. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13662. enableAttribute( attributes.position );
  13663. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13664. }
  13665. } else {
  13666. if ( object.morphTargetBase ) {
  13667. setupMorphTargets( material, geometryGroup, object );
  13668. }
  13669. }
  13670. if ( updateBuffers ) {
  13671. // custom attributes
  13672. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13673. if ( geometryGroup.__webglCustomAttributesList ) {
  13674. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13675. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13676. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13677. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13678. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13679. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13680. }
  13681. }
  13682. }
  13683. // colors
  13684. if ( attributes.color >= 0 ) {
  13685. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13686. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13687. enableAttribute( attributes.color );
  13688. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13689. } else if ( material.defaultAttributeValues ) {
  13690. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13691. }
  13692. }
  13693. // normals
  13694. if ( attributes.normal >= 0 ) {
  13695. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13696. enableAttribute( attributes.normal );
  13697. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13698. }
  13699. // tangents
  13700. if ( attributes.tangent >= 0 ) {
  13701. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13702. enableAttribute( attributes.tangent );
  13703. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13704. }
  13705. // uvs
  13706. if ( attributes.uv >= 0 ) {
  13707. if ( object.geometry.faceVertexUvs[0] ) {
  13708. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13709. enableAttribute( attributes.uv );
  13710. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13711. } else if ( material.defaultAttributeValues ) {
  13712. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13713. }
  13714. }
  13715. if ( attributes.uv2 >= 0 ) {
  13716. if ( object.geometry.faceVertexUvs[1] ) {
  13717. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13718. enableAttribute( attributes.uv2 );
  13719. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13720. } else if ( material.defaultAttributeValues ) {
  13721. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13722. }
  13723. }
  13724. if ( material.skinning &&
  13725. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13726. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13727. enableAttribute( attributes.skinIndex );
  13728. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13729. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13730. enableAttribute( attributes.skinWeight );
  13731. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13732. }
  13733. // line distances
  13734. if ( attributes.lineDistance >= 0 ) {
  13735. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13736. enableAttribute( attributes.lineDistance );
  13737. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13738. }
  13739. }
  13740. disableUnusedAttributes();
  13741. // render mesh
  13742. if ( object instanceof THREE.Mesh ) {
  13743. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  13744. // wireframe
  13745. if ( material.wireframe ) {
  13746. setLineWidth( material.wireframeLinewidth );
  13747. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13748. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  13749. // triangles
  13750. } else {
  13751. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13752. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  13753. }
  13754. _this.info.render.calls ++;
  13755. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13756. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13757. // render lines
  13758. } else if ( object instanceof THREE.Line ) {
  13759. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13760. setLineWidth( material.linewidth );
  13761. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13762. _this.info.render.calls ++;
  13763. // render particles
  13764. } else if ( object instanceof THREE.ParticleSystem ) {
  13765. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13766. _this.info.render.calls ++;
  13767. _this.info.render.points += geometryGroup.__webglParticleCount;
  13768. }
  13769. };
  13770. function initAttributes() {
  13771. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  13772. _newAttributes[ i ] = 0;
  13773. }
  13774. }
  13775. function enableAttribute( attribute ) {
  13776. _newAttributes[ attribute ] = 1;
  13777. if ( _enabledAttributes[ attribute ] === 0 ) {
  13778. _gl.enableVertexAttribArray( attribute );
  13779. _enabledAttributes[ attribute ] = 1;
  13780. }
  13781. }
  13782. function disableUnusedAttributes() {
  13783. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  13784. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  13785. _gl.disableVertexAttribArray( i );
  13786. _enabledAttributes[ i ] = 0;
  13787. }
  13788. }
  13789. }
  13790. function setupMorphTargets ( material, geometryGroup, object ) {
  13791. // set base
  13792. var attributes = material.program.attributes;
  13793. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13794. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13795. enableAttribute( attributes.position );
  13796. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13797. } else if ( attributes.position >= 0 ) {
  13798. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13799. enableAttribute( attributes.position );
  13800. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13801. }
  13802. if ( object.morphTargetForcedOrder.length ) {
  13803. // set forced order
  13804. var m = 0;
  13805. var order = object.morphTargetForcedOrder;
  13806. var influences = object.morphTargetInfluences;
  13807. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13808. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13809. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13810. enableAttribute( attributes[ "morphTarget" + m ] );
  13811. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13812. }
  13813. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13814. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13815. enableAttribute( attributes[ "morphNormal" + m ] );
  13816. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13817. }
  13818. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13819. m ++;
  13820. }
  13821. } else {
  13822. // find the most influencing
  13823. var influence, activeInfluenceIndices = [];
  13824. var influences = object.morphTargetInfluences;
  13825. var i, il = influences.length;
  13826. for ( i = 0; i < il; i ++ ) {
  13827. influence = influences[ i ];
  13828. if ( influence > 0 ) {
  13829. activeInfluenceIndices.push( [ influence, i ] );
  13830. }
  13831. }
  13832. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13833. activeInfluenceIndices.sort( numericalSort );
  13834. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13835. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13836. activeInfluenceIndices.sort( numericalSort );
  13837. } else if ( activeInfluenceIndices.length === 0 ) {
  13838. activeInfluenceIndices.push( [ 0, 0 ] );
  13839. };
  13840. var influenceIndex, m = 0;
  13841. while ( m < material.numSupportedMorphTargets ) {
  13842. if ( activeInfluenceIndices[ m ] ) {
  13843. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13844. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13845. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13846. enableAttribute( attributes[ "morphTarget" + m ] );
  13847. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13848. }
  13849. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13850. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13851. enableAttribute( attributes[ "morphNormal" + m ] );
  13852. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13853. }
  13854. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13855. } else {
  13856. /*
  13857. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13858. if ( material.morphNormals ) {
  13859. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13860. }
  13861. */
  13862. object.__webglMorphTargetInfluences[ m ] = 0;
  13863. }
  13864. m ++;
  13865. }
  13866. }
  13867. // load updated influences uniform
  13868. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13869. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13870. }
  13871. };
  13872. // Sorting
  13873. function painterSortStable ( a, b ) {
  13874. if ( a.z !== b.z ) {
  13875. return b.z - a.z;
  13876. } else {
  13877. return a.id - b.id;
  13878. }
  13879. };
  13880. function numericalSort ( a, b ) {
  13881. return b[ 0 ] - a[ 0 ];
  13882. };
  13883. // Rendering
  13884. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13885. if ( camera instanceof THREE.Camera === false ) {
  13886. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13887. return;
  13888. }
  13889. var i, il,
  13890. webglObject, object,
  13891. renderList,
  13892. lights = scene.__lights,
  13893. fog = scene.fog;
  13894. // reset caching for this frame
  13895. _currentMaterialId = -1;
  13896. _lightsNeedUpdate = true;
  13897. // update scene graph
  13898. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13899. // update camera matrices and frustum
  13900. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13901. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13902. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13903. _frustum.setFromMatrix( _projScreenMatrix );
  13904. // update WebGL objects
  13905. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13906. // custom render plugins (pre pass)
  13907. renderPlugins( this.renderPluginsPre, scene, camera );
  13908. //
  13909. _this.info.render.calls = 0;
  13910. _this.info.render.vertices = 0;
  13911. _this.info.render.faces = 0;
  13912. _this.info.render.points = 0;
  13913. this.setRenderTarget( renderTarget );
  13914. if ( this.autoClear || forceClear ) {
  13915. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13916. }
  13917. // set matrices for regular objects (frustum culled)
  13918. renderList = scene.__webglObjects;
  13919. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13920. webglObject = renderList[ i ];
  13921. object = webglObject.object;
  13922. webglObject.id = i;
  13923. webglObject.render = false;
  13924. if ( object.visible ) {
  13925. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13926. setupMatrices( object, camera );
  13927. unrollBufferMaterial( webglObject );
  13928. webglObject.render = true;
  13929. if ( this.sortObjects === true ) {
  13930. if ( object.renderDepth !== null ) {
  13931. webglObject.z = object.renderDepth;
  13932. } else {
  13933. _vector3.setFromMatrixPosition( object.matrixWorld );
  13934. _vector3.applyProjection( _projScreenMatrix );
  13935. webglObject.z = _vector3.z;
  13936. }
  13937. }
  13938. }
  13939. }
  13940. }
  13941. if ( this.sortObjects ) {
  13942. renderList.sort( painterSortStable );
  13943. }
  13944. // set matrices for immediate objects
  13945. renderList = scene.__webglObjectsImmediate;
  13946. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13947. webglObject = renderList[ i ];
  13948. object = webglObject.object;
  13949. if ( object.visible ) {
  13950. setupMatrices( object, camera );
  13951. unrollImmediateBufferMaterial( webglObject );
  13952. }
  13953. }
  13954. if ( scene.overrideMaterial ) {
  13955. var material = scene.overrideMaterial;
  13956. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13957. this.setDepthTest( material.depthTest );
  13958. this.setDepthWrite( material.depthWrite );
  13959. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13960. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13961. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13962. } else {
  13963. var material = null;
  13964. // opaque pass (front-to-back order)
  13965. this.setBlending( THREE.NoBlending );
  13966. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13967. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13968. // transparent pass (back-to-front order)
  13969. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13970. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13971. }
  13972. // custom render plugins (post pass)
  13973. renderPlugins( this.renderPluginsPost, scene, camera );
  13974. // Generate mipmap if we're using any kind of mipmap filtering
  13975. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13976. updateRenderTargetMipmap( renderTarget );
  13977. }
  13978. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13979. this.setDepthTest( true );
  13980. this.setDepthWrite( true );
  13981. // _gl.finish();
  13982. };
  13983. function renderPlugins( plugins, scene, camera ) {
  13984. if ( ! plugins.length ) return;
  13985. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13986. // reset state for plugin (to start from clean slate)
  13987. _currentProgram = null;
  13988. _currentCamera = null;
  13989. _oldBlending = -1;
  13990. _oldDepthTest = -1;
  13991. _oldDepthWrite = -1;
  13992. _oldDoubleSided = -1;
  13993. _oldFlipSided = -1;
  13994. _currentGeometryGroupHash = -1;
  13995. _currentMaterialId = -1;
  13996. _lightsNeedUpdate = true;
  13997. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13998. // reset state after plugin (anything could have changed)
  13999. _currentProgram = null;
  14000. _currentCamera = null;
  14001. _oldBlending = -1;
  14002. _oldDepthTest = -1;
  14003. _oldDepthWrite = -1;
  14004. _oldDoubleSided = -1;
  14005. _oldFlipSided = -1;
  14006. _currentGeometryGroupHash = -1;
  14007. _currentMaterialId = -1;
  14008. _lightsNeedUpdate = true;
  14009. }
  14010. };
  14011. function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14012. var webglObject, object, buffer, material, start, end, delta;
  14013. if ( reverse ) {
  14014. start = renderList.length - 1;
  14015. end = -1;
  14016. delta = -1;
  14017. } else {
  14018. start = 0;
  14019. end = renderList.length;
  14020. delta = 1;
  14021. }
  14022. for ( var i = start; i !== end; i += delta ) {
  14023. webglObject = renderList[ i ];
  14024. if ( webglObject.render ) {
  14025. object = webglObject.object;
  14026. buffer = webglObject.buffer;
  14027. if ( overrideMaterial ) {
  14028. material = overrideMaterial;
  14029. } else {
  14030. material = webglObject[ materialType ];
  14031. if ( ! material ) continue;
  14032. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14033. _this.setDepthTest( material.depthTest );
  14034. _this.setDepthWrite( material.depthWrite );
  14035. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14036. }
  14037. _this.setMaterialFaces( material );
  14038. if ( buffer instanceof THREE.BufferGeometry ) {
  14039. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  14040. } else {
  14041. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  14042. }
  14043. }
  14044. }
  14045. };
  14046. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14047. var webglObject, object, material, program;
  14048. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  14049. webglObject = renderList[ i ];
  14050. object = webglObject.object;
  14051. if ( object.visible ) {
  14052. if ( overrideMaterial ) {
  14053. material = overrideMaterial;
  14054. } else {
  14055. material = webglObject[ materialType ];
  14056. if ( ! material ) continue;
  14057. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14058. _this.setDepthTest( material.depthTest );
  14059. _this.setDepthWrite( material.depthWrite );
  14060. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14061. }
  14062. _this.renderImmediateObject( camera, lights, fog, material, object );
  14063. }
  14064. }
  14065. };
  14066. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  14067. var program = setProgram( camera, lights, fog, material, object );
  14068. _currentGeometryGroupHash = -1;
  14069. _this.setMaterialFaces( material );
  14070. if ( object.immediateRenderCallback ) {
  14071. object.immediateRenderCallback( program, _gl, _frustum );
  14072. } else {
  14073. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  14074. }
  14075. };
  14076. function unrollImmediateBufferMaterial ( globject ) {
  14077. var object = globject.object,
  14078. material = object.material;
  14079. if ( material.transparent ) {
  14080. globject.transparent = material;
  14081. globject.opaque = null;
  14082. } else {
  14083. globject.opaque = material;
  14084. globject.transparent = null;
  14085. }
  14086. };
  14087. function unrollBufferMaterial ( globject ) {
  14088. var object = globject.object;
  14089. var buffer = globject.buffer;
  14090. var geometry = object.geometry;
  14091. var material = object.material;
  14092. if ( material instanceof THREE.MeshFaceMaterial ) {
  14093. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  14094. material = material.materials[ materialIndex ];
  14095. if ( material.transparent ) {
  14096. globject.transparent = material;
  14097. globject.opaque = null;
  14098. } else {
  14099. globject.opaque = material;
  14100. globject.transparent = null;
  14101. }
  14102. } else {
  14103. if ( material ) {
  14104. if ( material.transparent ) {
  14105. globject.transparent = material;
  14106. globject.opaque = null;
  14107. } else {
  14108. globject.opaque = material;
  14109. globject.transparent = null;
  14110. }
  14111. }
  14112. }
  14113. };
  14114. // Objects refresh
  14115. this.initWebGLObjects = function ( scene ) {
  14116. if ( !scene.__webglObjects ) {
  14117. scene.__webglObjects = [];
  14118. scene.__webglObjectsImmediate = [];
  14119. scene.__webglSprites = [];
  14120. scene.__webglFlares = [];
  14121. }
  14122. while ( scene.__objectsAdded.length ) {
  14123. addObject( scene.__objectsAdded[ 0 ], scene );
  14124. scene.__objectsAdded.splice( 0, 1 );
  14125. }
  14126. while ( scene.__objectsRemoved.length ) {
  14127. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14128. scene.__objectsRemoved.splice( 0, 1 );
  14129. }
  14130. // update must be called after objects adding / removal
  14131. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14132. var object = scene.__webglObjects[ o ].object;
  14133. // TODO: Remove this hack (WebGLRenderer refactoring)
  14134. if ( object.__webglInit === undefined ) {
  14135. if ( object.__webglActive !== undefined ) {
  14136. removeObject( object, scene );
  14137. }
  14138. addObject( object, scene );
  14139. }
  14140. updateObject( object );
  14141. }
  14142. };
  14143. // Objects adding
  14144. function addObject( object, scene ) {
  14145. var g, geometry, material, geometryGroup;
  14146. if ( object.__webglInit === undefined ) {
  14147. object.__webglInit = true;
  14148. object._modelViewMatrix = new THREE.Matrix4();
  14149. object._normalMatrix = new THREE.Matrix3();
  14150. geometry = object.geometry;
  14151. if ( geometry === undefined ) {
  14152. // ImmediateRenderObject
  14153. } else if ( geometry.__webglInit === undefined ) {
  14154. geometry.__webglInit = true;
  14155. geometry.addEventListener( 'dispose', onGeometryDispose );
  14156. if ( geometry instanceof THREE.BufferGeometry ) {
  14157. initDirectBuffers( geometry );
  14158. } else if ( object instanceof THREE.Mesh ) {
  14159. material = object.material;
  14160. if ( geometry.geometryGroups === undefined ) {
  14161. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 );
  14162. }
  14163. // create separate VBOs per geometry chunk
  14164. for ( g in geometry.geometryGroups ) {
  14165. geometryGroup = geometry.geometryGroups[ g ];
  14166. // initialise VBO on the first access
  14167. if ( ! geometryGroup.__webglVertexBuffer ) {
  14168. createMeshBuffers( geometryGroup );
  14169. initMeshBuffers( geometryGroup, object );
  14170. geometry.verticesNeedUpdate = true;
  14171. geometry.morphTargetsNeedUpdate = true;
  14172. geometry.elementsNeedUpdate = true;
  14173. geometry.uvsNeedUpdate = true;
  14174. geometry.normalsNeedUpdate = true;
  14175. geometry.tangentsNeedUpdate = true;
  14176. geometry.colorsNeedUpdate = true;
  14177. }
  14178. }
  14179. } else if ( object instanceof THREE.Line ) {
  14180. if ( ! geometry.__webglVertexBuffer ) {
  14181. createLineBuffers( geometry );
  14182. initLineBuffers( geometry, object );
  14183. geometry.verticesNeedUpdate = true;
  14184. geometry.colorsNeedUpdate = true;
  14185. geometry.lineDistancesNeedUpdate = true;
  14186. }
  14187. } else if ( object instanceof THREE.ParticleSystem ) {
  14188. if ( ! geometry.__webglVertexBuffer ) {
  14189. createParticleBuffers( geometry );
  14190. initParticleBuffers( geometry, object );
  14191. geometry.verticesNeedUpdate = true;
  14192. geometry.colorsNeedUpdate = true;
  14193. }
  14194. }
  14195. }
  14196. }
  14197. if ( object.__webglActive === undefined ) {
  14198. if ( object instanceof THREE.Mesh ) {
  14199. geometry = object.geometry;
  14200. if ( geometry instanceof THREE.BufferGeometry ) {
  14201. addBuffer( scene.__webglObjects, geometry, object );
  14202. } else if ( geometry instanceof THREE.Geometry ) {
  14203. for ( g in geometry.geometryGroups ) {
  14204. geometryGroup = geometry.geometryGroups[ g ];
  14205. addBuffer( scene.__webglObjects, geometryGroup, object );
  14206. }
  14207. }
  14208. } else if ( object instanceof THREE.Line ||
  14209. object instanceof THREE.ParticleSystem ) {
  14210. geometry = object.geometry;
  14211. addBuffer( scene.__webglObjects, geometry, object );
  14212. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14213. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14214. } else if ( object instanceof THREE.Sprite ) {
  14215. scene.__webglSprites.push( object );
  14216. } else if ( object instanceof THREE.LensFlare ) {
  14217. scene.__webglFlares.push( object );
  14218. }
  14219. object.__webglActive = true;
  14220. }
  14221. };
  14222. function addBuffer( objlist, buffer, object ) {
  14223. objlist.push(
  14224. {
  14225. id: null,
  14226. buffer: buffer,
  14227. object: object,
  14228. opaque: null,
  14229. transparent: null,
  14230. z: 0
  14231. }
  14232. );
  14233. };
  14234. function addBufferImmediate( objlist, object ) {
  14235. objlist.push(
  14236. {
  14237. id: null,
  14238. object: object,
  14239. opaque: null,
  14240. transparent: null,
  14241. z: 0
  14242. }
  14243. );
  14244. };
  14245. // Objects updates
  14246. function updateObject( object ) {
  14247. var geometry = object.geometry,
  14248. geometryGroup, customAttributesDirty, material;
  14249. if ( geometry instanceof THREE.BufferGeometry ) {
  14250. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  14251. } else if ( object instanceof THREE.Mesh ) {
  14252. // check all geometry groups
  14253. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14254. geometryGroup = geometry.geometryGroupsList[ i ];
  14255. material = getBufferMaterial( object, geometryGroup );
  14256. if ( geometry.buffersNeedUpdate ) {
  14257. initMeshBuffers( geometryGroup, object );
  14258. }
  14259. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14260. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14261. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14262. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14263. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14264. }
  14265. }
  14266. geometry.verticesNeedUpdate = false;
  14267. geometry.morphTargetsNeedUpdate = false;
  14268. geometry.elementsNeedUpdate = false;
  14269. geometry.uvsNeedUpdate = false;
  14270. geometry.normalsNeedUpdate = false;
  14271. geometry.colorsNeedUpdate = false;
  14272. geometry.tangentsNeedUpdate = false;
  14273. geometry.buffersNeedUpdate = false;
  14274. material.attributes && clearCustomAttributes( material );
  14275. } else if ( object instanceof THREE.Line ) {
  14276. material = getBufferMaterial( object, geometry );
  14277. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14278. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14279. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14280. }
  14281. geometry.verticesNeedUpdate = false;
  14282. geometry.colorsNeedUpdate = false;
  14283. geometry.lineDistancesNeedUpdate = false;
  14284. material.attributes && clearCustomAttributes( material );
  14285. } else if ( object instanceof THREE.ParticleSystem ) {
  14286. material = getBufferMaterial( object, geometry );
  14287. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14288. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14289. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14290. }
  14291. geometry.verticesNeedUpdate = false;
  14292. geometry.colorsNeedUpdate = false;
  14293. material.attributes && clearCustomAttributes( material );
  14294. }
  14295. };
  14296. // Objects updates - custom attributes check
  14297. function areCustomAttributesDirty( material ) {
  14298. for ( var a in material.attributes ) {
  14299. if ( material.attributes[ a ].needsUpdate ) return true;
  14300. }
  14301. return false;
  14302. };
  14303. function clearCustomAttributes( material ) {
  14304. for ( var a in material.attributes ) {
  14305. material.attributes[ a ].needsUpdate = false;
  14306. }
  14307. };
  14308. // Objects removal
  14309. function removeObject( object, scene ) {
  14310. if ( object instanceof THREE.Mesh ||
  14311. object instanceof THREE.ParticleSystem ||
  14312. object instanceof THREE.Line ) {
  14313. removeInstances( scene.__webglObjects, object );
  14314. } else if ( object instanceof THREE.Sprite ) {
  14315. removeInstancesDirect( scene.__webglSprites, object );
  14316. } else if ( object instanceof THREE.LensFlare ) {
  14317. removeInstancesDirect( scene.__webglFlares, object );
  14318. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14319. removeInstances( scene.__webglObjectsImmediate, object );
  14320. }
  14321. delete object.__webglActive;
  14322. };
  14323. function removeInstances( objlist, object ) {
  14324. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14325. if ( objlist[ o ].object === object ) {
  14326. objlist.splice( o, 1 );
  14327. }
  14328. }
  14329. };
  14330. function removeInstancesDirect( objlist, object ) {
  14331. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14332. if ( objlist[ o ] === object ) {
  14333. objlist.splice( o, 1 );
  14334. }
  14335. }
  14336. };
  14337. // Materials
  14338. this.initMaterial = function ( material, lights, fog, object ) {
  14339. material.addEventListener( 'dispose', onMaterialDispose );
  14340. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14341. if ( material instanceof THREE.MeshDepthMaterial ) {
  14342. shaderID = 'depth';
  14343. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14344. shaderID = 'normal';
  14345. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14346. shaderID = 'basic';
  14347. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14348. shaderID = 'lambert';
  14349. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14350. shaderID = 'phong';
  14351. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14352. shaderID = 'basic';
  14353. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14354. shaderID = 'dashed';
  14355. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14356. shaderID = 'particle_basic';
  14357. }
  14358. if ( shaderID ) {
  14359. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14360. }
  14361. // heuristics to create shader parameters according to lights in the scene
  14362. // (not to blow over maxLights budget)
  14363. maxLightCount = allocateLights( lights );
  14364. maxShadows = allocateShadows( lights );
  14365. maxBones = allocateBones( object );
  14366. parameters = {
  14367. precision: _precision,
  14368. supportsVertexTextures: _supportsVertexTextures,
  14369. map: !!material.map,
  14370. envMap: !!material.envMap,
  14371. lightMap: !!material.lightMap,
  14372. bumpMap: !!material.bumpMap,
  14373. normalMap: !!material.normalMap,
  14374. specularMap: !!material.specularMap,
  14375. vertexColors: material.vertexColors,
  14376. fog: fog,
  14377. useFog: material.fog,
  14378. fogExp: fog instanceof THREE.FogExp2,
  14379. sizeAttenuation: material.sizeAttenuation,
  14380. skinning: material.skinning,
  14381. maxBones: maxBones,
  14382. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14383. morphTargets: material.morphTargets,
  14384. morphNormals: material.morphNormals,
  14385. maxMorphTargets: this.maxMorphTargets,
  14386. maxMorphNormals: this.maxMorphNormals,
  14387. maxDirLights: maxLightCount.directional,
  14388. maxPointLights: maxLightCount.point,
  14389. maxSpotLights: maxLightCount.spot,
  14390. maxHemiLights: maxLightCount.hemi,
  14391. maxShadows: maxShadows,
  14392. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  14393. shadowMapType: this.shadowMapType,
  14394. shadowMapDebug: this.shadowMapDebug,
  14395. shadowMapCascade: this.shadowMapCascade,
  14396. alphaTest: material.alphaTest,
  14397. metal: material.metal,
  14398. wrapAround: material.wrapAround,
  14399. doubleSided: material.side === THREE.DoubleSide,
  14400. flipSided: material.side === THREE.BackSide
  14401. };
  14402. // Generate code
  14403. var chunks = [];
  14404. if ( shaderID ) {
  14405. chunks.push( shaderID );
  14406. } else {
  14407. chunks.push( material.fragmentShader );
  14408. chunks.push( material.vertexShader );
  14409. }
  14410. for ( var d in material.defines ) {
  14411. chunks.push( d );
  14412. chunks.push( material.defines[ d ] );
  14413. }
  14414. for ( var p in parameters ) {
  14415. chunks.push( p );
  14416. chunks.push( parameters[ p ] );
  14417. }
  14418. var code = chunks.join();
  14419. var program;
  14420. // Check if code has been already compiled
  14421. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  14422. var programInfo = _programs[ p ];
  14423. if ( programInfo.code === code ) {
  14424. program = programInfo;
  14425. program.usedTimes ++;
  14426. break;
  14427. }
  14428. }
  14429. if ( program === undefined ) {
  14430. program = new THREE.WebGLProgram( this, code, material, parameters );
  14431. _programs.push( program );
  14432. _this.info.memory.programs = _programs.length;
  14433. }
  14434. material.program = program;
  14435. var attributes = material.program.attributes;
  14436. if ( material.morphTargets ) {
  14437. material.numSupportedMorphTargets = 0;
  14438. var id, base = "morphTarget";
  14439. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14440. id = base + i;
  14441. if ( attributes[ id ] >= 0 ) {
  14442. material.numSupportedMorphTargets ++;
  14443. }
  14444. }
  14445. }
  14446. if ( material.morphNormals ) {
  14447. material.numSupportedMorphNormals = 0;
  14448. var id, base = "morphNormal";
  14449. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14450. id = base + i;
  14451. if ( attributes[ id ] >= 0 ) {
  14452. material.numSupportedMorphNormals ++;
  14453. }
  14454. }
  14455. }
  14456. material.uniformsList = [];
  14457. for ( u in material.uniforms ) {
  14458. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14459. }
  14460. };
  14461. function setMaterialShaders( material, shaders ) {
  14462. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14463. material.vertexShader = shaders.vertexShader;
  14464. material.fragmentShader = shaders.fragmentShader;
  14465. };
  14466. function setProgram( camera, lights, fog, material, object ) {
  14467. _usedTextureUnits = 0;
  14468. if ( material.needsUpdate ) {
  14469. if ( material.program ) deallocateMaterial( material );
  14470. _this.initMaterial( material, lights, fog, object );
  14471. material.needsUpdate = false;
  14472. }
  14473. if ( material.morphTargets ) {
  14474. if ( ! object.__webglMorphTargetInfluences ) {
  14475. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14476. }
  14477. }
  14478. var refreshMaterial = false;
  14479. var program = material.program,
  14480. p_uniforms = program.uniforms,
  14481. m_uniforms = material.uniforms;
  14482. if ( program.id !== _currentProgram ) {
  14483. _gl.useProgram( program.program );
  14484. _currentProgram = program.id;
  14485. refreshMaterial = true;
  14486. }
  14487. if ( material.id !== _currentMaterialId ) {
  14488. _currentMaterialId = material.id;
  14489. refreshMaterial = true;
  14490. }
  14491. if ( refreshMaterial || camera !== _currentCamera ) {
  14492. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14493. if ( camera !== _currentCamera ) _currentCamera = camera;
  14494. }
  14495. // skinning uniforms must be set even if material didn't change
  14496. // auto-setting of texture unit for bone texture must go before other textures
  14497. // not sure why, but otherwise weird things happen
  14498. if ( material.skinning ) {
  14499. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14500. if ( p_uniforms.boneTexture !== null ) {
  14501. var textureUnit = getTextureUnit();
  14502. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14503. _this.setTexture( object.boneTexture, textureUnit );
  14504. }
  14505. if ( p_uniforms.boneTextureWidth !== null ) {
  14506. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14507. }
  14508. if ( p_uniforms.boneTextureHeight !== null ) {
  14509. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14510. }
  14511. } else {
  14512. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14513. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14514. }
  14515. }
  14516. }
  14517. if ( refreshMaterial ) {
  14518. // refresh uniforms common to several materials
  14519. if ( fog && material.fog ) {
  14520. refreshUniformsFog( m_uniforms, fog );
  14521. }
  14522. if ( material instanceof THREE.MeshPhongMaterial ||
  14523. material instanceof THREE.MeshLambertMaterial ||
  14524. material.lights ) {
  14525. if ( _lightsNeedUpdate ) {
  14526. setupLights( program, lights );
  14527. _lightsNeedUpdate = false;
  14528. }
  14529. refreshUniformsLights( m_uniforms, _lights );
  14530. }
  14531. if ( material instanceof THREE.MeshBasicMaterial ||
  14532. material instanceof THREE.MeshLambertMaterial ||
  14533. material instanceof THREE.MeshPhongMaterial ) {
  14534. refreshUniformsCommon( m_uniforms, material );
  14535. }
  14536. // refresh single material specific uniforms
  14537. if ( material instanceof THREE.LineBasicMaterial ) {
  14538. refreshUniformsLine( m_uniforms, material );
  14539. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14540. refreshUniformsLine( m_uniforms, material );
  14541. refreshUniformsDash( m_uniforms, material );
  14542. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14543. refreshUniformsParticle( m_uniforms, material );
  14544. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14545. refreshUniformsPhong( m_uniforms, material );
  14546. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14547. refreshUniformsLambert( m_uniforms, material );
  14548. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14549. m_uniforms.mNear.value = camera.near;
  14550. m_uniforms.mFar.value = camera.far;
  14551. m_uniforms.opacity.value = material.opacity;
  14552. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14553. m_uniforms.opacity.value = material.opacity;
  14554. }
  14555. if ( object.receiveShadow && ! material._shadowPass ) {
  14556. refreshUniformsShadow( m_uniforms, lights );
  14557. }
  14558. // load common uniforms
  14559. loadUniformsGeneric( program, material.uniformsList );
  14560. // load material specific uniforms
  14561. // (shader material also gets them for the sake of genericity)
  14562. if ( material instanceof THREE.ShaderMaterial ||
  14563. material instanceof THREE.MeshPhongMaterial ||
  14564. material.envMap ) {
  14565. if ( p_uniforms.cameraPosition !== null ) {
  14566. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14567. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14568. }
  14569. }
  14570. if ( material instanceof THREE.MeshPhongMaterial ||
  14571. material instanceof THREE.MeshLambertMaterial ||
  14572. material instanceof THREE.ShaderMaterial ||
  14573. material.skinning ) {
  14574. if ( p_uniforms.viewMatrix !== null ) {
  14575. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14576. }
  14577. }
  14578. }
  14579. loadUniformsMatrices( p_uniforms, object );
  14580. if ( p_uniforms.modelMatrix !== null ) {
  14581. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14582. }
  14583. return program;
  14584. };
  14585. // Uniforms (refresh uniforms objects)
  14586. function refreshUniformsCommon ( uniforms, material ) {
  14587. uniforms.opacity.value = material.opacity;
  14588. if ( _this.gammaInput ) {
  14589. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14590. } else {
  14591. uniforms.diffuse.value = material.color;
  14592. }
  14593. uniforms.map.value = material.map;
  14594. uniforms.lightMap.value = material.lightMap;
  14595. uniforms.specularMap.value = material.specularMap;
  14596. if ( material.bumpMap ) {
  14597. uniforms.bumpMap.value = material.bumpMap;
  14598. uniforms.bumpScale.value = material.bumpScale;
  14599. }
  14600. if ( material.normalMap ) {
  14601. uniforms.normalMap.value = material.normalMap;
  14602. uniforms.normalScale.value.copy( material.normalScale );
  14603. }
  14604. // uv repeat and offset setting priorities
  14605. // 1. color map
  14606. // 2. specular map
  14607. // 3. normal map
  14608. // 4. bump map
  14609. var uvScaleMap;
  14610. if ( material.map ) {
  14611. uvScaleMap = material.map;
  14612. } else if ( material.specularMap ) {
  14613. uvScaleMap = material.specularMap;
  14614. } else if ( material.normalMap ) {
  14615. uvScaleMap = material.normalMap;
  14616. } else if ( material.bumpMap ) {
  14617. uvScaleMap = material.bumpMap;
  14618. }
  14619. if ( uvScaleMap !== undefined ) {
  14620. var offset = uvScaleMap.offset;
  14621. var repeat = uvScaleMap.repeat;
  14622. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14623. }
  14624. uniforms.envMap.value = material.envMap;
  14625. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14626. if ( _this.gammaInput ) {
  14627. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14628. uniforms.reflectivity.value = material.reflectivity;
  14629. } else {
  14630. uniforms.reflectivity.value = material.reflectivity;
  14631. }
  14632. uniforms.refractionRatio.value = material.refractionRatio;
  14633. uniforms.combine.value = material.combine;
  14634. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14635. };
  14636. function refreshUniformsLine ( uniforms, material ) {
  14637. uniforms.diffuse.value = material.color;
  14638. uniforms.opacity.value = material.opacity;
  14639. };
  14640. function refreshUniformsDash ( uniforms, material ) {
  14641. uniforms.dashSize.value = material.dashSize;
  14642. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14643. uniforms.scale.value = material.scale;
  14644. };
  14645. function refreshUniformsParticle ( uniforms, material ) {
  14646. uniforms.psColor.value = material.color;
  14647. uniforms.opacity.value = material.opacity;
  14648. uniforms.size.value = material.size;
  14649. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14650. uniforms.map.value = material.map;
  14651. };
  14652. function refreshUniformsFog ( uniforms, fog ) {
  14653. uniforms.fogColor.value = fog.color;
  14654. if ( fog instanceof THREE.Fog ) {
  14655. uniforms.fogNear.value = fog.near;
  14656. uniforms.fogFar.value = fog.far;
  14657. } else if ( fog instanceof THREE.FogExp2 ) {
  14658. uniforms.fogDensity.value = fog.density;
  14659. }
  14660. };
  14661. function refreshUniformsPhong ( uniforms, material ) {
  14662. uniforms.shininess.value = material.shininess;
  14663. if ( _this.gammaInput ) {
  14664. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14665. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14666. uniforms.specular.value.copyGammaToLinear( material.specular );
  14667. } else {
  14668. uniforms.ambient.value = material.ambient;
  14669. uniforms.emissive.value = material.emissive;
  14670. uniforms.specular.value = material.specular;
  14671. }
  14672. if ( material.wrapAround ) {
  14673. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14674. }
  14675. };
  14676. function refreshUniformsLambert ( uniforms, material ) {
  14677. if ( _this.gammaInput ) {
  14678. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14679. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14680. } else {
  14681. uniforms.ambient.value = material.ambient;
  14682. uniforms.emissive.value = material.emissive;
  14683. }
  14684. if ( material.wrapAround ) {
  14685. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14686. }
  14687. };
  14688. function refreshUniformsLights ( uniforms, lights ) {
  14689. uniforms.ambientLightColor.value = lights.ambient;
  14690. uniforms.directionalLightColor.value = lights.directional.colors;
  14691. uniforms.directionalLightDirection.value = lights.directional.positions;
  14692. uniforms.pointLightColor.value = lights.point.colors;
  14693. uniforms.pointLightPosition.value = lights.point.positions;
  14694. uniforms.pointLightDistance.value = lights.point.distances;
  14695. uniforms.spotLightColor.value = lights.spot.colors;
  14696. uniforms.spotLightPosition.value = lights.spot.positions;
  14697. uniforms.spotLightDistance.value = lights.spot.distances;
  14698. uniforms.spotLightDirection.value = lights.spot.directions;
  14699. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14700. uniforms.spotLightExponent.value = lights.spot.exponents;
  14701. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14702. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14703. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14704. };
  14705. function refreshUniformsShadow ( uniforms, lights ) {
  14706. if ( uniforms.shadowMatrix ) {
  14707. var j = 0;
  14708. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14709. var light = lights[ i ];
  14710. if ( ! light.castShadow ) continue;
  14711. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14712. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14713. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14714. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14715. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14716. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14717. j ++;
  14718. }
  14719. }
  14720. }
  14721. };
  14722. // Uniforms (load to GPU)
  14723. function loadUniformsMatrices ( uniforms, object ) {
  14724. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14725. if ( uniforms.normalMatrix ) {
  14726. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14727. }
  14728. };
  14729. function getTextureUnit() {
  14730. var textureUnit = _usedTextureUnits;
  14731. if ( textureUnit >= _maxTextures ) {
  14732. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14733. }
  14734. _usedTextureUnits += 1;
  14735. return textureUnit;
  14736. };
  14737. function loadUniformsGeneric ( program, uniforms ) {
  14738. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14739. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14740. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14741. if ( !location ) continue;
  14742. uniform = uniforms[ j ][ 0 ];
  14743. type = uniform.type;
  14744. value = uniform.value;
  14745. if ( type === "i" ) { // single integer
  14746. _gl.uniform1i( location, value );
  14747. } else if ( type === "f" ) { // single float
  14748. _gl.uniform1f( location, value );
  14749. } else if ( type === "v2" ) { // single THREE.Vector2
  14750. _gl.uniform2f( location, value.x, value.y );
  14751. } else if ( type === "v3" ) { // single THREE.Vector3
  14752. _gl.uniform3f( location, value.x, value.y, value.z );
  14753. } else if ( type === "v4" ) { // single THREE.Vector4
  14754. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14755. } else if ( type === "c" ) { // single THREE.Color
  14756. _gl.uniform3f( location, value.r, value.g, value.b );
  14757. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14758. _gl.uniform1iv( location, value );
  14759. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14760. _gl.uniform3iv( location, value );
  14761. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14762. _gl.uniform1fv( location, value );
  14763. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14764. _gl.uniform3fv( location, value );
  14765. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14766. if ( uniform._array === undefined ) {
  14767. uniform._array = new Float32Array( 2 * value.length );
  14768. }
  14769. for ( i = 0, il = value.length; i < il; i ++ ) {
  14770. offset = i * 2;
  14771. uniform._array[ offset ] = value[ i ].x;
  14772. uniform._array[ offset + 1 ] = value[ i ].y;
  14773. }
  14774. _gl.uniform2fv( location, uniform._array );
  14775. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14776. if ( uniform._array === undefined ) {
  14777. uniform._array = new Float32Array( 3 * value.length );
  14778. }
  14779. for ( i = 0, il = value.length; i < il; i ++ ) {
  14780. offset = i * 3;
  14781. uniform._array[ offset ] = value[ i ].x;
  14782. uniform._array[ offset + 1 ] = value[ i ].y;
  14783. uniform._array[ offset + 2 ] = value[ i ].z;
  14784. }
  14785. _gl.uniform3fv( location, uniform._array );
  14786. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14787. if ( uniform._array === undefined ) {
  14788. uniform._array = new Float32Array( 4 * value.length );
  14789. }
  14790. for ( i = 0, il = value.length; i < il; i ++ ) {
  14791. offset = i * 4;
  14792. uniform._array[ offset ] = value[ i ].x;
  14793. uniform._array[ offset + 1 ] = value[ i ].y;
  14794. uniform._array[ offset + 2 ] = value[ i ].z;
  14795. uniform._array[ offset + 3 ] = value[ i ].w;
  14796. }
  14797. _gl.uniform4fv( location, uniform._array );
  14798. } else if ( type === "m4") { // single THREE.Matrix4
  14799. if ( uniform._array === undefined ) {
  14800. uniform._array = new Float32Array( 16 );
  14801. }
  14802. value.flattenToArray( uniform._array );
  14803. _gl.uniformMatrix4fv( location, false, uniform._array );
  14804. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14805. if ( uniform._array === undefined ) {
  14806. uniform._array = new Float32Array( 16 * value.length );
  14807. }
  14808. for ( i = 0, il = value.length; i < il; i ++ ) {
  14809. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14810. }
  14811. _gl.uniformMatrix4fv( location, false, uniform._array );
  14812. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14813. texture = value;
  14814. textureUnit = getTextureUnit();
  14815. _gl.uniform1i( location, textureUnit );
  14816. if ( !texture ) continue;
  14817. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14818. setCubeTexture( texture, textureUnit );
  14819. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14820. setCubeTextureDynamic( texture, textureUnit );
  14821. } else {
  14822. _this.setTexture( texture, textureUnit );
  14823. }
  14824. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14825. if ( uniform._array === undefined ) {
  14826. uniform._array = [];
  14827. }
  14828. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14829. uniform._array[ i ] = getTextureUnit();
  14830. }
  14831. _gl.uniform1iv( location, uniform._array );
  14832. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14833. texture = uniform.value[ i ];
  14834. textureUnit = uniform._array[ i ];
  14835. if ( !texture ) continue;
  14836. _this.setTexture( texture, textureUnit );
  14837. }
  14838. } else {
  14839. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14840. }
  14841. }
  14842. };
  14843. function setupMatrices ( object, camera ) {
  14844. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14845. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14846. };
  14847. //
  14848. function setColorGamma( array, offset, color, intensitySq ) {
  14849. array[ offset ] = color.r * color.r * intensitySq;
  14850. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14851. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14852. };
  14853. function setColorLinear( array, offset, color, intensity ) {
  14854. array[ offset ] = color.r * intensity;
  14855. array[ offset + 1 ] = color.g * intensity;
  14856. array[ offset + 2 ] = color.b * intensity;
  14857. };
  14858. function setupLights ( program, lights ) {
  14859. var l, ll, light, n,
  14860. r = 0, g = 0, b = 0,
  14861. color, skyColor, groundColor,
  14862. intensity, intensitySq,
  14863. position,
  14864. distance,
  14865. zlights = _lights,
  14866. dirColors = zlights.directional.colors,
  14867. dirPositions = zlights.directional.positions,
  14868. pointColors = zlights.point.colors,
  14869. pointPositions = zlights.point.positions,
  14870. pointDistances = zlights.point.distances,
  14871. spotColors = zlights.spot.colors,
  14872. spotPositions = zlights.spot.positions,
  14873. spotDistances = zlights.spot.distances,
  14874. spotDirections = zlights.spot.directions,
  14875. spotAnglesCos = zlights.spot.anglesCos,
  14876. spotExponents = zlights.spot.exponents,
  14877. hemiSkyColors = zlights.hemi.skyColors,
  14878. hemiGroundColors = zlights.hemi.groundColors,
  14879. hemiPositions = zlights.hemi.positions,
  14880. dirLength = 0,
  14881. pointLength = 0,
  14882. spotLength = 0,
  14883. hemiLength = 0,
  14884. dirCount = 0,
  14885. pointCount = 0,
  14886. spotCount = 0,
  14887. hemiCount = 0,
  14888. dirOffset = 0,
  14889. pointOffset = 0,
  14890. spotOffset = 0,
  14891. hemiOffset = 0;
  14892. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14893. light = lights[ l ];
  14894. if ( light.onlyShadow ) continue;
  14895. color = light.color;
  14896. intensity = light.intensity;
  14897. distance = light.distance;
  14898. if ( light instanceof THREE.AmbientLight ) {
  14899. if ( ! light.visible ) continue;
  14900. if ( _this.gammaInput ) {
  14901. r += color.r * color.r;
  14902. g += color.g * color.g;
  14903. b += color.b * color.b;
  14904. } else {
  14905. r += color.r;
  14906. g += color.g;
  14907. b += color.b;
  14908. }
  14909. } else if ( light instanceof THREE.DirectionalLight ) {
  14910. dirCount += 1;
  14911. if ( ! light.visible ) continue;
  14912. _direction.setFromMatrixPosition( light.matrixWorld );
  14913. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14914. _direction.sub( _vector3 );
  14915. _direction.normalize();
  14916. // skip lights with undefined direction
  14917. // these create troubles in OpenGL (making pixel black)
  14918. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14919. dirOffset = dirLength * 3;
  14920. dirPositions[ dirOffset ] = _direction.x;
  14921. dirPositions[ dirOffset + 1 ] = _direction.y;
  14922. dirPositions[ dirOffset + 2 ] = _direction.z;
  14923. if ( _this.gammaInput ) {
  14924. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14925. } else {
  14926. setColorLinear( dirColors, dirOffset, color, intensity );
  14927. }
  14928. dirLength += 1;
  14929. } else if ( light instanceof THREE.PointLight ) {
  14930. pointCount += 1;
  14931. if ( ! light.visible ) continue;
  14932. pointOffset = pointLength * 3;
  14933. if ( _this.gammaInput ) {
  14934. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14935. } else {
  14936. setColorLinear( pointColors, pointOffset, color, intensity );
  14937. }
  14938. _vector3.setFromMatrixPosition( light.matrixWorld );
  14939. pointPositions[ pointOffset ] = _vector3.x;
  14940. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14941. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14942. pointDistances[ pointLength ] = distance;
  14943. pointLength += 1;
  14944. } else if ( light instanceof THREE.SpotLight ) {
  14945. spotCount += 1;
  14946. if ( ! light.visible ) continue;
  14947. spotOffset = spotLength * 3;
  14948. if ( _this.gammaInput ) {
  14949. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14950. } else {
  14951. setColorLinear( spotColors, spotOffset, color, intensity );
  14952. }
  14953. _vector3.setFromMatrixPosition( light.matrixWorld );
  14954. spotPositions[ spotOffset ] = _vector3.x;
  14955. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14956. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14957. spotDistances[ spotLength ] = distance;
  14958. _direction.copy( _vector3 );
  14959. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14960. _direction.sub( _vector3 );
  14961. _direction.normalize();
  14962. spotDirections[ spotOffset ] = _direction.x;
  14963. spotDirections[ spotOffset + 1 ] = _direction.y;
  14964. spotDirections[ spotOffset + 2 ] = _direction.z;
  14965. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14966. spotExponents[ spotLength ] = light.exponent;
  14967. spotLength += 1;
  14968. } else if ( light instanceof THREE.HemisphereLight ) {
  14969. hemiCount += 1;
  14970. if ( ! light.visible ) continue;
  14971. _direction.setFromMatrixPosition( light.matrixWorld );
  14972. _direction.normalize();
  14973. // skip lights with undefined direction
  14974. // these create troubles in OpenGL (making pixel black)
  14975. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14976. hemiOffset = hemiLength * 3;
  14977. hemiPositions[ hemiOffset ] = _direction.x;
  14978. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14979. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14980. skyColor = light.color;
  14981. groundColor = light.groundColor;
  14982. if ( _this.gammaInput ) {
  14983. intensitySq = intensity * intensity;
  14984. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14985. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14986. } else {
  14987. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14988. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14989. }
  14990. hemiLength += 1;
  14991. }
  14992. }
  14993. // null eventual remains from removed lights
  14994. // (this is to avoid if in shader)
  14995. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14996. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14997. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14998. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14999. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  15000. zlights.directional.length = dirLength;
  15001. zlights.point.length = pointLength;
  15002. zlights.spot.length = spotLength;
  15003. zlights.hemi.length = hemiLength;
  15004. zlights.ambient[ 0 ] = r;
  15005. zlights.ambient[ 1 ] = g;
  15006. zlights.ambient[ 2 ] = b;
  15007. };
  15008. // GL state setting
  15009. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15010. if ( cullFace === THREE.CullFaceNone ) {
  15011. _gl.disable( _gl.CULL_FACE );
  15012. } else {
  15013. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  15014. _gl.frontFace( _gl.CW );
  15015. } else {
  15016. _gl.frontFace( _gl.CCW );
  15017. }
  15018. if ( cullFace === THREE.CullFaceBack ) {
  15019. _gl.cullFace( _gl.BACK );
  15020. } else if ( cullFace === THREE.CullFaceFront ) {
  15021. _gl.cullFace( _gl.FRONT );
  15022. } else {
  15023. _gl.cullFace( _gl.FRONT_AND_BACK );
  15024. }
  15025. _gl.enable( _gl.CULL_FACE );
  15026. }
  15027. };
  15028. this.setMaterialFaces = function ( material ) {
  15029. var doubleSided = material.side === THREE.DoubleSide;
  15030. var flipSided = material.side === THREE.BackSide;
  15031. if ( _oldDoubleSided !== doubleSided ) {
  15032. if ( doubleSided ) {
  15033. _gl.disable( _gl.CULL_FACE );
  15034. } else {
  15035. _gl.enable( _gl.CULL_FACE );
  15036. }
  15037. _oldDoubleSided = doubleSided;
  15038. }
  15039. if ( _oldFlipSided !== flipSided ) {
  15040. if ( flipSided ) {
  15041. _gl.frontFace( _gl.CW );
  15042. } else {
  15043. _gl.frontFace( _gl.CCW );
  15044. }
  15045. _oldFlipSided = flipSided;
  15046. }
  15047. };
  15048. this.setDepthTest = function ( depthTest ) {
  15049. if ( _oldDepthTest !== depthTest ) {
  15050. if ( depthTest ) {
  15051. _gl.enable( _gl.DEPTH_TEST );
  15052. } else {
  15053. _gl.disable( _gl.DEPTH_TEST );
  15054. }
  15055. _oldDepthTest = depthTest;
  15056. }
  15057. };
  15058. this.setDepthWrite = function ( depthWrite ) {
  15059. if ( _oldDepthWrite !== depthWrite ) {
  15060. _gl.depthMask( depthWrite );
  15061. _oldDepthWrite = depthWrite;
  15062. }
  15063. };
  15064. function setLineWidth ( width ) {
  15065. if ( width !== _oldLineWidth ) {
  15066. _gl.lineWidth( width );
  15067. _oldLineWidth = width;
  15068. }
  15069. };
  15070. function setPolygonOffset ( polygonoffset, factor, units ) {
  15071. if ( _oldPolygonOffset !== polygonoffset ) {
  15072. if ( polygonoffset ) {
  15073. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15074. } else {
  15075. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15076. }
  15077. _oldPolygonOffset = polygonoffset;
  15078. }
  15079. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15080. _gl.polygonOffset( factor, units );
  15081. _oldPolygonOffsetFactor = factor;
  15082. _oldPolygonOffsetUnits = units;
  15083. }
  15084. };
  15085. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15086. if ( blending !== _oldBlending ) {
  15087. if ( blending === THREE.NoBlending ) {
  15088. _gl.disable( _gl.BLEND );
  15089. } else if ( blending === THREE.AdditiveBlending ) {
  15090. _gl.enable( _gl.BLEND );
  15091. _gl.blendEquation( _gl.FUNC_ADD );
  15092. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15093. } else if ( blending === THREE.SubtractiveBlending ) {
  15094. // TODO: Find blendFuncSeparate() combination
  15095. _gl.enable( _gl.BLEND );
  15096. _gl.blendEquation( _gl.FUNC_ADD );
  15097. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15098. } else if ( blending === THREE.MultiplyBlending ) {
  15099. // TODO: Find blendFuncSeparate() combination
  15100. _gl.enable( _gl.BLEND );
  15101. _gl.blendEquation( _gl.FUNC_ADD );
  15102. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15103. } else if ( blending === THREE.CustomBlending ) {
  15104. _gl.enable( _gl.BLEND );
  15105. } else {
  15106. _gl.enable( _gl.BLEND );
  15107. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15108. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15109. }
  15110. _oldBlending = blending;
  15111. }
  15112. if ( blending === THREE.CustomBlending ) {
  15113. if ( blendEquation !== _oldBlendEquation ) {
  15114. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15115. _oldBlendEquation = blendEquation;
  15116. }
  15117. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15118. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15119. _oldBlendSrc = blendSrc;
  15120. _oldBlendDst = blendDst;
  15121. }
  15122. } else {
  15123. _oldBlendEquation = null;
  15124. _oldBlendSrc = null;
  15125. _oldBlendDst = null;
  15126. }
  15127. };
  15128. // Textures
  15129. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15130. if ( isImagePowerOfTwo ) {
  15131. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15132. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15133. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15134. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15135. } else {
  15136. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15137. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15138. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15139. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15140. }
  15141. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15142. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15143. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15144. texture.__oldAnisotropy = texture.anisotropy;
  15145. }
  15146. }
  15147. };
  15148. this.setTexture = function ( texture, slot ) {
  15149. if ( texture.needsUpdate ) {
  15150. if ( ! texture.__webglInit ) {
  15151. texture.__webglInit = true;
  15152. texture.addEventListener( 'dispose', onTextureDispose );
  15153. texture.__webglTexture = _gl.createTexture();
  15154. _this.info.memory.textures ++;
  15155. }
  15156. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15157. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15158. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15159. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15160. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15161. var image = texture.image,
  15162. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15163. glFormat = paramThreeToGL( texture.format ),
  15164. glType = paramThreeToGL( texture.type );
  15165. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15166. var mipmap, mipmaps = texture.mipmaps;
  15167. if ( texture instanceof THREE.DataTexture ) {
  15168. // use manually created mipmaps if available
  15169. // if there are no manual mipmaps
  15170. // set 0 level mipmap and then use GL to generate other mipmap levels
  15171. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15172. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15173. mipmap = mipmaps[ i ];
  15174. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15175. }
  15176. texture.generateMipmaps = false;
  15177. } else {
  15178. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15179. }
  15180. } else if ( texture instanceof THREE.CompressedTexture ) {
  15181. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15182. mipmap = mipmaps[ i ];
  15183. if ( texture.format!==THREE.RGBAFormat ) {
  15184. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15185. } else {
  15186. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15187. }
  15188. }
  15189. } else { // regular Texture (image, video, canvas)
  15190. // use manually created mipmaps if available
  15191. // if there are no manual mipmaps
  15192. // set 0 level mipmap and then use GL to generate other mipmap levels
  15193. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15194. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15195. mipmap = mipmaps[ i ];
  15196. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15197. }
  15198. texture.generateMipmaps = false;
  15199. } else {
  15200. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15201. }
  15202. }
  15203. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15204. texture.needsUpdate = false;
  15205. if ( texture.onUpdate ) texture.onUpdate();
  15206. } else {
  15207. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15208. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15209. }
  15210. };
  15211. function clampToMaxSize ( image, maxSize ) {
  15212. if ( image.width <= maxSize && image.height <= maxSize ) {
  15213. return image;
  15214. }
  15215. // Warning: Scaling through the canvas will only work with images that use
  15216. // premultiplied alpha.
  15217. var maxDimension = Math.max( image.width, image.height );
  15218. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15219. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15220. var canvas = document.createElement( 'canvas' );
  15221. canvas.width = newWidth;
  15222. canvas.height = newHeight;
  15223. var ctx = canvas.getContext( "2d" );
  15224. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15225. return canvas;
  15226. }
  15227. function setCubeTexture ( texture, slot ) {
  15228. if ( texture.image.length === 6 ) {
  15229. if ( texture.needsUpdate ) {
  15230. if ( ! texture.image.__webglTextureCube ) {
  15231. texture.addEventListener( 'dispose', onTextureDispose );
  15232. texture.image.__webglTextureCube = _gl.createTexture();
  15233. _this.info.memory.textures ++;
  15234. }
  15235. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15236. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15237. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15238. var isCompressed = texture instanceof THREE.CompressedTexture;
  15239. var cubeImage = [];
  15240. for ( var i = 0; i < 6; i ++ ) {
  15241. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15242. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15243. } else {
  15244. cubeImage[ i ] = texture.image[ i ];
  15245. }
  15246. }
  15247. var image = cubeImage[ 0 ],
  15248. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15249. glFormat = paramThreeToGL( texture.format ),
  15250. glType = paramThreeToGL( texture.type );
  15251. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15252. for ( var i = 0; i < 6; i ++ ) {
  15253. if( !isCompressed ) {
  15254. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15255. } else {
  15256. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15257. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15258. mipmap = mipmaps[ j ];
  15259. if ( texture.format!==THREE.RGBAFormat ) {
  15260. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15261. } else {
  15262. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15263. }
  15264. }
  15265. }
  15266. }
  15267. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15268. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15269. }
  15270. texture.needsUpdate = false;
  15271. if ( texture.onUpdate ) texture.onUpdate();
  15272. } else {
  15273. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15274. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15275. }
  15276. }
  15277. };
  15278. function setCubeTextureDynamic ( texture, slot ) {
  15279. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15280. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15281. };
  15282. // Render targets
  15283. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15284. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15285. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15286. };
  15287. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15288. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15289. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15290. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15291. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15292. /* For some reason this is not working. Defaulting to RGBA4.
  15293. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15294. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15295. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15296. */
  15297. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15298. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15299. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15300. } else {
  15301. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15302. }
  15303. };
  15304. this.setRenderTarget = function ( renderTarget ) {
  15305. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15306. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15307. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15308. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15309. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15310. renderTarget.__webglTexture = _gl.createTexture();
  15311. _this.info.memory.textures ++;
  15312. // Setup texture, create render and frame buffers
  15313. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15314. glFormat = paramThreeToGL( renderTarget.format ),
  15315. glType = paramThreeToGL( renderTarget.type );
  15316. if ( isCube ) {
  15317. renderTarget.__webglFramebuffer = [];
  15318. renderTarget.__webglRenderbuffer = [];
  15319. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15320. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15321. for ( var i = 0; i < 6; i ++ ) {
  15322. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15323. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15324. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15325. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15326. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15327. }
  15328. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15329. } else {
  15330. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15331. if ( renderTarget.shareDepthFrom ) {
  15332. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15333. } else {
  15334. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15335. }
  15336. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15337. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15338. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15339. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15340. if ( renderTarget.shareDepthFrom ) {
  15341. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15342. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15343. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15344. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15345. }
  15346. } else {
  15347. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15348. }
  15349. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15350. }
  15351. // Release everything
  15352. if ( isCube ) {
  15353. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15354. } else {
  15355. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15356. }
  15357. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15358. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15359. }
  15360. var framebuffer, width, height, vx, vy;
  15361. if ( renderTarget ) {
  15362. if ( isCube ) {
  15363. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15364. } else {
  15365. framebuffer = renderTarget.__webglFramebuffer;
  15366. }
  15367. width = renderTarget.width;
  15368. height = renderTarget.height;
  15369. vx = 0;
  15370. vy = 0;
  15371. } else {
  15372. framebuffer = null;
  15373. width = _viewportWidth;
  15374. height = _viewportHeight;
  15375. vx = _viewportX;
  15376. vy = _viewportY;
  15377. }
  15378. if ( framebuffer !== _currentFramebuffer ) {
  15379. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15380. _gl.viewport( vx, vy, width, height );
  15381. _currentFramebuffer = framebuffer;
  15382. }
  15383. _currentWidth = width;
  15384. _currentHeight = height;
  15385. };
  15386. function updateRenderTargetMipmap ( renderTarget ) {
  15387. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15388. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15389. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15390. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15391. } else {
  15392. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15393. _gl.generateMipmap( _gl.TEXTURE_2D );
  15394. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15395. }
  15396. };
  15397. // Fallback filters for non-power-of-2 textures
  15398. function filterFallback ( f ) {
  15399. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15400. return _gl.NEAREST;
  15401. }
  15402. return _gl.LINEAR;
  15403. };
  15404. // Map three.js constants to WebGL constants
  15405. function paramThreeToGL ( p ) {
  15406. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15407. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15408. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15409. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15410. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15411. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15412. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15413. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15414. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15415. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15416. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15417. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15418. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15419. if ( p === THREE.ByteType ) return _gl.BYTE;
  15420. if ( p === THREE.ShortType ) return _gl.SHORT;
  15421. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15422. if ( p === THREE.IntType ) return _gl.INT;
  15423. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15424. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15425. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15426. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15427. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15428. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15429. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15430. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15431. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15432. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15433. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15434. if ( p === THREE.OneFactor ) return _gl.ONE;
  15435. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15436. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15437. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15438. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15439. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15440. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15441. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15442. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15443. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15444. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15445. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15446. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15447. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15448. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15449. }
  15450. return 0;
  15451. };
  15452. // Allocations
  15453. function allocateBones ( object ) {
  15454. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15455. return 1024;
  15456. } else {
  15457. // default for when object is not specified
  15458. // ( for example when prebuilding shader
  15459. // to be used with multiple objects )
  15460. //
  15461. // - leave some extra space for other uniforms
  15462. // - limit here is ANGLE's 254 max uniform vectors
  15463. // (up to 54 should be safe)
  15464. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15465. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15466. var maxBones = nVertexMatrices;
  15467. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15468. maxBones = Math.min( object.bones.length, maxBones );
  15469. if ( maxBones < object.bones.length ) {
  15470. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15471. }
  15472. }
  15473. return maxBones;
  15474. }
  15475. };
  15476. function allocateLights( lights ) {
  15477. var dirLights = 0;
  15478. var pointLights = 0;
  15479. var spotLights = 0;
  15480. var hemiLights = 0;
  15481. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15482. var light = lights[ l ];
  15483. if ( light.onlyShadow || light.visible === false ) continue;
  15484. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15485. if ( light instanceof THREE.PointLight ) pointLights ++;
  15486. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15487. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15488. }
  15489. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15490. };
  15491. function allocateShadows( lights ) {
  15492. var maxShadows = 0;
  15493. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15494. var light = lights[ l ];
  15495. if ( ! light.castShadow ) continue;
  15496. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15497. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15498. }
  15499. return maxShadows;
  15500. };
  15501. // Initialization
  15502. function initGL() {
  15503. try {
  15504. var attributes = {
  15505. alpha: _alpha,
  15506. depth: _depth,
  15507. stencil: _stencil,
  15508. antialias: _antialias,
  15509. premultipliedAlpha: _premultipliedAlpha,
  15510. preserveDrawingBuffer: _preserveDrawingBuffer
  15511. };
  15512. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15513. if ( _gl === null ) {
  15514. throw 'Error creating WebGL context.';
  15515. }
  15516. } catch ( error ) {
  15517. console.error( error );
  15518. }
  15519. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15520. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15521. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15522. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15523. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15524. _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' );
  15525. if ( _glExtensionTextureFloat === null ) {
  15526. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15527. }
  15528. if ( _glExtensionStandardDerivatives === null ) {
  15529. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15530. }
  15531. if ( _glExtensionTextureFilterAnisotropic === null ) {
  15532. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15533. }
  15534. if ( _glExtensionCompressedTextureS3TC === null ) {
  15535. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15536. }
  15537. if ( _glExtensionElementIndexUint === null ) {
  15538. console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' );
  15539. }
  15540. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15541. _gl.getShaderPrecisionFormat = function() {
  15542. return {
  15543. "rangeMin" : 1,
  15544. "rangeMax" : 1,
  15545. "precision" : 1
  15546. };
  15547. }
  15548. }
  15549. };
  15550. function setDefaultGLState () {
  15551. _gl.clearColor( 0, 0, 0, 1 );
  15552. _gl.clearDepth( 1 );
  15553. _gl.clearStencil( 0 );
  15554. _gl.enable( _gl.DEPTH_TEST );
  15555. _gl.depthFunc( _gl.LEQUAL );
  15556. _gl.frontFace( _gl.CCW );
  15557. _gl.cullFace( _gl.BACK );
  15558. _gl.enable( _gl.CULL_FACE );
  15559. _gl.enable( _gl.BLEND );
  15560. _gl.blendEquation( _gl.FUNC_ADD );
  15561. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15562. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15563. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15564. };
  15565. // default plugins (order is important)
  15566. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15567. this.addPrePlugin( this.shadowMapPlugin );
  15568. this.addPostPlugin( new THREE.SpritePlugin() );
  15569. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15570. };
  15571. /**
  15572. * @author szimek / https://github.com/szimek/
  15573. * @author alteredq / http://alteredqualia.com/
  15574. */
  15575. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15576. this.width = width;
  15577. this.height = height;
  15578. options = options || {};
  15579. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15580. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15581. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15582. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15583. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15584. this.offset = new THREE.Vector2( 0, 0 );
  15585. this.repeat = new THREE.Vector2( 1, 1 );
  15586. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15587. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15588. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15589. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15590. this.generateMipmaps = true;
  15591. this.shareDepthFrom = null;
  15592. };
  15593. THREE.WebGLRenderTarget.prototype = {
  15594. constructor: THREE.WebGLRenderTarget,
  15595. clone: function () {
  15596. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15597. tmp.wrapS = this.wrapS;
  15598. tmp.wrapT = this.wrapT;
  15599. tmp.magFilter = this.magFilter;
  15600. tmp.minFilter = this.minFilter;
  15601. tmp.anisotropy = this.anisotropy;
  15602. tmp.offset.copy( this.offset );
  15603. tmp.repeat.copy( this.repeat );
  15604. tmp.format = this.format;
  15605. tmp.type = this.type;
  15606. tmp.depthBuffer = this.depthBuffer;
  15607. tmp.stencilBuffer = this.stencilBuffer;
  15608. tmp.generateMipmaps = this.generateMipmaps;
  15609. tmp.shareDepthFrom = this.shareDepthFrom;
  15610. return tmp;
  15611. },
  15612. dispose: function () {
  15613. this.dispatchEvent( { type: 'dispose' } );
  15614. }
  15615. };
  15616. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15617. /**
  15618. * @author alteredq / http://alteredqualia.com
  15619. */
  15620. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15621. THREE.WebGLRenderTarget.call( this, width, height, options );
  15622. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15623. };
  15624. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15625. THREE.WebGLProgram = ( function () {
  15626. var programIdCount = 0;
  15627. var generateDefines = function ( defines ) {
  15628. var value, chunk, chunks = [];
  15629. for ( var d in defines ) {
  15630. value = defines[ d ];
  15631. if ( value === false ) continue;
  15632. chunk = "#define " + d + " " + value;
  15633. chunks.push( chunk );
  15634. }
  15635. return chunks.join( "\n" );
  15636. };
  15637. var cacheUniformLocations = function ( gl, program, identifiers ) {
  15638. var uniforms = {};
  15639. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15640. var id = identifiers[ i ];
  15641. uniforms[ id ] = gl.getUniformLocation( program, id );
  15642. }
  15643. return uniforms;
  15644. };
  15645. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  15646. var attributes = {};
  15647. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15648. var id = identifiers[ i ];
  15649. attributes[ id ] = gl.getAttribLocation( program, id );
  15650. }
  15651. return attributes;
  15652. };
  15653. return function ( renderer, code, material, parameters ) {
  15654. var _this = renderer;
  15655. var _gl = _this.context;
  15656. var fragmentShader = material.fragmentShader;
  15657. var vertexShader = material.vertexShader;
  15658. var uniforms = material.uniforms;
  15659. var attributes = material.attributes;
  15660. var defines = material.defines;
  15661. var index0AttributeName = material.index0AttributeName;
  15662. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15663. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15664. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15665. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15666. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15667. }
  15668. // console.log( "building new program " );
  15669. //
  15670. var customDefines = generateDefines( defines );
  15671. //
  15672. var program = _gl.createProgram();
  15673. var prefix_vertex = [
  15674. "precision " + parameters.precision + " float;",
  15675. "precision " + parameters.precision + " int;",
  15676. customDefines,
  15677. parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15678. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15679. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15680. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15681. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15682. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15683. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15684. "#define MAX_SHADOWS " + parameters.maxShadows,
  15685. "#define MAX_BONES " + parameters.maxBones,
  15686. parameters.map ? "#define USE_MAP" : "",
  15687. parameters.envMap ? "#define USE_ENVMAP" : "",
  15688. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15689. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15690. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15691. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15692. parameters.vertexColors ? "#define USE_COLOR" : "",
  15693. parameters.skinning ? "#define USE_SKINNING" : "",
  15694. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15695. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15696. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15697. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15698. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15699. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15700. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15701. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15702. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15703. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15704. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15705. "uniform mat4 modelMatrix;",
  15706. "uniform mat4 modelViewMatrix;",
  15707. "uniform mat4 projectionMatrix;",
  15708. "uniform mat4 viewMatrix;",
  15709. "uniform mat3 normalMatrix;",
  15710. "uniform vec3 cameraPosition;",
  15711. "attribute vec3 position;",
  15712. "attribute vec3 normal;",
  15713. "attribute vec2 uv;",
  15714. "attribute vec2 uv2;",
  15715. "#ifdef USE_COLOR",
  15716. " attribute vec3 color;",
  15717. "#endif",
  15718. "#ifdef USE_MORPHTARGETS",
  15719. " attribute vec3 morphTarget0;",
  15720. " attribute vec3 morphTarget1;",
  15721. " attribute vec3 morphTarget2;",
  15722. " attribute vec3 morphTarget3;",
  15723. " #ifdef USE_MORPHNORMALS",
  15724. " attribute vec3 morphNormal0;",
  15725. " attribute vec3 morphNormal1;",
  15726. " attribute vec3 morphNormal2;",
  15727. " attribute vec3 morphNormal3;",
  15728. " #else",
  15729. " attribute vec3 morphTarget4;",
  15730. " attribute vec3 morphTarget5;",
  15731. " attribute vec3 morphTarget6;",
  15732. " attribute vec3 morphTarget7;",
  15733. " #endif",
  15734. "#endif",
  15735. "#ifdef USE_SKINNING",
  15736. " attribute vec4 skinIndex;",
  15737. " attribute vec4 skinWeight;",
  15738. "#endif",
  15739. ""
  15740. ].join( '\n' );
  15741. var prefix_fragment = [
  15742. "precision " + parameters.precision + " float;",
  15743. "precision " + parameters.precision + " int;",
  15744. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15745. customDefines,
  15746. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15747. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15748. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15749. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15750. "#define MAX_SHADOWS " + parameters.maxShadows,
  15751. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15752. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15753. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15754. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15755. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15756. parameters.map ? "#define USE_MAP" : "",
  15757. parameters.envMap ? "#define USE_ENVMAP" : "",
  15758. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15759. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15760. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15761. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15762. parameters.vertexColors ? "#define USE_COLOR" : "",
  15763. parameters.metal ? "#define METAL" : "",
  15764. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15765. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15766. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15767. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15768. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15769. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15770. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15771. "uniform mat4 viewMatrix;",
  15772. "uniform vec3 cameraPosition;",
  15773. ""
  15774. ].join( '\n' );
  15775. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  15776. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  15777. _gl.attachShader( program, glVertexShader );
  15778. _gl.attachShader( program, glFragmentShader );
  15779. // Force a particular attribute to index 0.
  15780. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15781. // And, color, for example is often automatically bound to index 0 so disabling it
  15782. if ( index0AttributeName !== undefined ) {
  15783. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15784. }
  15785. _gl.linkProgram( program );
  15786. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  15787. console.error( 'Could not initialise shader' );
  15788. console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
  15789. console.error( 'gl.getError()', _gl.getError() );
  15790. }
  15791. if ( _gl.getProgramInfoLog( program ) !== '' ) {
  15792. console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
  15793. }
  15794. // cache uniform locations
  15795. var identifiers = [
  15796. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15797. 'morphTargetInfluences'
  15798. ];
  15799. if ( parameters.useVertexTexture ) {
  15800. identifiers.push( 'boneTexture' );
  15801. identifiers.push( 'boneTextureWidth' );
  15802. identifiers.push( 'boneTextureHeight' );
  15803. } else {
  15804. identifiers.push( 'boneGlobalMatrices' );
  15805. }
  15806. for ( var u in uniforms ) {
  15807. identifiers.push( u );
  15808. }
  15809. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  15810. // cache attributes locations
  15811. identifiers = [
  15812. "position", "normal", "uv", "uv2", "tangent", "color",
  15813. "skinIndex", "skinWeight", "lineDistance"
  15814. ];
  15815. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15816. identifiers.push( "morphTarget" + i );
  15817. }
  15818. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15819. identifiers.push( "morphNormal" + i );
  15820. }
  15821. for ( var a in attributes ) {
  15822. identifiers.push( a );
  15823. }
  15824. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  15825. //
  15826. this.id = programIdCount ++;
  15827. this.code = code;
  15828. this.usedTimes = 1;
  15829. this.program = program;
  15830. this.vertexShader = glVertexShader; // _gl.getShaderSource( glVertexShader );
  15831. this.fragmentShader = _gl.getShaderSource( glFragmentShader );
  15832. // clean up
  15833. _gl.deleteShader( glVertexShader );
  15834. _gl.deleteShader( glFragmentShader );
  15835. return this;
  15836. };
  15837. } )();
  15838. THREE.WebGLShader = ( function () {
  15839. var addLineNumbers = function ( string ) {
  15840. var lines = string.split( '\n' );
  15841. for ( var i = 0; i < lines.length; i ++ ) {
  15842. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  15843. }
  15844. return lines.join( '\n' );
  15845. };
  15846. return function ( gl, type, string ) {
  15847. var shader = gl.createShader( type );
  15848. gl.shaderSource( shader, string );
  15849. gl.compileShader( shader );
  15850. // if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {}
  15851. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  15852. console.error( 'THREE.WebGLShader:', 'gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) );
  15853. console.error( addLineNumbers( string ) );
  15854. }
  15855. return shader;
  15856. };
  15857. } )();
  15858. /**
  15859. * @author mrdoob / http://mrdoob.com/
  15860. */
  15861. THREE.RenderableVertex = function () {
  15862. this.position = new THREE.Vector3();
  15863. this.positionWorld = new THREE.Vector3();
  15864. this.positionScreen = new THREE.Vector4();
  15865. this.visible = true;
  15866. };
  15867. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15868. this.positionWorld.copy( vertex.positionWorld );
  15869. this.positionScreen.copy( vertex.positionScreen );
  15870. };
  15871. /**
  15872. * @author mrdoob / http://mrdoob.com/
  15873. */
  15874. THREE.RenderableFace = function () {
  15875. this.id = 0;
  15876. this.v1 = new THREE.RenderableVertex();
  15877. this.v2 = new THREE.RenderableVertex();
  15878. this.v3 = new THREE.RenderableVertex();
  15879. this.normalModel = new THREE.Vector3();
  15880. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15881. this.vertexNormalsLength = 0;
  15882. this.color = null;
  15883. this.material = null;
  15884. this.uvs = [[]];
  15885. this.z = 0;
  15886. };
  15887. /**
  15888. * @author mrdoob / http://mrdoob.com/
  15889. */
  15890. THREE.RenderableObject = function () {
  15891. this.id = 0;
  15892. this.object = null;
  15893. this.z = 0;
  15894. };
  15895. /**
  15896. * @author mrdoob / http://mrdoob.com/
  15897. */
  15898. THREE.RenderableSprite = function () {
  15899. this.id = 0;
  15900. this.object = null;
  15901. this.x = 0;
  15902. this.y = 0;
  15903. this.z = 0;
  15904. this.rotation = 0;
  15905. this.scale = new THREE.Vector2();
  15906. this.material = null;
  15907. };
  15908. /**
  15909. * @author mrdoob / http://mrdoob.com/
  15910. */
  15911. THREE.RenderableLine = function () {
  15912. this.id = 0;
  15913. this.v1 = new THREE.RenderableVertex();
  15914. this.v2 = new THREE.RenderableVertex();
  15915. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15916. this.material = null;
  15917. this.z = 0;
  15918. };
  15919. /**
  15920. * @author mrdoob / http://mrdoob.com/
  15921. * @author alteredq / http://alteredqualia.com/
  15922. */
  15923. THREE.GeometryUtils = {
  15924. // Merge two geometries or geometry and geometry from object (using object's transform)
  15925. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15926. var matrix, normalMatrix,
  15927. vertexOffset = geometry1.vertices.length,
  15928. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15929. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15930. vertices1 = geometry1.vertices,
  15931. vertices2 = geometry2.vertices,
  15932. faces1 = geometry1.faces,
  15933. faces2 = geometry2.faces,
  15934. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15935. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15936. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15937. if ( object2 instanceof THREE.Mesh ) {
  15938. object2.matrixAutoUpdate && object2.updateMatrix();
  15939. matrix = object2.matrix;
  15940. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15941. }
  15942. // vertices
  15943. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15944. var vertex = vertices2[ i ];
  15945. var vertexCopy = vertex.clone();
  15946. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15947. vertices1.push( vertexCopy );
  15948. }
  15949. // faces
  15950. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15951. var face = faces2[ i ], faceCopy, normal, color,
  15952. faceVertexNormals = face.vertexNormals,
  15953. faceVertexColors = face.vertexColors;
  15954. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15955. faceCopy.normal.copy( face.normal );
  15956. if ( normalMatrix ) {
  15957. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15958. }
  15959. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15960. normal = faceVertexNormals[ j ].clone();
  15961. if ( normalMatrix ) {
  15962. normal.applyMatrix3( normalMatrix ).normalize();
  15963. }
  15964. faceCopy.vertexNormals.push( normal );
  15965. }
  15966. faceCopy.color.copy( face.color );
  15967. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15968. color = faceVertexColors[ j ];
  15969. faceCopy.vertexColors.push( color.clone() );
  15970. }
  15971. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15972. faces1.push( faceCopy );
  15973. }
  15974. // uvs
  15975. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15976. var uv = uvs2[ i ], uvCopy = [];
  15977. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15978. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15979. }
  15980. uvs1.push( uvCopy );
  15981. }
  15982. },
  15983. // Get random point in triangle (via barycentric coordinates)
  15984. // (uniform distribution)
  15985. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15986. randomPointInTriangle: function () {
  15987. var vector = new THREE.Vector3();
  15988. return function ( vectorA, vectorB, vectorC ) {
  15989. var point = new THREE.Vector3();
  15990. var a = THREE.Math.random16();
  15991. var b = THREE.Math.random16();
  15992. if ( ( a + b ) > 1 ) {
  15993. a = 1 - a;
  15994. b = 1 - b;
  15995. }
  15996. var c = 1 - a - b;
  15997. point.copy( vectorA );
  15998. point.multiplyScalar( a );
  15999. vector.copy( vectorB );
  16000. vector.multiplyScalar( b );
  16001. point.add( vector );
  16002. vector.copy( vectorC );
  16003. vector.multiplyScalar( c );
  16004. point.add( vector );
  16005. return point;
  16006. };
  16007. }(),
  16008. // Get random point in face (triangle / quad)
  16009. // (uniform distribution)
  16010. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  16011. var vA, vB, vC, vD;
  16012. vA = geometry.vertices[ face.a ];
  16013. vB = geometry.vertices[ face.b ];
  16014. vC = geometry.vertices[ face.c ];
  16015. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  16016. },
  16017. // Get uniformly distributed random points in mesh
  16018. // - create array with cumulative sums of face areas
  16019. // - pick random number from 0 to total area
  16020. // - find corresponding place in area array by binary search
  16021. // - get random point in face
  16022. randomPointsInGeometry: function ( geometry, n ) {
  16023. var face, i,
  16024. faces = geometry.faces,
  16025. vertices = geometry.vertices,
  16026. il = faces.length,
  16027. totalArea = 0,
  16028. cumulativeAreas = [],
  16029. vA, vB, vC, vD;
  16030. // precompute face areas
  16031. for ( i = 0; i < il; i ++ ) {
  16032. face = faces[ i ];
  16033. vA = vertices[ face.a ];
  16034. vB = vertices[ face.b ];
  16035. vC = vertices[ face.c ];
  16036. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16037. totalArea += face._area;
  16038. cumulativeAreas[ i ] = totalArea;
  16039. }
  16040. // binary search cumulative areas array
  16041. function binarySearchIndices( value ) {
  16042. function binarySearch( start, end ) {
  16043. // return closest larger index
  16044. // if exact number is not found
  16045. if ( end < start )
  16046. return start;
  16047. var mid = start + Math.floor( ( end - start ) / 2 );
  16048. if ( cumulativeAreas[ mid ] > value ) {
  16049. return binarySearch( start, mid - 1 );
  16050. } else if ( cumulativeAreas[ mid ] < value ) {
  16051. return binarySearch( mid + 1, end );
  16052. } else {
  16053. return mid;
  16054. }
  16055. }
  16056. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16057. return result;
  16058. }
  16059. // pick random face weighted by face area
  16060. var r, index,
  16061. result = [];
  16062. var stats = {};
  16063. for ( i = 0; i < n; i ++ ) {
  16064. r = THREE.Math.random16() * totalArea;
  16065. index = binarySearchIndices( r );
  16066. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16067. if ( ! stats[ index ] ) {
  16068. stats[ index ] = 1;
  16069. } else {
  16070. stats[ index ] += 1;
  16071. }
  16072. }
  16073. return result;
  16074. },
  16075. // Get triangle area (half of parallelogram)
  16076. // http://mathworld.wolfram.com/TriangleArea.html
  16077. triangleArea: function () {
  16078. var vector1 = new THREE.Vector3();
  16079. var vector2 = new THREE.Vector3();
  16080. return function ( vectorA, vectorB, vectorC ) {
  16081. vector1.subVectors( vectorB, vectorA );
  16082. vector2.subVectors( vectorC, vectorA );
  16083. vector1.cross( vector2 );
  16084. return 0.5 * vector1.length();
  16085. };
  16086. }(),
  16087. // Center geometry so that 0,0,0 is in center of bounding box
  16088. center: function ( geometry ) {
  16089. geometry.computeBoundingBox();
  16090. var bb = geometry.boundingBox;
  16091. var offset = new THREE.Vector3();
  16092. offset.addVectors( bb.min, bb.max );
  16093. offset.multiplyScalar( -0.5 );
  16094. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16095. geometry.computeBoundingBox();
  16096. return offset;
  16097. }
  16098. };
  16099. /**
  16100. * @author alteredq / http://alteredqualia.com/
  16101. * @author mrdoob / http://mrdoob.com/
  16102. */
  16103. THREE.ImageUtils = {
  16104. crossOrigin: undefined,
  16105. loadTexture: function ( url, mapping, onLoad, onError ) {
  16106. var loader = new THREE.ImageLoader();
  16107. loader.crossOrigin = this.crossOrigin;
  16108. var texture = new THREE.Texture( undefined, mapping );
  16109. var image = loader.load( url, function () {
  16110. texture.needsUpdate = true;
  16111. if ( onLoad ) onLoad( texture );
  16112. } );
  16113. texture.image = image;
  16114. texture.sourceFile = url;
  16115. return texture;
  16116. },
  16117. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16118. var texture = new THREE.CompressedTexture();
  16119. texture.mapping = mapping;
  16120. var request = new XMLHttpRequest();
  16121. request.onload = function () {
  16122. var buffer = request.response;
  16123. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16124. texture.format = dds.format;
  16125. texture.mipmaps = dds.mipmaps;
  16126. texture.image.width = dds.width;
  16127. texture.image.height = dds.height;
  16128. // gl.generateMipmap fails for compressed textures
  16129. // mipmaps must be embedded in the DDS file
  16130. // or texture filters must not use mipmapping
  16131. texture.generateMipmaps = false;
  16132. texture.needsUpdate = true;
  16133. if ( onLoad ) onLoad( texture );
  16134. }
  16135. request.onerror = onError;
  16136. request.open( 'GET', url, true );
  16137. request.responseType = "arraybuffer";
  16138. request.send( null );
  16139. return texture;
  16140. },
  16141. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16142. var images = [];
  16143. images.loadCount = 0;
  16144. var texture = new THREE.Texture();
  16145. texture.image = images;
  16146. if ( mapping !== undefined ) texture.mapping = mapping;
  16147. // no flipping needed for cube textures
  16148. texture.flipY = false;
  16149. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16150. var cubeImage = new Image();
  16151. images[ i ] = cubeImage;
  16152. cubeImage.onload = function () {
  16153. images.loadCount += 1;
  16154. if ( images.loadCount === 6 ) {
  16155. texture.needsUpdate = true;
  16156. if ( onLoad ) onLoad( texture );
  16157. }
  16158. };
  16159. cubeImage.onerror = onError;
  16160. cubeImage.crossOrigin = this.crossOrigin;
  16161. cubeImage.src = array[ i ];
  16162. }
  16163. return texture;
  16164. },
  16165. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16166. var images = [];
  16167. images.loadCount = 0;
  16168. var texture = new THREE.CompressedTexture();
  16169. texture.image = images;
  16170. if ( mapping !== undefined ) texture.mapping = mapping;
  16171. // no flipping for cube textures
  16172. // (also flipping doesn't work for compressed textures )
  16173. texture.flipY = false;
  16174. // can't generate mipmaps for compressed textures
  16175. // mips must be embedded in DDS files
  16176. texture.generateMipmaps = false;
  16177. var generateCubeFaceCallback = function ( rq, img ) {
  16178. return function () {
  16179. var buffer = rq.response;
  16180. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16181. img.format = dds.format;
  16182. img.mipmaps = dds.mipmaps;
  16183. img.width = dds.width;
  16184. img.height = dds.height;
  16185. images.loadCount += 1;
  16186. if ( images.loadCount === 6 ) {
  16187. texture.format = dds.format;
  16188. texture.needsUpdate = true;
  16189. if ( onLoad ) onLoad( texture );
  16190. }
  16191. }
  16192. }
  16193. // compressed cubemap textures as 6 separate DDS files
  16194. if ( array instanceof Array ) {
  16195. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16196. var cubeImage = {};
  16197. images[ i ] = cubeImage;
  16198. var request = new XMLHttpRequest();
  16199. request.onload = generateCubeFaceCallback( request, cubeImage );
  16200. request.onerror = onError;
  16201. var url = array[ i ];
  16202. request.open( 'GET', url, true );
  16203. request.responseType = "arraybuffer";
  16204. request.send( null );
  16205. }
  16206. // compressed cubemap texture stored in a single DDS file
  16207. } else {
  16208. var url = array;
  16209. var request = new XMLHttpRequest();
  16210. request.onload = function( ) {
  16211. var buffer = request.response;
  16212. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16213. if ( dds.isCubemap ) {
  16214. var faces = dds.mipmaps.length / dds.mipmapCount;
  16215. for ( var f = 0; f < faces; f ++ ) {
  16216. images[ f ] = { mipmaps : [] };
  16217. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16218. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16219. images[ f ].format = dds.format;
  16220. images[ f ].width = dds.width;
  16221. images[ f ].height = dds.height;
  16222. }
  16223. }
  16224. texture.format = dds.format;
  16225. texture.needsUpdate = true;
  16226. if ( onLoad ) onLoad( texture );
  16227. }
  16228. }
  16229. request.onerror = onError;
  16230. request.open( 'GET', url, true );
  16231. request.responseType = "arraybuffer";
  16232. request.send( null );
  16233. }
  16234. return texture;
  16235. },
  16236. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  16237. var images = [];
  16238. images.loadCount = 0;
  16239. var texture = new THREE.CompressedTexture();
  16240. texture.image = images;
  16241. if ( mapping !== undefined ) texture.mapping = mapping;
  16242. // no flipping for cube textures
  16243. // (also flipping doesn't work for compressed textures )
  16244. texture.flipY = false;
  16245. // can't generate mipmaps for compressed textures
  16246. // mips must be embedded in DDS files
  16247. texture.generateMipmaps = false;
  16248. {
  16249. var request = new XMLHttpRequest();
  16250. request.onload = function( ) {
  16251. var buffer = request.response;
  16252. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16253. if ( dds.isCubemap ) {
  16254. var faces = dds.mipmaps.length / dds.mipmapCount;
  16255. for ( var f = 0; f < faces; f ++ ) {
  16256. images[ f ] = { mipmaps : [] };
  16257. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16258. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16259. images[ f ].format = dds.format;
  16260. images[ f ].width = dds.width;
  16261. images[ f ].height = dds.height;
  16262. }
  16263. }
  16264. } else {
  16265. texture.image.width = dds.width;
  16266. texture.image.height = dds.height;
  16267. texture.mipmaps = dds.mipmaps;
  16268. }
  16269. texture.format = dds.format;
  16270. texture.needsUpdate = true;
  16271. if ( onLoad ) onLoad( texture );
  16272. }
  16273. request.onerror = onError;
  16274. request.open( 'GET', url, true );
  16275. request.responseType = "arraybuffer";
  16276. request.send( null );
  16277. }
  16278. return texture;
  16279. },
  16280. parseDDS: function ( buffer, loadMipmaps ) {
  16281. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16282. // Adapted from @toji's DDS utils
  16283. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16284. // All values and structures referenced from:
  16285. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16286. var DDS_MAGIC = 0x20534444;
  16287. var DDSD_CAPS = 0x1,
  16288. DDSD_HEIGHT = 0x2,
  16289. DDSD_WIDTH = 0x4,
  16290. DDSD_PITCH = 0x8,
  16291. DDSD_PIXELFORMAT = 0x1000,
  16292. DDSD_MIPMAPCOUNT = 0x20000,
  16293. DDSD_LINEARSIZE = 0x80000,
  16294. DDSD_DEPTH = 0x800000;
  16295. var DDSCAPS_COMPLEX = 0x8,
  16296. DDSCAPS_MIPMAP = 0x400000,
  16297. DDSCAPS_TEXTURE = 0x1000;
  16298. var DDSCAPS2_CUBEMAP = 0x200,
  16299. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16300. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16301. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16302. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16303. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16304. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16305. DDSCAPS2_VOLUME = 0x200000;
  16306. var DDPF_ALPHAPIXELS = 0x1,
  16307. DDPF_ALPHA = 0x2,
  16308. DDPF_FOURCC = 0x4,
  16309. DDPF_RGB = 0x40,
  16310. DDPF_YUV = 0x200,
  16311. DDPF_LUMINANCE = 0x20000;
  16312. function fourCCToInt32( value ) {
  16313. return value.charCodeAt(0) +
  16314. (value.charCodeAt(1) << 8) +
  16315. (value.charCodeAt(2) << 16) +
  16316. (value.charCodeAt(3) << 24);
  16317. }
  16318. function int32ToFourCC( value ) {
  16319. return String.fromCharCode(
  16320. value & 0xff,
  16321. (value >> 8) & 0xff,
  16322. (value >> 16) & 0xff,
  16323. (value >> 24) & 0xff
  16324. );
  16325. }
  16326. function loadARGBMip( buffer, dataOffset, width, height ) {
  16327. var dataLength = width*height*4;
  16328. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  16329. var byteArray = new Uint8Array( dataLength );
  16330. var dst = 0;
  16331. var src = 0;
  16332. for ( var y = 0; y < height; y++ ) {
  16333. for ( var x = 0; x < width; x++ ) {
  16334. var b = srcBuffer[src]; src++;
  16335. var g = srcBuffer[src]; src++;
  16336. var r = srcBuffer[src]; src++;
  16337. var a = srcBuffer[src]; src++;
  16338. byteArray[dst] = r; dst++; //r
  16339. byteArray[dst] = g; dst++; //g
  16340. byteArray[dst] = b; dst++; //b
  16341. byteArray[dst] = a; dst++; //a
  16342. }
  16343. }
  16344. return byteArray;
  16345. }
  16346. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16347. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16348. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16349. var headerLengthInt = 31; // The header length in 32 bit ints
  16350. // Offsets into the header array
  16351. var off_magic = 0;
  16352. var off_size = 1;
  16353. var off_flags = 2;
  16354. var off_height = 3;
  16355. var off_width = 4;
  16356. var off_mipmapCount = 7;
  16357. var off_pfFlags = 20;
  16358. var off_pfFourCC = 21;
  16359. var off_RGBBitCount = 22;
  16360. var off_RBitMask = 23;
  16361. var off_GBitMask = 24;
  16362. var off_BBitMask = 25;
  16363. var off_ABitMask = 26;
  16364. var off_caps = 27;
  16365. var off_caps2 = 28;
  16366. var off_caps3 = 29;
  16367. var off_caps4 = 30;
  16368. // Parse header
  16369. var header = new Int32Array( buffer, 0, headerLengthInt );
  16370. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16371. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16372. return dds;
  16373. }
  16374. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16375. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16376. return dds;
  16377. }
  16378. var blockBytes;
  16379. var fourCC = header[ off_pfFourCC ];
  16380. var isRGBAUncompressed = false;
  16381. switch ( fourCC ) {
  16382. case FOURCC_DXT1:
  16383. blockBytes = 8;
  16384. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16385. break;
  16386. case FOURCC_DXT3:
  16387. blockBytes = 16;
  16388. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16389. break;
  16390. case FOURCC_DXT5:
  16391. blockBytes = 16;
  16392. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16393. break;
  16394. default:
  16395. if( header[off_RGBBitCount] ==32
  16396. && header[off_RBitMask]&0xff0000
  16397. && header[off_GBitMask]&0xff00
  16398. && header[off_BBitMask]&0xff
  16399. && header[off_ABitMask]&0xff000000 ) {
  16400. isRGBAUncompressed = true;
  16401. blockBytes = 64;
  16402. dds.format = THREE.RGBAFormat;
  16403. } else {
  16404. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16405. return dds;
  16406. }
  16407. }
  16408. dds.mipmapCount = 1;
  16409. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16410. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16411. }
  16412. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16413. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16414. dds.width = header[ off_width ];
  16415. dds.height = header[ off_height ];
  16416. var dataOffset = header[ off_size ] + 4;
  16417. // Extract mipmaps buffers
  16418. var width = dds.width;
  16419. var height = dds.height;
  16420. var faces = dds.isCubemap ? 6 : 1;
  16421. for ( var face = 0; face < faces; face ++ ) {
  16422. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16423. if( isRGBAUncompressed ) {
  16424. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16425. var dataLength = byteArray.length;
  16426. } else {
  16427. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16428. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16429. }
  16430. var mipmap = { "data": byteArray, "width": width, "height": height };
  16431. dds.mipmaps.push( mipmap );
  16432. dataOffset += dataLength;
  16433. width = Math.max( width * 0.5, 1 );
  16434. height = Math.max( height * 0.5, 1 );
  16435. }
  16436. width = dds.width;
  16437. height = dds.height;
  16438. }
  16439. return dds;
  16440. },
  16441. getNormalMap: function ( image, depth ) {
  16442. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16443. var cross = function ( a, b ) {
  16444. 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 ] ];
  16445. }
  16446. var subtract = function ( a, b ) {
  16447. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16448. }
  16449. var normalize = function ( a ) {
  16450. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16451. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16452. }
  16453. depth = depth | 1;
  16454. var width = image.width;
  16455. var height = image.height;
  16456. var canvas = document.createElement( 'canvas' );
  16457. canvas.width = width;
  16458. canvas.height = height;
  16459. var context = canvas.getContext( '2d' );
  16460. context.drawImage( image, 0, 0 );
  16461. var data = context.getImageData( 0, 0, width, height ).data;
  16462. var imageData = context.createImageData( width, height );
  16463. var output = imageData.data;
  16464. for ( var x = 0; x < width; x ++ ) {
  16465. for ( var y = 0; y < height; y ++ ) {
  16466. var ly = y - 1 < 0 ? 0 : y - 1;
  16467. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16468. var lx = x - 1 < 0 ? 0 : x - 1;
  16469. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16470. var points = [];
  16471. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16472. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16473. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16474. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16475. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16476. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16477. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16478. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16479. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16480. var normals = [];
  16481. var num_points = points.length;
  16482. for ( var i = 0; i < num_points; i ++ ) {
  16483. var v1 = points[ i ];
  16484. var v2 = points[ ( i + 1 ) % num_points ];
  16485. v1 = subtract( v1, origin );
  16486. v2 = subtract( v2, origin );
  16487. normals.push( normalize( cross( v1, v2 ) ) );
  16488. }
  16489. var normal = [ 0, 0, 0 ];
  16490. for ( var i = 0; i < normals.length; i ++ ) {
  16491. normal[ 0 ] += normals[ i ][ 0 ];
  16492. normal[ 1 ] += normals[ i ][ 1 ];
  16493. normal[ 2 ] += normals[ i ][ 2 ];
  16494. }
  16495. normal[ 0 ] /= normals.length;
  16496. normal[ 1 ] /= normals.length;
  16497. normal[ 2 ] /= normals.length;
  16498. var idx = ( y * width + x ) * 4;
  16499. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16500. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16501. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16502. output[ idx + 3 ] = 255;
  16503. }
  16504. }
  16505. context.putImageData( imageData, 0, 0 );
  16506. return canvas;
  16507. },
  16508. generateDataTexture: function ( width, height, color ) {
  16509. var size = width * height;
  16510. var data = new Uint8Array( 3 * size );
  16511. var r = Math.floor( color.r * 255 );
  16512. var g = Math.floor( color.g * 255 );
  16513. var b = Math.floor( color.b * 255 );
  16514. for ( var i = 0; i < size; i ++ ) {
  16515. data[ i * 3 ] = r;
  16516. data[ i * 3 + 1 ] = g;
  16517. data[ i * 3 + 2 ] = b;
  16518. }
  16519. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16520. texture.needsUpdate = true;
  16521. return texture;
  16522. }
  16523. };
  16524. /**
  16525. * @author alteredq / http://alteredqualia.com/
  16526. */
  16527. THREE.SceneUtils = {
  16528. createMultiMaterialObject: function ( geometry, materials ) {
  16529. var group = new THREE.Object3D();
  16530. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16531. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16532. }
  16533. return group;
  16534. },
  16535. detach : function ( child, parent, scene ) {
  16536. child.applyMatrix( parent.matrixWorld );
  16537. parent.remove( child );
  16538. scene.add( child );
  16539. },
  16540. attach: function ( child, scene, parent ) {
  16541. var matrixWorldInverse = new THREE.Matrix4();
  16542. matrixWorldInverse.getInverse( parent.matrixWorld );
  16543. child.applyMatrix( matrixWorldInverse );
  16544. scene.remove( child );
  16545. parent.add( child );
  16546. }
  16547. };
  16548. /**
  16549. * @author zz85 / http://www.lab4games.net/zz85/blog
  16550. * @author alteredq / http://alteredqualia.com/
  16551. *
  16552. * For Text operations in three.js (See TextGeometry)
  16553. *
  16554. * It uses techniques used in:
  16555. *
  16556. * typeface.js and canvastext
  16557. * For converting fonts and rendering with javascript
  16558. * http://typeface.neocracy.org
  16559. *
  16560. * Triangulation ported from AS3
  16561. * Simple Polygon Triangulation
  16562. * http://actionsnippet.com/?p=1462
  16563. *
  16564. * A Method to triangulate shapes with holes
  16565. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16566. *
  16567. */
  16568. THREE.FontUtils = {
  16569. faces : {},
  16570. // Just for now. face[weight][style]
  16571. face : "helvetiker",
  16572. weight: "normal",
  16573. style : "normal",
  16574. size : 150,
  16575. divisions : 10,
  16576. getFace : function() {
  16577. return this.faces[ this.face ][ this.weight ][ this.style ];
  16578. },
  16579. loadFace : function( data ) {
  16580. var family = data.familyName.toLowerCase();
  16581. var ThreeFont = this;
  16582. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16583. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16584. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16585. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16586. return data;
  16587. },
  16588. drawText : function( text ) {
  16589. var characterPts = [], allPts = [];
  16590. // RenderText
  16591. var i, p,
  16592. face = this.getFace(),
  16593. scale = this.size / face.resolution,
  16594. offset = 0,
  16595. chars = String( text ).split( '' ),
  16596. length = chars.length;
  16597. var fontPaths = [];
  16598. for ( i = 0; i < length; i ++ ) {
  16599. var path = new THREE.Path();
  16600. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16601. offset += ret.offset;
  16602. fontPaths.push( ret.path );
  16603. }
  16604. // get the width
  16605. var width = offset / 2;
  16606. //
  16607. // for ( p = 0; p < allPts.length; p++ ) {
  16608. //
  16609. // allPts[ p ].x -= width;
  16610. //
  16611. // }
  16612. //var extract = this.extractPoints( allPts, characterPts );
  16613. //extract.contour = allPts;
  16614. //extract.paths = fontPaths;
  16615. //extract.offset = width;
  16616. return { paths : fontPaths, offset : width };
  16617. },
  16618. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16619. var pts = [];
  16620. var i, i2, divisions,
  16621. outline, action, length,
  16622. scaleX, scaleY,
  16623. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16624. laste,
  16625. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16626. if ( !glyph ) return;
  16627. if ( glyph.o ) {
  16628. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16629. length = outline.length;
  16630. scaleX = scale;
  16631. scaleY = scale;
  16632. for ( i = 0; i < length; ) {
  16633. action = outline[ i ++ ];
  16634. //console.log( action );
  16635. switch( action ) {
  16636. case 'm':
  16637. // Move To
  16638. x = outline[ i++ ] * scaleX + offset;
  16639. y = outline[ i++ ] * scaleY;
  16640. path.moveTo( x, y );
  16641. break;
  16642. case 'l':
  16643. // Line To
  16644. x = outline[ i++ ] * scaleX + offset;
  16645. y = outline[ i++ ] * scaleY;
  16646. path.lineTo(x,y);
  16647. break;
  16648. case 'q':
  16649. // QuadraticCurveTo
  16650. cpx = outline[ i++ ] * scaleX + offset;
  16651. cpy = outline[ i++ ] * scaleY;
  16652. cpx1 = outline[ i++ ] * scaleX + offset;
  16653. cpy1 = outline[ i++ ] * scaleY;
  16654. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16655. laste = pts[ pts.length - 1 ];
  16656. if ( laste ) {
  16657. cpx0 = laste.x;
  16658. cpy0 = laste.y;
  16659. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16660. var t = i2 / divisions;
  16661. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16662. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16663. }
  16664. }
  16665. break;
  16666. case 'b':
  16667. // Cubic Bezier Curve
  16668. cpx = outline[ i++ ] * scaleX + offset;
  16669. cpy = outline[ i++ ] * scaleY;
  16670. cpx1 = outline[ i++ ] * scaleX + offset;
  16671. cpy1 = outline[ i++ ] * -scaleY;
  16672. cpx2 = outline[ i++ ] * scaleX + offset;
  16673. cpy2 = outline[ i++ ] * -scaleY;
  16674. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16675. laste = pts[ pts.length - 1 ];
  16676. if ( laste ) {
  16677. cpx0 = laste.x;
  16678. cpy0 = laste.y;
  16679. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16680. var t = i2 / divisions;
  16681. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16682. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16683. }
  16684. }
  16685. break;
  16686. }
  16687. }
  16688. }
  16689. return { offset: glyph.ha*scale, path:path};
  16690. }
  16691. };
  16692. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16693. // Parameters
  16694. parameters = parameters || {};
  16695. var size = parameters.size !== undefined ? parameters.size : 100;
  16696. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16697. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16698. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16699. var style = parameters.style !== undefined ? parameters.style : "normal";
  16700. THREE.FontUtils.size = size;
  16701. THREE.FontUtils.divisions = curveSegments;
  16702. THREE.FontUtils.face = font;
  16703. THREE.FontUtils.weight = weight;
  16704. THREE.FontUtils.style = style;
  16705. // Get a Font data json object
  16706. var data = THREE.FontUtils.drawText( text );
  16707. var paths = data.paths;
  16708. var shapes = [];
  16709. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16710. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16711. }
  16712. return shapes;
  16713. };
  16714. /**
  16715. * This code is a quick port of code written in C++ which was submitted to
  16716. * flipcode.com by John W. Ratcliff // July 22, 2000
  16717. * See original code and more information here:
  16718. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16719. *
  16720. * ported to actionscript by Zevan Rosser
  16721. * www.actionsnippet.com
  16722. *
  16723. * ported to javascript by Joshua Koo
  16724. * http://www.lab4games.net/zz85/blog
  16725. *
  16726. */
  16727. ( function( namespace ) {
  16728. var EPSILON = 0.0000000001;
  16729. // takes in an contour array and returns
  16730. var process = function( contour, indices ) {
  16731. var n = contour.length;
  16732. if ( n < 3 ) return null;
  16733. var result = [],
  16734. verts = [],
  16735. vertIndices = [];
  16736. /* we want a counter-clockwise polygon in verts */
  16737. var u, v, w;
  16738. if ( area( contour ) > 0.0 ) {
  16739. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16740. } else {
  16741. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16742. }
  16743. var nv = n;
  16744. /* remove nv - 2 vertices, creating 1 triangle every time */
  16745. var count = 2 * nv; /* error detection */
  16746. for( v = nv - 1; nv > 2; ) {
  16747. /* if we loop, it is probably a non-simple polygon */
  16748. if ( ( count-- ) <= 0 ) {
  16749. //** Triangulate: ERROR - probable bad polygon!
  16750. //throw ( "Warning, unable to triangulate polygon!" );
  16751. //return null;
  16752. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16753. console.log( "Warning, unable to triangulate polygon!" );
  16754. if ( indices ) return vertIndices;
  16755. return result;
  16756. }
  16757. /* three consecutive vertices in current polygon, <u,v,w> */
  16758. u = v; if ( nv <= u ) u = 0; /* previous */
  16759. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16760. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16761. if ( snip( contour, u, v, w, nv, verts ) ) {
  16762. var a, b, c, s, t;
  16763. /* true names of the vertices */
  16764. a = verts[ u ];
  16765. b = verts[ v ];
  16766. c = verts[ w ];
  16767. /* output Triangle */
  16768. result.push( [ contour[ a ],
  16769. contour[ b ],
  16770. contour[ c ] ] );
  16771. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16772. /* remove v from the remaining polygon */
  16773. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16774. verts[ s ] = verts[ t ];
  16775. }
  16776. nv--;
  16777. /* reset error detection counter */
  16778. count = 2 * nv;
  16779. }
  16780. }
  16781. if ( indices ) return vertIndices;
  16782. return result;
  16783. };
  16784. // calculate area of the contour polygon
  16785. var area = function ( contour ) {
  16786. var n = contour.length;
  16787. var a = 0.0;
  16788. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16789. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16790. }
  16791. return a * 0.5;
  16792. };
  16793. var snip = function ( contour, u, v, w, n, verts ) {
  16794. var p;
  16795. var ax, ay, bx, by;
  16796. var cx, cy, px, py;
  16797. ax = contour[ verts[ u ] ].x;
  16798. ay = contour[ verts[ u ] ].y;
  16799. bx = contour[ verts[ v ] ].x;
  16800. by = contour[ verts[ v ] ].y;
  16801. cx = contour[ verts[ w ] ].x;
  16802. cy = contour[ verts[ w ] ].y;
  16803. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16804. var aX, aY, bX, bY, cX, cY;
  16805. var apx, apy, bpx, bpy, cpx, cpy;
  16806. var cCROSSap, bCROSScp, aCROSSbp;
  16807. aX = cx - bx; aY = cy - by;
  16808. bX = ax - cx; bY = ay - cy;
  16809. cX = bx - ax; cY = by - ay;
  16810. for ( p = 0; p < n; p++ ) {
  16811. px = contour[ verts[ p ] ].x
  16812. py = contour[ verts[ p ] ].y
  16813. if ( ( (px === ax) && (py === ay) ) ||
  16814. ( (px === bx) && (py === by) ) ||
  16815. ( (px === cx) && (py === cy) ) ) continue;
  16816. apx = px - ax; apy = py - ay;
  16817. bpx = px - bx; bpy = py - by;
  16818. cpx = px - cx; cpy = py - cy;
  16819. // see if p is inside triangle abc
  16820. aCROSSbp = aX*bpy - aY*bpx;
  16821. cCROSSap = cX*apy - cY*apx;
  16822. bCROSScp = bX*cpy - bY*cpx;
  16823. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16824. }
  16825. return true;
  16826. };
  16827. namespace.Triangulate = process;
  16828. namespace.Triangulate.area = area;
  16829. return namespace;
  16830. })(THREE.FontUtils);
  16831. // To use the typeface.js face files, hook up the API
  16832. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16833. THREE.typeface_js = self._typeface_js;
  16834. /**
  16835. * @author zz85 / http://www.lab4games.net/zz85/blog
  16836. * Extensible curve object
  16837. *
  16838. * Some common of Curve methods
  16839. * .getPoint(t), getTangent(t)
  16840. * .getPointAt(u), getTagentAt(u)
  16841. * .getPoints(), .getSpacedPoints()
  16842. * .getLength()
  16843. * .updateArcLengths()
  16844. *
  16845. * This following classes subclasses THREE.Curve:
  16846. *
  16847. * -- 2d classes --
  16848. * THREE.LineCurve
  16849. * THREE.QuadraticBezierCurve
  16850. * THREE.CubicBezierCurve
  16851. * THREE.SplineCurve
  16852. * THREE.ArcCurve
  16853. * THREE.EllipseCurve
  16854. *
  16855. * -- 3d classes --
  16856. * THREE.LineCurve3
  16857. * THREE.QuadraticBezierCurve3
  16858. * THREE.CubicBezierCurve3
  16859. * THREE.SplineCurve3
  16860. * THREE.ClosedSplineCurve3
  16861. *
  16862. * A series of curves can be represented as a THREE.CurvePath
  16863. *
  16864. **/
  16865. /**************************************************************
  16866. * Abstract Curve base class
  16867. **************************************************************/
  16868. THREE.Curve = function () {
  16869. };
  16870. // Virtual base class method to overwrite and implement in subclasses
  16871. // - t [0 .. 1]
  16872. THREE.Curve.prototype.getPoint = function ( t ) {
  16873. console.log( "Warning, getPoint() not implemented!" );
  16874. return null;
  16875. };
  16876. // Get point at relative position in curve according to arc length
  16877. // - u [0 .. 1]
  16878. THREE.Curve.prototype.getPointAt = function ( u ) {
  16879. var t = this.getUtoTmapping( u );
  16880. return this.getPoint( t );
  16881. };
  16882. // Get sequence of points using getPoint( t )
  16883. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16884. if ( !divisions ) divisions = 5;
  16885. var d, pts = [];
  16886. for ( d = 0; d <= divisions; d ++ ) {
  16887. pts.push( this.getPoint( d / divisions ) );
  16888. }
  16889. return pts;
  16890. };
  16891. // Get sequence of points using getPointAt( u )
  16892. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16893. if ( !divisions ) divisions = 5;
  16894. var d, pts = [];
  16895. for ( d = 0; d <= divisions; d ++ ) {
  16896. pts.push( this.getPointAt( d / divisions ) );
  16897. }
  16898. return pts;
  16899. };
  16900. // Get total curve arc length
  16901. THREE.Curve.prototype.getLength = function () {
  16902. var lengths = this.getLengths();
  16903. return lengths[ lengths.length - 1 ];
  16904. };
  16905. // Get list of cumulative segment lengths
  16906. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16907. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16908. if ( this.cacheArcLengths
  16909. && ( this.cacheArcLengths.length == divisions + 1 )
  16910. && !this.needsUpdate) {
  16911. //console.log( "cached", this.cacheArcLengths );
  16912. return this.cacheArcLengths;
  16913. }
  16914. this.needsUpdate = false;
  16915. var cache = [];
  16916. var current, last = this.getPoint( 0 );
  16917. var p, sum = 0;
  16918. cache.push( 0 );
  16919. for ( p = 1; p <= divisions; p ++ ) {
  16920. current = this.getPoint ( p / divisions );
  16921. sum += current.distanceTo( last );
  16922. cache.push( sum );
  16923. last = current;
  16924. }
  16925. this.cacheArcLengths = cache;
  16926. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16927. };
  16928. THREE.Curve.prototype.updateArcLengths = function() {
  16929. this.needsUpdate = true;
  16930. this.getLengths();
  16931. };
  16932. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16933. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16934. var arcLengths = this.getLengths();
  16935. var i = 0, il = arcLengths.length;
  16936. var targetArcLength; // The targeted u distance value to get
  16937. if ( distance ) {
  16938. targetArcLength = distance;
  16939. } else {
  16940. targetArcLength = u * arcLengths[ il - 1 ];
  16941. }
  16942. //var time = Date.now();
  16943. // binary search for the index with largest value smaller than target u distance
  16944. var low = 0, high = il - 1, comparison;
  16945. while ( low <= high ) {
  16946. 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
  16947. comparison = arcLengths[ i ] - targetArcLength;
  16948. if ( comparison < 0 ) {
  16949. low = i + 1;
  16950. continue;
  16951. } else if ( comparison > 0 ) {
  16952. high = i - 1;
  16953. continue;
  16954. } else {
  16955. high = i;
  16956. break;
  16957. // DONE
  16958. }
  16959. }
  16960. i = high;
  16961. //console.log('b' , i, low, high, Date.now()- time);
  16962. if ( arcLengths[ i ] == targetArcLength ) {
  16963. var t = i / ( il - 1 );
  16964. return t;
  16965. }
  16966. // we could get finer grain at lengths, or use simple interpolatation between two points
  16967. var lengthBefore = arcLengths[ i ];
  16968. var lengthAfter = arcLengths[ i + 1 ];
  16969. var segmentLength = lengthAfter - lengthBefore;
  16970. // determine where we are between the 'before' and 'after' points
  16971. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16972. // add that fractional amount to t
  16973. var t = ( i + segmentFraction ) / ( il -1 );
  16974. return t;
  16975. };
  16976. // Returns a unit vector tangent at t
  16977. // In case any sub curve does not implement its tangent derivation,
  16978. // 2 points a small delta apart will be used to find its gradient
  16979. // which seems to give a reasonable approximation
  16980. THREE.Curve.prototype.getTangent = function( t ) {
  16981. var delta = 0.0001;
  16982. var t1 = t - delta;
  16983. var t2 = t + delta;
  16984. // Capping in case of danger
  16985. if ( t1 < 0 ) t1 = 0;
  16986. if ( t2 > 1 ) t2 = 1;
  16987. var pt1 = this.getPoint( t1 );
  16988. var pt2 = this.getPoint( t2 );
  16989. var vec = pt2.clone().sub(pt1);
  16990. return vec.normalize();
  16991. };
  16992. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16993. var t = this.getUtoTmapping( u );
  16994. return this.getTangent( t );
  16995. };
  16996. /**************************************************************
  16997. * Utils
  16998. **************************************************************/
  16999. THREE.Curve.Utils = {
  17000. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17001. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17002. },
  17003. // Puay Bing, thanks for helping with this derivative!
  17004. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17005. return -3 * p0 * (1 - t) * (1 - t) +
  17006. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17007. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17008. 3 * t * t * p3;
  17009. },
  17010. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17011. // To check if my formulas are correct
  17012. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17013. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17014. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17015. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17016. return h00 + h10 + h01 + h11;
  17017. },
  17018. // Catmull-Rom
  17019. interpolate: function( p0, p1, p2, p3, t ) {
  17020. var v0 = ( p2 - p0 ) * 0.5;
  17021. var v1 = ( p3 - p1 ) * 0.5;
  17022. var t2 = t * t;
  17023. var t3 = t * t2;
  17024. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17025. }
  17026. };
  17027. // TODO: Transformation for Curves?
  17028. /**************************************************************
  17029. * 3D Curves
  17030. **************************************************************/
  17031. // A Factory method for creating new curve subclasses
  17032. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17033. constructor.prototype = Object.create( THREE.Curve.prototype );
  17034. constructor.prototype.getPoint = getPointFunc;
  17035. return constructor;
  17036. };
  17037. /**
  17038. * @author zz85 / http://www.lab4games.net/zz85/blog
  17039. *
  17040. **/
  17041. /**************************************************************
  17042. * Curved Path - a curve path is simply a array of connected
  17043. * curves, but retains the api of a curve
  17044. **************************************************************/
  17045. THREE.CurvePath = function () {
  17046. this.curves = [];
  17047. this.bends = [];
  17048. this.autoClose = false; // Automatically closes the path
  17049. };
  17050. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17051. THREE.CurvePath.prototype.add = function ( curve ) {
  17052. this.curves.push( curve );
  17053. };
  17054. THREE.CurvePath.prototype.checkConnection = function() {
  17055. // TODO
  17056. // If the ending of curve is not connected to the starting
  17057. // or the next curve, then, this is not a real path
  17058. };
  17059. THREE.CurvePath.prototype.closePath = function() {
  17060. // TODO Test
  17061. // and verify for vector3 (needs to implement equals)
  17062. // Add a line curve if start and end of lines are not connected
  17063. var startPoint = this.curves[0].getPoint(0);
  17064. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17065. if (!startPoint.equals(endPoint)) {
  17066. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17067. }
  17068. };
  17069. // To get accurate point with reference to
  17070. // entire path distance at time t,
  17071. // following has to be done:
  17072. // 1. Length of each sub path have to be known
  17073. // 2. Locate and identify type of curve
  17074. // 3. Get t for the curve
  17075. // 4. Return curve.getPointAt(t')
  17076. THREE.CurvePath.prototype.getPoint = function( t ) {
  17077. var d = t * this.getLength();
  17078. var curveLengths = this.getCurveLengths();
  17079. var i = 0, diff, curve;
  17080. // To think about boundaries points.
  17081. while ( i < curveLengths.length ) {
  17082. if ( curveLengths[ i ] >= d ) {
  17083. diff = curveLengths[ i ] - d;
  17084. curve = this.curves[ i ];
  17085. var u = 1 - diff / curve.getLength();
  17086. return curve.getPointAt( u );
  17087. break;
  17088. }
  17089. i ++;
  17090. }
  17091. return null;
  17092. // loop where sum != 0, sum > d , sum+1 <d
  17093. };
  17094. /*
  17095. THREE.CurvePath.prototype.getTangent = function( t ) {
  17096. };*/
  17097. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17098. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17099. // getPoint() depends on getLength
  17100. THREE.CurvePath.prototype.getLength = function() {
  17101. var lens = this.getCurveLengths();
  17102. return lens[ lens.length - 1 ];
  17103. };
  17104. // Compute lengths and cache them
  17105. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17106. THREE.CurvePath.prototype.getCurveLengths = function() {
  17107. // We use cache values if curves and cache array are same length
  17108. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17109. return this.cacheLengths;
  17110. };
  17111. // Get length of subsurve
  17112. // Push sums into cached array
  17113. var lengths = [], sums = 0;
  17114. var i, il = this.curves.length;
  17115. for ( i = 0; i < il; i ++ ) {
  17116. sums += this.curves[ i ].getLength();
  17117. lengths.push( sums );
  17118. }
  17119. this.cacheLengths = lengths;
  17120. return lengths;
  17121. };
  17122. // Returns min and max coordinates
  17123. THREE.CurvePath.prototype.getBoundingBox = function () {
  17124. var points = this.getPoints();
  17125. var maxX, maxY, maxZ;
  17126. var minX, minY, minZ;
  17127. maxX = maxY = Number.NEGATIVE_INFINITY;
  17128. minX = minY = Number.POSITIVE_INFINITY;
  17129. var p, i, il, sum;
  17130. var v3 = points[0] instanceof THREE.Vector3;
  17131. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17132. for ( i = 0, il = points.length; i < il; i ++ ) {
  17133. p = points[ i ];
  17134. if ( p.x > maxX ) maxX = p.x;
  17135. else if ( p.x < minX ) minX = p.x;
  17136. if ( p.y > maxY ) maxY = p.y;
  17137. else if ( p.y < minY ) minY = p.y;
  17138. if ( v3 ) {
  17139. if ( p.z > maxZ ) maxZ = p.z;
  17140. else if ( p.z < minZ ) minZ = p.z;
  17141. }
  17142. sum.add( p );
  17143. }
  17144. var ret = {
  17145. minX: minX,
  17146. minY: minY,
  17147. maxX: maxX,
  17148. maxY: maxY
  17149. };
  17150. if ( v3 ) {
  17151. ret.maxZ = maxZ;
  17152. ret.minZ = minZ;
  17153. }
  17154. return ret;
  17155. };
  17156. /**************************************************************
  17157. * Create Geometries Helpers
  17158. **************************************************************/
  17159. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17160. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17161. var pts = this.getPoints( divisions, true );
  17162. return this.createGeometry( pts );
  17163. };
  17164. // Generate geometry from equidistance sampling along the path
  17165. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17166. var pts = this.getSpacedPoints( divisions, true );
  17167. return this.createGeometry( pts );
  17168. };
  17169. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17170. var geometry = new THREE.Geometry();
  17171. for ( var i = 0; i < points.length; i ++ ) {
  17172. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17173. }
  17174. return geometry;
  17175. };
  17176. /**************************************************************
  17177. * Bend / Wrap Helper Methods
  17178. **************************************************************/
  17179. // Wrap path / Bend modifiers?
  17180. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17181. this.bends.push( bendpath );
  17182. };
  17183. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17184. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17185. var i, il;
  17186. if ( !bends ) {
  17187. bends = this.bends;
  17188. }
  17189. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17190. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17191. }
  17192. return oldPts;
  17193. };
  17194. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17195. var oldPts = this.getSpacedPoints( segments );
  17196. var i, il;
  17197. if ( !bends ) {
  17198. bends = this.bends;
  17199. }
  17200. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17201. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17202. }
  17203. return oldPts;
  17204. };
  17205. // This returns getPoints() bend/wrapped around the contour of a path.
  17206. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17207. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17208. var bounds = this.getBoundingBox();
  17209. var i, il, p, oldX, oldY, xNorm;
  17210. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17211. p = oldPts[ i ];
  17212. oldX = p.x;
  17213. oldY = p.y;
  17214. xNorm = oldX / bounds.maxX;
  17215. // If using actual distance, for length > path, requires line extrusions
  17216. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17217. xNorm = path.getUtoTmapping( xNorm, oldX );
  17218. // check for out of bounds?
  17219. var pathPt = path.getPoint( xNorm );
  17220. var normal = path.getTangent( xNorm );
  17221. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  17222. p.x = pathPt.x + normal.x;
  17223. p.y = pathPt.y + normal.y;
  17224. }
  17225. return oldPts;
  17226. };
  17227. /**
  17228. * @author alteredq / http://alteredqualia.com/
  17229. */
  17230. THREE.Gyroscope = function () {
  17231. THREE.Object3D.call( this );
  17232. };
  17233. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17234. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17235. this.matrixAutoUpdate && this.updateMatrix();
  17236. // update matrixWorld
  17237. if ( this.matrixWorldNeedsUpdate || force ) {
  17238. if ( this.parent ) {
  17239. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17240. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17241. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17242. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17243. } else {
  17244. this.matrixWorld.copy( this.matrix );
  17245. }
  17246. this.matrixWorldNeedsUpdate = false;
  17247. force = true;
  17248. }
  17249. // update children
  17250. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17251. this.children[ i ].updateMatrixWorld( force );
  17252. }
  17253. };
  17254. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17255. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17256. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17257. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17258. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17259. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17260. /**
  17261. * @author zz85 / http://www.lab4games.net/zz85/blog
  17262. * Creates free form 2d path using series of points, lines or curves.
  17263. *
  17264. **/
  17265. THREE.Path = function ( points ) {
  17266. THREE.CurvePath.call(this);
  17267. this.actions = [];
  17268. if ( points ) {
  17269. this.fromPoints( points );
  17270. }
  17271. };
  17272. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17273. THREE.PathActions = {
  17274. MOVE_TO: 'moveTo',
  17275. LINE_TO: 'lineTo',
  17276. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17277. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17278. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17279. ARC: 'arc', // Circle
  17280. ELLIPSE: 'ellipse'
  17281. };
  17282. // TODO Clean up PATH API
  17283. // Create path using straight lines to connect all points
  17284. // - vectors: array of Vector2
  17285. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17286. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17287. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17288. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17289. };
  17290. };
  17291. // startPath() endPath()?
  17292. THREE.Path.prototype.moveTo = function ( x, y ) {
  17293. var args = Array.prototype.slice.call( arguments );
  17294. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17295. };
  17296. THREE.Path.prototype.lineTo = function ( x, y ) {
  17297. var args = Array.prototype.slice.call( arguments );
  17298. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17299. var x0 = lastargs[ lastargs.length - 2 ];
  17300. var y0 = lastargs[ lastargs.length - 1 ];
  17301. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17302. this.curves.push( curve );
  17303. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17304. };
  17305. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  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.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17311. new THREE.Vector2( aCPx, aCPy ),
  17312. new THREE.Vector2( aX, aY ) );
  17313. this.curves.push( curve );
  17314. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17315. };
  17316. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17317. aCP2x, aCP2y,
  17318. aX, aY ) {
  17319. var args = Array.prototype.slice.call( arguments );
  17320. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17321. var x0 = lastargs[ lastargs.length - 2 ];
  17322. var y0 = lastargs[ lastargs.length - 1 ];
  17323. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17324. new THREE.Vector2( aCP1x, aCP1y ),
  17325. new THREE.Vector2( aCP2x, aCP2y ),
  17326. new THREE.Vector2( aX, aY ) );
  17327. this.curves.push( curve );
  17328. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17329. };
  17330. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17331. var args = Array.prototype.slice.call( arguments );
  17332. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17333. var x0 = lastargs[ lastargs.length - 2 ];
  17334. var y0 = lastargs[ lastargs.length - 1 ];
  17335. //---
  17336. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17337. Array.prototype.push.apply( npts, pts );
  17338. var curve = new THREE.SplineCurve( npts );
  17339. this.curves.push( curve );
  17340. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17341. };
  17342. // FUTURE: Change the API or follow canvas API?
  17343. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17344. aStartAngle, aEndAngle, aClockwise ) {
  17345. var lastargs = this.actions[ this.actions.length - 1].args;
  17346. var x0 = lastargs[ lastargs.length - 2 ];
  17347. var y0 = lastargs[ lastargs.length - 1 ];
  17348. this.absarc(aX + x0, aY + y0, aRadius,
  17349. aStartAngle, aEndAngle, aClockwise );
  17350. };
  17351. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17352. aStartAngle, aEndAngle, aClockwise ) {
  17353. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17354. };
  17355. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17356. aStartAngle, aEndAngle, aClockwise ) {
  17357. var lastargs = this.actions[ this.actions.length - 1].args;
  17358. var x0 = lastargs[ lastargs.length - 2 ];
  17359. var y0 = lastargs[ lastargs.length - 1 ];
  17360. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17361. aStartAngle, aEndAngle, aClockwise );
  17362. };
  17363. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17364. aStartAngle, aEndAngle, aClockwise ) {
  17365. var args = Array.prototype.slice.call( arguments );
  17366. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17367. aStartAngle, aEndAngle, aClockwise );
  17368. this.curves.push( curve );
  17369. var lastPoint = curve.getPoint(1);
  17370. args.push(lastPoint.x);
  17371. args.push(lastPoint.y);
  17372. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17373. };
  17374. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17375. if ( ! divisions ) divisions = 40;
  17376. var points = [];
  17377. for ( var i = 0; i < divisions; i ++ ) {
  17378. points.push( this.getPoint( i / divisions ) );
  17379. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17380. }
  17381. // if ( closedPath ) {
  17382. //
  17383. // points.push( points[ 0 ] );
  17384. //
  17385. // }
  17386. return points;
  17387. };
  17388. /* Return an array of vectors based on contour of the path */
  17389. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17390. if (this.useSpacedPoints) {
  17391. console.log('tata');
  17392. return this.getSpacedPoints( divisions, closedPath );
  17393. }
  17394. divisions = divisions || 12;
  17395. var points = [];
  17396. var i, il, item, action, args;
  17397. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17398. laste, j,
  17399. t, tx, ty;
  17400. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17401. item = this.actions[ i ];
  17402. action = item.action;
  17403. args = item.args;
  17404. switch( action ) {
  17405. case THREE.PathActions.MOVE_TO:
  17406. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17407. break;
  17408. case THREE.PathActions.LINE_TO:
  17409. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17410. break;
  17411. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17412. cpx = args[ 2 ];
  17413. cpy = args[ 3 ];
  17414. cpx1 = args[ 0 ];
  17415. cpy1 = args[ 1 ];
  17416. if ( points.length > 0 ) {
  17417. laste = points[ points.length - 1 ];
  17418. cpx0 = laste.x;
  17419. cpy0 = laste.y;
  17420. } else {
  17421. laste = this.actions[ i - 1 ].args;
  17422. cpx0 = laste[ laste.length - 2 ];
  17423. cpy0 = laste[ laste.length - 1 ];
  17424. }
  17425. for ( j = 1; j <= divisions; j ++ ) {
  17426. t = j / divisions;
  17427. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17428. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17429. points.push( new THREE.Vector2( tx, ty ) );
  17430. }
  17431. break;
  17432. case THREE.PathActions.BEZIER_CURVE_TO:
  17433. cpx = args[ 4 ];
  17434. cpy = args[ 5 ];
  17435. cpx1 = args[ 0 ];
  17436. cpy1 = args[ 1 ];
  17437. cpx2 = args[ 2 ];
  17438. cpy2 = args[ 3 ];
  17439. if ( points.length > 0 ) {
  17440. laste = points[ points.length - 1 ];
  17441. cpx0 = laste.x;
  17442. cpy0 = laste.y;
  17443. } else {
  17444. laste = this.actions[ i - 1 ].args;
  17445. cpx0 = laste[ laste.length - 2 ];
  17446. cpy0 = laste[ laste.length - 1 ];
  17447. }
  17448. for ( j = 1; j <= divisions; j ++ ) {
  17449. t = j / divisions;
  17450. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17451. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17452. points.push( new THREE.Vector2( tx, ty ) );
  17453. }
  17454. break;
  17455. case THREE.PathActions.CSPLINE_THRU:
  17456. laste = this.actions[ i - 1 ].args;
  17457. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17458. var spts = [ last ];
  17459. var n = divisions * args[ 0 ].length;
  17460. spts = spts.concat( args[ 0 ] );
  17461. var spline = new THREE.SplineCurve( spts );
  17462. for ( j = 1; j <= n; j ++ ) {
  17463. points.push( spline.getPointAt( j / n ) ) ;
  17464. }
  17465. break;
  17466. case THREE.PathActions.ARC:
  17467. var aX = args[ 0 ], aY = args[ 1 ],
  17468. aRadius = args[ 2 ],
  17469. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17470. aClockwise = !!args[ 5 ];
  17471. var deltaAngle = aEndAngle - aStartAngle;
  17472. var angle;
  17473. var tdivisions = divisions * 2;
  17474. for ( j = 1; j <= tdivisions; j ++ ) {
  17475. t = j / tdivisions;
  17476. if ( ! aClockwise ) {
  17477. t = 1 - t;
  17478. }
  17479. angle = aStartAngle + t * deltaAngle;
  17480. tx = aX + aRadius * Math.cos( angle );
  17481. ty = aY + aRadius * Math.sin( angle );
  17482. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17483. points.push( new THREE.Vector2( tx, ty ) );
  17484. }
  17485. //console.log(points);
  17486. break;
  17487. case THREE.PathActions.ELLIPSE:
  17488. var aX = args[ 0 ], aY = args[ 1 ],
  17489. xRadius = args[ 2 ],
  17490. yRadius = args[ 3 ],
  17491. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17492. aClockwise = !!args[ 6 ];
  17493. var deltaAngle = aEndAngle - aStartAngle;
  17494. var angle;
  17495. var tdivisions = divisions * 2;
  17496. for ( j = 1; j <= tdivisions; j ++ ) {
  17497. t = j / tdivisions;
  17498. if ( ! aClockwise ) {
  17499. t = 1 - t;
  17500. }
  17501. angle = aStartAngle + t * deltaAngle;
  17502. tx = aX + xRadius * Math.cos( angle );
  17503. ty = aY + yRadius * Math.sin( angle );
  17504. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17505. points.push( new THREE.Vector2( tx, ty ) );
  17506. }
  17507. //console.log(points);
  17508. break;
  17509. } // end switch
  17510. }
  17511. // Normalize to remove the closing point by default.
  17512. var lastPoint = points[ points.length - 1];
  17513. var EPSILON = 0.0000000001;
  17514. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17515. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17516. points.splice( points.length - 1, 1);
  17517. if ( closedPath ) {
  17518. points.push( points[ 0 ] );
  17519. }
  17520. return points;
  17521. };
  17522. // Breaks path into shapes
  17523. THREE.Path.prototype.toShapes = function( isCCW ) {
  17524. function isPointInsidePolygon( inPt, inPolygon ) {
  17525. var EPSILON = 0.0000000001;
  17526. var polyLen = inPolygon.length;
  17527. // inPt on polygon contour => immediate success or
  17528. // toggling of inside/outside at every single! intersection point of an edge
  17529. // with the horizontal line through inPt, left of inPt
  17530. // not counting lowerY endpoints of edges and whole edges on that line
  17531. var inside = false;
  17532. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  17533. var edgeLowPt = inPolygon[ p ];
  17534. var edgeHighPt = inPolygon[ q ];
  17535. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17536. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17537. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17538. if ( edgeDy < 0 ) {
  17539. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  17540. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  17541. }
  17542. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17543. if ( inPt.y == edgeLowPt.y ) {
  17544. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17545. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17546. } else {
  17547. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17548. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17549. if ( perpEdge < 0 ) continue;
  17550. inside = !inside; // true intersection left of inPt
  17551. }
  17552. } else { // parallel or colinear
  17553. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17554. // egde lies on the same horizontal line as inPt
  17555. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17556. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17557. // continue;
  17558. }
  17559. }
  17560. return inside;
  17561. }
  17562. var i, il, item, action, args;
  17563. var subPaths = [], lastPath = new THREE.Path();
  17564. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17565. item = this.actions[ i ];
  17566. args = item.args;
  17567. action = item.action;
  17568. if ( action == THREE.PathActions.MOVE_TO ) {
  17569. if ( lastPath.actions.length != 0 ) {
  17570. subPaths.push( lastPath );
  17571. lastPath = new THREE.Path();
  17572. }
  17573. }
  17574. lastPath[ action ].apply( lastPath, args );
  17575. }
  17576. if ( lastPath.actions.length != 0 ) {
  17577. subPaths.push( lastPath );
  17578. }
  17579. // console.log(subPaths);
  17580. if ( subPaths.length == 0 ) return [];
  17581. var solid, tmpPath, tmpShape, shapes = [];
  17582. if ( subPaths.length == 1) {
  17583. tmpPath = subPaths[0];
  17584. tmpShape = new THREE.Shape();
  17585. tmpShape.actions = tmpPath.actions;
  17586. tmpShape.curves = tmpPath.curves;
  17587. shapes.push( tmpShape );
  17588. return shapes;
  17589. }
  17590. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17591. holesFirst = isCCW ? !holesFirst : holesFirst;
  17592. // console.log("Holes first", holesFirst);
  17593. var betterShapeHoles = [];
  17594. var newShapes = [];
  17595. var newShapeHoles = [];
  17596. var mainIdx = 0;
  17597. var tmpPoints;
  17598. newShapes[mainIdx] = undefined;
  17599. newShapeHoles[mainIdx] = [];
  17600. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17601. tmpPath = subPaths[ i ];
  17602. tmpPoints = tmpPath.getPoints();
  17603. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17604. solid = isCCW ? !solid : solid;
  17605. if ( solid ) {
  17606. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  17607. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17608. newShapes[mainIdx].s.actions = tmpPath.actions;
  17609. newShapes[mainIdx].s.curves = tmpPath.curves;
  17610. if ( holesFirst ) mainIdx++;
  17611. newShapeHoles[mainIdx] = [];
  17612. //console.log('cw', i);
  17613. } else {
  17614. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17615. //console.log('ccw', i);
  17616. }
  17617. }
  17618. if ( newShapes.length > 1 ) {
  17619. var ambigious = false;
  17620. var toChange = [];
  17621. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17622. betterShapeHoles[sIdx] = [];
  17623. }
  17624. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17625. var sh = newShapes[sIdx];
  17626. var sho = newShapeHoles[sIdx];
  17627. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  17628. var ho = sho[hIdx];
  17629. var hole_unassigned = true;
  17630. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  17631. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17632. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17633. if ( hole_unassigned ) {
  17634. hole_unassigned = false;
  17635. betterShapeHoles[s2Idx].push( ho );
  17636. } else {
  17637. ambigious = true;
  17638. }
  17639. }
  17640. }
  17641. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17642. }
  17643. }
  17644. // console.log("ambigious: ", ambigious);
  17645. if ( toChange.length > 0 ) {
  17646. // console.log("to change: ", toChange);
  17647. if (! ambigious) newShapeHoles = betterShapeHoles;
  17648. }
  17649. }
  17650. var tmpHoles, j, jl;
  17651. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17652. tmpShape = newShapes[i].s;
  17653. shapes.push( tmpShape );
  17654. tmpHoles = newShapeHoles[i];
  17655. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17656. tmpShape.holes.push( tmpHoles[j].h );
  17657. }
  17658. }
  17659. //console.log("shape", shapes);
  17660. return shapes;
  17661. };
  17662. /**
  17663. * @author zz85 / http://www.lab4games.net/zz85/blog
  17664. * Defines a 2d shape plane using paths.
  17665. **/
  17666. // STEP 1 Create a path.
  17667. // STEP 2 Turn path into shape.
  17668. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17669. // STEP 3a - Extract points from each shape, turn to vertices
  17670. // STEP 3b - Triangulate each shape, add faces.
  17671. THREE.Shape = function () {
  17672. THREE.Path.apply( this, arguments );
  17673. this.holes = [];
  17674. };
  17675. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17676. // Convenience method to return ExtrudeGeometry
  17677. THREE.Shape.prototype.extrude = function ( options ) {
  17678. var extruded = new THREE.ExtrudeGeometry( this, options );
  17679. return extruded;
  17680. };
  17681. // Convenience method to return ShapeGeometry
  17682. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17683. var geometry = new THREE.ShapeGeometry( this, options );
  17684. return geometry;
  17685. };
  17686. // Get points of holes
  17687. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17688. var i, il = this.holes.length, holesPts = [];
  17689. for ( i = 0; i < il; i ++ ) {
  17690. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17691. }
  17692. return holesPts;
  17693. };
  17694. // Get points of holes (spaced by regular distance)
  17695. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17696. var i, il = this.holes.length, holesPts = [];
  17697. for ( i = 0; i < il; i ++ ) {
  17698. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17699. }
  17700. return holesPts;
  17701. };
  17702. // Get points of shape and holes (keypoints based on segments parameter)
  17703. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17704. return {
  17705. shape: this.getTransformedPoints( divisions ),
  17706. holes: this.getPointsHoles( divisions )
  17707. };
  17708. };
  17709. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17710. if (this.useSpacedPoints) {
  17711. return this.extractAllSpacedPoints(divisions);
  17712. }
  17713. return this.extractAllPoints(divisions);
  17714. };
  17715. //
  17716. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17717. //
  17718. // return {
  17719. //
  17720. // shape: this.transform( bend, divisions ),
  17721. // holes: this.getPointsHoles( divisions, bend )
  17722. //
  17723. // };
  17724. //
  17725. // };
  17726. // Get points of shape and holes (spaced by regular distance)
  17727. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17728. return {
  17729. shape: this.getTransformedSpacedPoints( divisions ),
  17730. holes: this.getSpacedPointsHoles( divisions )
  17731. };
  17732. };
  17733. /**************************************************************
  17734. * Utils
  17735. **************************************************************/
  17736. THREE.Shape.Utils = {
  17737. triangulateShape: function ( contour, holes ) {
  17738. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17739. // inOtherPt needs to be colinear to the inSegment
  17740. if ( inSegPt1.x != inSegPt2.x ) {
  17741. if ( inSegPt1.x < inSegPt2.x ) {
  17742. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17743. } else {
  17744. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17745. }
  17746. } else {
  17747. if ( inSegPt1.y < inSegPt2.y ) {
  17748. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17749. } else {
  17750. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17751. }
  17752. }
  17753. }
  17754. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17755. var EPSILON = 0.0000000001;
  17756. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17757. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17758. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17759. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17760. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17761. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17762. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17763. var perpSeg2;
  17764. if ( limit > 0 ) {
  17765. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17766. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17767. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17768. } else {
  17769. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17770. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17771. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17772. }
  17773. // i.e. to reduce rounding errors
  17774. // intersection at endpoint of segment#1?
  17775. if ( perpSeg2 == 0 ) {
  17776. if ( ( inExcludeAdjacentSegs ) &&
  17777. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17778. return [ inSeg1Pt1 ];
  17779. }
  17780. if ( perpSeg2 == limit ) {
  17781. if ( ( inExcludeAdjacentSegs ) &&
  17782. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17783. return [ inSeg1Pt2 ];
  17784. }
  17785. // intersection at endpoint of segment#2?
  17786. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17787. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17788. // return real intersection point
  17789. var factorSeg1 = perpSeg2 / limit;
  17790. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17791. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17792. } else { // parallel or colinear
  17793. if ( ( perpSeg1 != 0 ) ||
  17794. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17795. // they are collinear or degenerate
  17796. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17797. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17798. // both segments are points
  17799. if ( seg1Pt && seg2Pt ) {
  17800. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17801. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17802. return [ inSeg1Pt1 ]; // they are the same point
  17803. }
  17804. // segment#1 is a single point
  17805. if ( seg1Pt ) {
  17806. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17807. return [ inSeg1Pt1 ];
  17808. }
  17809. // segment#2 is a single point
  17810. if ( seg2Pt ) {
  17811. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17812. return [ inSeg2Pt1 ];
  17813. }
  17814. // they are collinear segments, which might overlap
  17815. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17816. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17817. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17818. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17819. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17820. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17821. } else {
  17822. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17823. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17824. }
  17825. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17826. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17827. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17828. } else {
  17829. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17830. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17831. }
  17832. } else { // the segments are on a vertical line
  17833. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17834. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17835. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17836. } else {
  17837. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17838. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17839. }
  17840. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17841. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17842. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17843. } else {
  17844. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17845. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17846. }
  17847. }
  17848. if ( seg1minVal <= seg2minVal ) {
  17849. if ( seg1maxVal < seg2minVal ) return [];
  17850. if ( seg1maxVal == seg2minVal ) {
  17851. if ( inExcludeAdjacentSegs ) return [];
  17852. return [ seg2min ];
  17853. }
  17854. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17855. return [ seg2min, seg2max ];
  17856. } else {
  17857. if ( seg1minVal > seg2maxVal ) return [];
  17858. if ( seg1minVal == seg2maxVal ) {
  17859. if ( inExcludeAdjacentSegs ) return [];
  17860. return [ seg1min ];
  17861. }
  17862. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17863. return [ seg1min, seg2max ];
  17864. }
  17865. }
  17866. }
  17867. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17868. // The order of legs is important
  17869. var EPSILON = 0.0000000001;
  17870. // translation of all points, so that Vertex is at (0,0)
  17871. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17872. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17873. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17874. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17875. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17876. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17877. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17878. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17879. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17880. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17881. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17882. } else { // main angle > 180 deg.
  17883. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17884. }
  17885. } else { // angle == 180 deg.
  17886. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17887. return ( from2otherAngle > 0 );
  17888. }
  17889. }
  17890. function removeHoles( contour, holes ) {
  17891. var shape = contour.concat(); // work on this shape
  17892. var hole;
  17893. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17894. // Check if hole point lies within angle around shape point
  17895. var lastShapeIdx = shape.length - 1;
  17896. var prevShapeIdx = inShapeIdx - 1;
  17897. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17898. var nextShapeIdx = inShapeIdx + 1;
  17899. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17900. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17901. if (! insideAngle ) {
  17902. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17903. return false;
  17904. }
  17905. // Check if shape point lies within angle around hole point
  17906. var lastHoleIdx = hole.length - 1;
  17907. var prevHoleIdx = inHoleIdx - 1;
  17908. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17909. var nextHoleIdx = inHoleIdx + 1;
  17910. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17911. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17912. if (! insideAngle ) {
  17913. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17914. return false;
  17915. }
  17916. return true;
  17917. }
  17918. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17919. // checks for intersections with shape edges
  17920. var sIdx, nextIdx, intersection;
  17921. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  17922. nextIdx = sIdx+1; nextIdx %= shape.length;
  17923. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17924. if ( intersection.length > 0 ) return true;
  17925. }
  17926. return false;
  17927. }
  17928. var indepHoles = [];
  17929. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17930. // checks for intersections with hole edges
  17931. var ihIdx, chkHole,
  17932. hIdx, nextIdx, intersection;
  17933. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  17934. chkHole = holes[indepHoles[ihIdx]];
  17935. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  17936. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  17937. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17938. if ( intersection.length > 0 ) return true;
  17939. }
  17940. }
  17941. return false;
  17942. }
  17943. var holeIndex, shapeIndex,
  17944. shapePt, holePt,
  17945. holeIdx, cutKey, failedCuts = [],
  17946. tmpShape1, tmpShape2,
  17947. tmpHole1, tmpHole2;
  17948. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17949. indepHoles.push( h );
  17950. }
  17951. var counter = indepHoles.length * 2;
  17952. while ( indepHoles.length > 0 ) {
  17953. counter --;
  17954. if ( counter < 0 ) {
  17955. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17956. break;
  17957. }
  17958. // search for shape-vertex and hole-vertex,
  17959. // which can be connected without intersections
  17960. for ( shapeIndex = 0; shapeIndex < shape.length; shapeIndex++ ) {
  17961. shapePt = shape[ shapeIndex ];
  17962. holeIndex = -1;
  17963. // search for hole which can be reached without intersections
  17964. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17965. holeIdx = indepHoles[h];
  17966. // prevent multiple checks
  17967. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17968. if ( failedCuts[cutKey] !== undefined ) continue;
  17969. hole = holes[holeIdx];
  17970. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17971. holePt = hole[ h2 ];
  17972. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17973. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17974. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17975. holeIndex = h2;
  17976. indepHoles.splice(h,1);
  17977. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  17978. tmpShape2 = shape.slice( shapeIndex );
  17979. tmpHole1 = hole.slice( holeIndex );
  17980. tmpHole2 = hole.slice( 0, holeIndex+1 );
  17981. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17982. // Debug only, to show the selected cuts
  17983. // glob_CutLines.push( [ shapePt, holePt ] );
  17984. break;
  17985. }
  17986. if ( holeIndex >= 0 ) break; // hole-vertex found
  17987. failedCuts[cutKey] = true; // remember failure
  17988. }
  17989. if ( holeIndex >= 0 ) break; // hole-vertex found
  17990. }
  17991. }
  17992. return shape; /* shape with no holes */
  17993. }
  17994. var i, il, f, face,
  17995. key, index,
  17996. allPointsMap = {};
  17997. // 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.
  17998. var allpoints = contour.concat();
  17999. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18000. Array.prototype.push.apply( allpoints, holes[h] );
  18001. }
  18002. //console.log( "allpoints",allpoints, allpoints.length );
  18003. // prepare all points map
  18004. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  18005. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  18006. if ( allPointsMap[ key ] !== undefined ) {
  18007. console.log( "Duplicate point", key );
  18008. }
  18009. allPointsMap[ key ] = i;
  18010. }
  18011. // remove holes by cutting paths to holes and adding them to the shape
  18012. var shapeWithoutHoles = removeHoles( contour, holes );
  18013. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  18014. //console.log( "triangles",triangles, triangles.length );
  18015. // check all face vertices against all points map
  18016. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  18017. face = triangles[ i ];
  18018. for ( f = 0; f < 3; f ++ ) {
  18019. key = face[ f ].x + ":" + face[ f ].y;
  18020. index = allPointsMap[ key ];
  18021. if ( index !== undefined ) {
  18022. face[ f ] = index;
  18023. }
  18024. }
  18025. }
  18026. return triangles.concat();
  18027. },
  18028. isClockWise: function ( pts ) {
  18029. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  18030. },
  18031. // Bezier Curves formulas obtained from
  18032. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18033. // Quad Bezier Functions
  18034. b2p0: function ( t, p ) {
  18035. var k = 1 - t;
  18036. return k * k * p;
  18037. },
  18038. b2p1: function ( t, p ) {
  18039. return 2 * ( 1 - t ) * t * p;
  18040. },
  18041. b2p2: function ( t, p ) {
  18042. return t * t * p;
  18043. },
  18044. b2: function ( t, p0, p1, p2 ) {
  18045. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  18046. },
  18047. // Cubic Bezier Functions
  18048. b3p0: function ( t, p ) {
  18049. var k = 1 - t;
  18050. return k * k * k * p;
  18051. },
  18052. b3p1: function ( t, p ) {
  18053. var k = 1 - t;
  18054. return 3 * k * k * t * p;
  18055. },
  18056. b3p2: function ( t, p ) {
  18057. var k = 1 - t;
  18058. return 3 * k * t * t * p;
  18059. },
  18060. b3p3: function ( t, p ) {
  18061. return t * t * t * p;
  18062. },
  18063. b3: function ( t, p0, p1, p2, p3 ) {
  18064. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  18065. }
  18066. };
  18067. /**************************************************************
  18068. * Line
  18069. **************************************************************/
  18070. THREE.LineCurve = function ( v1, v2 ) {
  18071. this.v1 = v1;
  18072. this.v2 = v2;
  18073. };
  18074. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  18075. THREE.LineCurve.prototype.getPoint = function ( t ) {
  18076. var point = this.v2.clone().sub(this.v1);
  18077. point.multiplyScalar( t ).add( this.v1 );
  18078. return point;
  18079. };
  18080. // Line curve is linear, so we can overwrite default getPointAt
  18081. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  18082. return this.getPoint( u );
  18083. };
  18084. THREE.LineCurve.prototype.getTangent = function( t ) {
  18085. var tangent = this.v2.clone().sub(this.v1);
  18086. return tangent.normalize();
  18087. };
  18088. /**************************************************************
  18089. * Quadratic Bezier curve
  18090. **************************************************************/
  18091. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  18092. this.v0 = v0;
  18093. this.v1 = v1;
  18094. this.v2 = v2;
  18095. };
  18096. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18097. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18098. var tx, ty;
  18099. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18100. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18101. return new THREE.Vector2( tx, ty );
  18102. };
  18103. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18104. var tx, ty;
  18105. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  18106. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  18107. // returns unit vector
  18108. var tangent = new THREE.Vector2( tx, ty );
  18109. tangent.normalize();
  18110. return tangent;
  18111. };
  18112. /**************************************************************
  18113. * Cubic Bezier curve
  18114. **************************************************************/
  18115. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  18116. this.v0 = v0;
  18117. this.v1 = v1;
  18118. this.v2 = v2;
  18119. this.v3 = v3;
  18120. };
  18121. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18122. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  18123. var tx, ty;
  18124. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18125. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18126. return new THREE.Vector2( tx, ty );
  18127. };
  18128. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18129. var tx, ty;
  18130. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18131. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18132. var tangent = new THREE.Vector2( tx, ty );
  18133. tangent.normalize();
  18134. return tangent;
  18135. };
  18136. /**************************************************************
  18137. * Spline curve
  18138. **************************************************************/
  18139. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18140. this.points = (points == undefined) ? [] : points;
  18141. };
  18142. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18143. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18144. var v = new THREE.Vector2();
  18145. var c = [];
  18146. var points = this.points, point, intPoint, weight;
  18147. point = ( points.length - 1 ) * t;
  18148. intPoint = Math.floor( point );
  18149. weight = point - intPoint;
  18150. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18151. c[ 1 ] = intPoint;
  18152. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18153. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18154. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18155. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18156. return v;
  18157. };
  18158. /**************************************************************
  18159. * Ellipse curve
  18160. **************************************************************/
  18161. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  18162. this.aX = aX;
  18163. this.aY = aY;
  18164. this.xRadius = xRadius;
  18165. this.yRadius = yRadius;
  18166. this.aStartAngle = aStartAngle;
  18167. this.aEndAngle = aEndAngle;
  18168. this.aClockwise = aClockwise;
  18169. };
  18170. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18171. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18172. var angle;
  18173. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18174. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  18175. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  18176. if ( this.aClockwise === true ) {
  18177. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  18178. } else {
  18179. angle = this.aStartAngle + t * deltaAngle;
  18180. }
  18181. var tx = this.aX + this.xRadius * Math.cos( angle );
  18182. var ty = this.aY + this.yRadius * Math.sin( angle );
  18183. return new THREE.Vector2( tx, ty );
  18184. };
  18185. /**************************************************************
  18186. * Arc curve
  18187. **************************************************************/
  18188. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18189. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18190. };
  18191. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18192. /**************************************************************
  18193. * Line3D
  18194. **************************************************************/
  18195. THREE.LineCurve3 = THREE.Curve.create(
  18196. function ( v1, v2 ) {
  18197. this.v1 = v1;
  18198. this.v2 = v2;
  18199. },
  18200. function ( t ) {
  18201. var r = new THREE.Vector3();
  18202. r.subVectors( this.v2, this.v1 ); // diff
  18203. r.multiplyScalar( t );
  18204. r.add( this.v1 );
  18205. return r;
  18206. }
  18207. );
  18208. /**************************************************************
  18209. * Quadratic Bezier 3D curve
  18210. **************************************************************/
  18211. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18212. function ( v0, v1, v2 ) {
  18213. this.v0 = v0;
  18214. this.v1 = v1;
  18215. this.v2 = v2;
  18216. },
  18217. function ( t ) {
  18218. var tx, ty, tz;
  18219. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18220. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18221. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18222. return new THREE.Vector3( tx, ty, tz );
  18223. }
  18224. );
  18225. /**************************************************************
  18226. * Cubic Bezier 3D curve
  18227. **************************************************************/
  18228. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18229. function ( v0, v1, v2, v3 ) {
  18230. this.v0 = v0;
  18231. this.v1 = v1;
  18232. this.v2 = v2;
  18233. this.v3 = v3;
  18234. },
  18235. function ( t ) {
  18236. var tx, ty, tz;
  18237. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18238. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18239. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18240. return new THREE.Vector3( tx, ty, tz );
  18241. }
  18242. );
  18243. /**************************************************************
  18244. * Spline 3D curve
  18245. **************************************************************/
  18246. THREE.SplineCurve3 = THREE.Curve.create(
  18247. function ( points /* array of Vector3 */) {
  18248. this.points = (points == undefined) ? [] : points;
  18249. },
  18250. function ( t ) {
  18251. var v = new THREE.Vector3();
  18252. var c = [];
  18253. var points = this.points, point, intPoint, weight;
  18254. point = ( points.length - 1 ) * t;
  18255. intPoint = Math.floor( point );
  18256. weight = point - intPoint;
  18257. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18258. c[ 1 ] = intPoint;
  18259. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18260. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18261. var pt0 = points[ c[0] ],
  18262. pt1 = points[ c[1] ],
  18263. pt2 = points[ c[2] ],
  18264. pt3 = points[ c[3] ];
  18265. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18266. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18267. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18268. return v;
  18269. }
  18270. );
  18271. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18272. // var v = new THREE.Vector3();
  18273. // var c = [];
  18274. // var points = this.points, point, intPoint, weight;
  18275. // point = ( points.length - 1 ) * t;
  18276. // intPoint = Math.floor( point );
  18277. // weight = point - intPoint;
  18278. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18279. // c[ 1 ] = intPoint;
  18280. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18281. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18282. // var pt0 = points[ c[0] ],
  18283. // pt1 = points[ c[1] ],
  18284. // pt2 = points[ c[2] ],
  18285. // pt3 = points[ c[3] ];
  18286. // // t = weight;
  18287. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18288. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18289. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18290. // return v;
  18291. // }
  18292. /**************************************************************
  18293. * Closed Spline 3D curve
  18294. **************************************************************/
  18295. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18296. function ( points /* array of Vector3 */) {
  18297. this.points = (points == undefined) ? [] : points;
  18298. },
  18299. function ( t ) {
  18300. var v = new THREE.Vector3();
  18301. var c = [];
  18302. var points = this.points, point, intPoint, weight;
  18303. point = ( points.length - 0 ) * t;
  18304. // This needs to be from 0-length +1
  18305. intPoint = Math.floor( point );
  18306. weight = point - intPoint;
  18307. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18308. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18309. c[ 1 ] = ( intPoint ) % points.length;
  18310. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18311. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18312. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18313. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18314. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18315. return v;
  18316. }
  18317. );
  18318. /**
  18319. * @author mikael emtinger / http://gomo.se/
  18320. */
  18321. THREE.AnimationHandler = (function() {
  18322. var playing = [];
  18323. var library = {};
  18324. var that = {};
  18325. //--- update ---
  18326. that.update = function( deltaTimeMS ) {
  18327. for( var i = 0; i < playing.length; i ++ )
  18328. playing[ i ].update( deltaTimeMS );
  18329. };
  18330. //--- add ---
  18331. that.addToUpdate = function( animation ) {
  18332. if ( playing.indexOf( animation ) === -1 )
  18333. playing.push( animation );
  18334. };
  18335. //--- remove ---
  18336. that.removeFromUpdate = function( animation ) {
  18337. var index = playing.indexOf( animation );
  18338. if( index !== -1 )
  18339. playing.splice( index, 1 );
  18340. };
  18341. //--- add ---
  18342. that.add = function( data ) {
  18343. if ( library[ data.name ] !== undefined )
  18344. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18345. library[ data.name ] = data;
  18346. initData( data );
  18347. };
  18348. //--- get ---
  18349. that.get = function( name ) {
  18350. if ( typeof name === "string" ) {
  18351. if ( library[ name ] ) {
  18352. return library[ name ];
  18353. } else {
  18354. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18355. return null;
  18356. }
  18357. } else {
  18358. // todo: add simple tween library
  18359. }
  18360. };
  18361. //--- parse ---
  18362. that.parse = function( root ) {
  18363. // setup hierarchy
  18364. var hierarchy = [];
  18365. if ( root instanceof THREE.SkinnedMesh ) {
  18366. for( var b = 0; b < root.bones.length; b++ ) {
  18367. hierarchy.push( root.bones[ b ] );
  18368. }
  18369. } else {
  18370. parseRecurseHierarchy( root, hierarchy );
  18371. }
  18372. return hierarchy;
  18373. };
  18374. var parseRecurseHierarchy = function( root, hierarchy ) {
  18375. hierarchy.push( root );
  18376. for( var c = 0; c < root.children.length; c++ )
  18377. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18378. }
  18379. //--- init data ---
  18380. var initData = function( data ) {
  18381. if( data.initialized === true )
  18382. return;
  18383. // loop through all keys
  18384. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18385. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18386. // remove minus times
  18387. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18388. data.hierarchy[ h ].keys[ k ].time = 0;
  18389. // create quaternions
  18390. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18391. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18392. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18393. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18394. }
  18395. }
  18396. // prepare morph target keys
  18397. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18398. // get all used
  18399. var usedMorphTargets = {};
  18400. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18401. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18402. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18403. usedMorphTargets[ morphTargetName ] = -1;
  18404. }
  18405. }
  18406. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18407. // set all used on all frames
  18408. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18409. var influences = {};
  18410. for ( var morphTargetName in usedMorphTargets ) {
  18411. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18412. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18413. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18414. break;
  18415. }
  18416. }
  18417. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18418. influences[ morphTargetName ] = 0;
  18419. }
  18420. }
  18421. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18422. }
  18423. }
  18424. // remove all keys that are on the same time
  18425. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18426. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18427. data.hierarchy[ h ].keys.splice( k, 1 );
  18428. k --;
  18429. }
  18430. }
  18431. // set index
  18432. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18433. data.hierarchy[ h ].keys[ k ].index = k;
  18434. }
  18435. }
  18436. // done
  18437. data.initialized = true;
  18438. };
  18439. // interpolation types
  18440. that.LINEAR = 0;
  18441. that.CATMULLROM = 1;
  18442. that.CATMULLROM_FORWARD = 2;
  18443. return that;
  18444. }());
  18445. /**
  18446. * @author mikael emtinger / http://gomo.se/
  18447. * @author mrdoob / http://mrdoob.com/
  18448. * @author alteredq / http://alteredqualia.com/
  18449. */
  18450. THREE.Animation = function ( root, name ) {
  18451. this.root = root;
  18452. this.data = THREE.AnimationHandler.get( name );
  18453. this.hierarchy = THREE.AnimationHandler.parse( root );
  18454. this.currentTime = 0;
  18455. this.timeScale = 1;
  18456. this.isPlaying = false;
  18457. this.isPaused = true;
  18458. this.loop = true;
  18459. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18460. };
  18461. THREE.Animation.prototype.play = function ( startTime ) {
  18462. this.currentTime = startTime !== undefined ? startTime : 0;
  18463. if ( this.isPlaying === false ) {
  18464. this.isPlaying = true;
  18465. this.reset();
  18466. this.update( 0 );
  18467. }
  18468. this.isPaused = false;
  18469. THREE.AnimationHandler.addToUpdate( this );
  18470. };
  18471. THREE.Animation.prototype.pause = function() {
  18472. if ( this.isPaused === true ) {
  18473. THREE.AnimationHandler.addToUpdate( this );
  18474. } else {
  18475. THREE.AnimationHandler.removeFromUpdate( this );
  18476. }
  18477. this.isPaused = !this.isPaused;
  18478. };
  18479. THREE.Animation.prototype.stop = function() {
  18480. this.isPlaying = false;
  18481. this.isPaused = false;
  18482. THREE.AnimationHandler.removeFromUpdate( this );
  18483. };
  18484. THREE.Animation.prototype.reset = function () {
  18485. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18486. var object = this.hierarchy[ h ];
  18487. object.matrixAutoUpdate = true;
  18488. if ( object.animationCache === undefined ) {
  18489. object.animationCache = {};
  18490. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18491. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18492. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18493. }
  18494. var prevKey = object.animationCache.prevKey;
  18495. var nextKey = object.animationCache.nextKey;
  18496. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18497. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18498. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18499. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18500. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18501. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18502. }
  18503. };
  18504. THREE.Animation.prototype.update = (function(){
  18505. var points = [];
  18506. var target = new THREE.Vector3();
  18507. // Catmull-Rom spline
  18508. var interpolateCatmullRom = function ( points, scale ) {
  18509. var c = [], v3 = [],
  18510. point, intPoint, weight, w2, w3,
  18511. pa, pb, pc, pd;
  18512. point = ( points.length - 1 ) * scale;
  18513. intPoint = Math.floor( point );
  18514. weight = point - intPoint;
  18515. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18516. c[ 1 ] = intPoint;
  18517. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18518. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18519. pa = points[ c[ 0 ] ];
  18520. pb = points[ c[ 1 ] ];
  18521. pc = points[ c[ 2 ] ];
  18522. pd = points[ c[ 3 ] ];
  18523. w2 = weight * weight;
  18524. w3 = weight * w2;
  18525. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18526. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18527. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18528. return v3;
  18529. };
  18530. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18531. var v0 = ( p2 - p0 ) * 0.5,
  18532. v1 = ( p3 - p1 ) * 0.5;
  18533. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18534. };
  18535. return function ( delta ) {
  18536. if ( this.isPlaying === false ) return;
  18537. this.currentTime += delta * this.timeScale;
  18538. //
  18539. var vector;
  18540. var types = [ "pos", "rot", "scl" ];
  18541. var duration = this.data.length;
  18542. if ( this.loop === true && this.currentTime > duration ) {
  18543. this.currentTime %= duration;
  18544. this.reset();
  18545. } else if ( this.loop === false && this.currentTime > duration ) {
  18546. this.stop();
  18547. return;
  18548. }
  18549. this.currentTime = Math.min( this.currentTime, duration );
  18550. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18551. var object = this.hierarchy[ h ];
  18552. var animationCache = object.animationCache;
  18553. // loop through pos/rot/scl
  18554. for ( var t = 0; t < 3; t ++ ) {
  18555. // get keys
  18556. var type = types[ t ];
  18557. var prevKey = animationCache.prevKey[ type ];
  18558. var nextKey = animationCache.nextKey[ type ];
  18559. if ( nextKey.time <= this.currentTime ) {
  18560. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18561. nextKey = this.getNextKeyWith( type, h, 1 );
  18562. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18563. prevKey = nextKey;
  18564. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18565. }
  18566. animationCache.prevKey[ type ] = prevKey;
  18567. animationCache.nextKey[ type ] = nextKey;
  18568. }
  18569. object.matrixAutoUpdate = true;
  18570. object.matrixWorldNeedsUpdate = true;
  18571. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18572. var prevXYZ = prevKey[ type ];
  18573. var nextXYZ = nextKey[ type ];
  18574. if ( scale < 0 ) scale = 0;
  18575. if ( scale > 1 ) scale = 1;
  18576. // interpolate
  18577. if ( type === "pos" ) {
  18578. vector = object.position;
  18579. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18580. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18581. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18582. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18583. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18584. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18585. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18586. points[ 1 ] = prevXYZ;
  18587. points[ 2 ] = nextXYZ;
  18588. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18589. scale = scale * 0.33 + 0.33;
  18590. var currentPoint = interpolateCatmullRom( points, scale );
  18591. vector.x = currentPoint[ 0 ];
  18592. vector.y = currentPoint[ 1 ];
  18593. vector.z = currentPoint[ 2 ];
  18594. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18595. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  18596. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18597. target.sub( vector );
  18598. target.y = 0;
  18599. target.normalize();
  18600. var angle = Math.atan2( target.x, target.z );
  18601. object.rotation.set( 0, angle, 0 );
  18602. }
  18603. }
  18604. } else if ( type === "rot" ) {
  18605. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18606. } else if ( type === "scl" ) {
  18607. vector = object.scale;
  18608. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18609. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18610. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18611. }
  18612. }
  18613. }
  18614. };
  18615. })();
  18616. // Get next key with
  18617. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18618. var keys = this.data.hierarchy[ h ].keys;
  18619. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18620. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18621. key = key < keys.length - 1 ? key : keys.length - 1;
  18622. } else {
  18623. key = key % keys.length;
  18624. }
  18625. for ( ; key < keys.length; key++ ) {
  18626. if ( keys[ key ][ type ] !== undefined ) {
  18627. return keys[ key ];
  18628. }
  18629. }
  18630. return this.data.hierarchy[ h ].keys[ 0 ];
  18631. };
  18632. // Get previous key with
  18633. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18634. var keys = this.data.hierarchy[ h ].keys;
  18635. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18636. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18637. key = key > 0 ? key : 0;
  18638. } else {
  18639. key = key >= 0 ? key : key + keys.length;
  18640. }
  18641. for ( ; key >= 0; key -- ) {
  18642. if ( keys[ key ][ type ] !== undefined ) {
  18643. return keys[ key ];
  18644. }
  18645. }
  18646. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18647. };
  18648. /**
  18649. * @author mikael emtinger / http://gomo.se/
  18650. * @author mrdoob / http://mrdoob.com/
  18651. * @author alteredq / http://alteredqualia.com/
  18652. * @author khang duong
  18653. * @author erik kitson
  18654. */
  18655. THREE.KeyFrameAnimation = function ( root, data ) {
  18656. this.root = root;
  18657. this.data = THREE.AnimationHandler.get( data );
  18658. this.hierarchy = THREE.AnimationHandler.parse( root );
  18659. this.currentTime = 0;
  18660. this.timeScale = 0.001;
  18661. this.isPlaying = false;
  18662. this.isPaused = true;
  18663. this.loop = true;
  18664. // initialize to first keyframes
  18665. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18666. var keys = this.data.hierarchy[h].keys,
  18667. sids = this.data.hierarchy[h].sids,
  18668. obj = this.hierarchy[h];
  18669. if ( keys.length && sids ) {
  18670. for ( var s = 0; s < sids.length; s++ ) {
  18671. var sid = sids[ s ],
  18672. next = this.getNextKeyWith( sid, h, 0 );
  18673. if ( next ) {
  18674. next.apply( sid );
  18675. }
  18676. }
  18677. obj.matrixAutoUpdate = false;
  18678. this.data.hierarchy[h].node.updateMatrix();
  18679. obj.matrixWorldNeedsUpdate = true;
  18680. }
  18681. }
  18682. };
  18683. // Play
  18684. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18685. this.currentTime = startTime !== undefined ? startTime : 0;
  18686. if ( this.isPlaying === false ) {
  18687. this.isPlaying = true;
  18688. // reset key cache
  18689. var h, hl = this.hierarchy.length,
  18690. object,
  18691. node;
  18692. for ( h = 0; h < hl; h++ ) {
  18693. object = this.hierarchy[ h ];
  18694. node = this.data.hierarchy[ h ];
  18695. if ( node.animationCache === undefined ) {
  18696. node.animationCache = {};
  18697. node.animationCache.prevKey = null;
  18698. node.animationCache.nextKey = null;
  18699. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18700. }
  18701. var keys = this.data.hierarchy[h].keys;
  18702. if (keys.length) {
  18703. node.animationCache.prevKey = keys[ 0 ];
  18704. node.animationCache.nextKey = keys[ 1 ];
  18705. this.startTime = Math.min( keys[0].time, this.startTime );
  18706. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18707. }
  18708. }
  18709. this.update( 0 );
  18710. }
  18711. this.isPaused = false;
  18712. THREE.AnimationHandler.addToUpdate( this );
  18713. };
  18714. // Pause
  18715. THREE.KeyFrameAnimation.prototype.pause = function() {
  18716. if( this.isPaused ) {
  18717. THREE.AnimationHandler.addToUpdate( this );
  18718. } else {
  18719. THREE.AnimationHandler.removeFromUpdate( this );
  18720. }
  18721. this.isPaused = !this.isPaused;
  18722. };
  18723. // Stop
  18724. THREE.KeyFrameAnimation.prototype.stop = function() {
  18725. this.isPlaying = false;
  18726. this.isPaused = false;
  18727. THREE.AnimationHandler.removeFromUpdate( this );
  18728. // reset JIT matrix and remove cache
  18729. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18730. var obj = this.hierarchy[ h ];
  18731. var node = this.data.hierarchy[ h ];
  18732. if ( node.animationCache !== undefined ) {
  18733. var original = node.animationCache.originalMatrix;
  18734. if( obj instanceof THREE.Bone ) {
  18735. original.copy( obj.skinMatrix );
  18736. obj.skinMatrix = original;
  18737. } else {
  18738. original.copy( obj.matrix );
  18739. obj.matrix = original;
  18740. }
  18741. delete node.animationCache;
  18742. }
  18743. }
  18744. };
  18745. // Update
  18746. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18747. if ( this.isPlaying === false ) return;
  18748. this.currentTime += delta * this.timeScale;
  18749. //
  18750. var duration = this.data.length;
  18751. if ( this.loop === true && this.currentTime > duration ) {
  18752. this.currentTime %= duration;
  18753. }
  18754. this.currentTime = Math.min( this.currentTime, duration );
  18755. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18756. var object = this.hierarchy[ h ];
  18757. var node = this.data.hierarchy[ h ];
  18758. var keys = node.keys,
  18759. animationCache = node.animationCache;
  18760. if ( keys.length ) {
  18761. var prevKey = animationCache.prevKey;
  18762. var nextKey = animationCache.nextKey;
  18763. if ( nextKey.time <= this.currentTime ) {
  18764. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18765. prevKey = nextKey;
  18766. nextKey = keys[ prevKey.index + 1 ];
  18767. }
  18768. animationCache.prevKey = prevKey;
  18769. animationCache.nextKey = nextKey;
  18770. }
  18771. if ( nextKey.time >= this.currentTime ) {
  18772. prevKey.interpolate( nextKey, this.currentTime );
  18773. } else {
  18774. prevKey.interpolate( nextKey, nextKey.time );
  18775. }
  18776. this.data.hierarchy[ h ].node.updateMatrix();
  18777. object.matrixWorldNeedsUpdate = true;
  18778. }
  18779. }
  18780. };
  18781. // Get next key with
  18782. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18783. var keys = this.data.hierarchy[ h ].keys;
  18784. key = key % keys.length;
  18785. for ( ; key < keys.length; key++ ) {
  18786. if ( keys[ key ].hasTarget( sid ) ) {
  18787. return keys[ key ];
  18788. }
  18789. }
  18790. return keys[ 0 ];
  18791. };
  18792. // Get previous key with
  18793. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18794. var keys = this.data.hierarchy[ h ].keys;
  18795. key = key >= 0 ? key : key + keys.length;
  18796. for ( ; key >= 0; key-- ) {
  18797. if ( keys[ key ].hasTarget( sid ) ) {
  18798. return keys[ key ];
  18799. }
  18800. }
  18801. return keys[ keys.length - 1 ];
  18802. };
  18803. /**
  18804. * @author mrdoob / http://mrdoob.com
  18805. */
  18806. THREE.MorphAnimation = function ( mesh ) {
  18807. this.mesh = mesh;
  18808. this.frames = mesh.morphTargetInfluences.length;
  18809. this.currentTime = 0;
  18810. this.duration = 1000;
  18811. this.loop = true;
  18812. this.isPlaying = false;
  18813. };
  18814. THREE.MorphAnimation.prototype = {
  18815. play: function () {
  18816. this.isPlaying = true;
  18817. },
  18818. pause: function () {
  18819. this.isPlaying = false;
  18820. },
  18821. update: ( function () {
  18822. var lastFrame = 0;
  18823. var currentFrame = 0;
  18824. return function ( delta ) {
  18825. if ( this.isPlaying === false ) return;
  18826. this.currentTime += delta;
  18827. if ( this.loop === true && this.currentTime > this.duration ) {
  18828. this.currentTime %= this.duration;
  18829. }
  18830. this.currentTime = Math.min( this.currentTime, this.duration );
  18831. var interpolation = this.duration / this.frames;
  18832. var frame = Math.floor( this.currentTime / interpolation );
  18833. if ( frame != currentFrame ) {
  18834. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  18835. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  18836. this.mesh.morphTargetInfluences[ frame ] = 0;
  18837. lastFrame = currentFrame;
  18838. currentFrame = frame;
  18839. }
  18840. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18841. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  18842. }
  18843. } )()
  18844. };
  18845. /**
  18846. * Camera for rendering cube maps
  18847. * - renders scene into axis-aligned cube
  18848. *
  18849. * @author alteredq / http://alteredqualia.com/
  18850. */
  18851. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18852. THREE.Object3D.call( this );
  18853. var fov = 90, aspect = 1;
  18854. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18855. cameraPX.up.set( 0, -1, 0 );
  18856. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18857. this.add( cameraPX );
  18858. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18859. cameraNX.up.set( 0, -1, 0 );
  18860. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18861. this.add( cameraNX );
  18862. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18863. cameraPY.up.set( 0, 0, 1 );
  18864. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18865. this.add( cameraPY );
  18866. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18867. cameraNY.up.set( 0, 0, -1 );
  18868. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18869. this.add( cameraNY );
  18870. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18871. cameraPZ.up.set( 0, -1, 0 );
  18872. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18873. this.add( cameraPZ );
  18874. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18875. cameraNZ.up.set( 0, -1, 0 );
  18876. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18877. this.add( cameraNZ );
  18878. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18879. this.updateCubeMap = function ( renderer, scene ) {
  18880. var renderTarget = this.renderTarget;
  18881. var generateMipmaps = renderTarget.generateMipmaps;
  18882. renderTarget.generateMipmaps = false;
  18883. renderTarget.activeCubeFace = 0;
  18884. renderer.render( scene, cameraPX, renderTarget );
  18885. renderTarget.activeCubeFace = 1;
  18886. renderer.render( scene, cameraNX, renderTarget );
  18887. renderTarget.activeCubeFace = 2;
  18888. renderer.render( scene, cameraPY, renderTarget );
  18889. renderTarget.activeCubeFace = 3;
  18890. renderer.render( scene, cameraNY, renderTarget );
  18891. renderTarget.activeCubeFace = 4;
  18892. renderer.render( scene, cameraPZ, renderTarget );
  18893. renderTarget.generateMipmaps = generateMipmaps;
  18894. renderTarget.activeCubeFace = 5;
  18895. renderer.render( scene, cameraNZ, renderTarget );
  18896. };
  18897. };
  18898. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18899. /**
  18900. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18901. *
  18902. * A general perpose camera, for setting FOV, Lens Focal Length,
  18903. * and switching between perspective and orthographic views easily.
  18904. * Use this only if you do not wish to manage
  18905. * both a Orthographic and Perspective Camera
  18906. *
  18907. */
  18908. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18909. THREE.Camera.call( this );
  18910. this.fov = fov;
  18911. this.left = -width / 2;
  18912. this.right = width / 2
  18913. this.top = height / 2;
  18914. this.bottom = -height / 2;
  18915. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18916. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18917. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18918. this.zoom = 1;
  18919. this.toPerspective();
  18920. var aspect = width/height;
  18921. };
  18922. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18923. THREE.CombinedCamera.prototype.toPerspective = function () {
  18924. // Switches to the Perspective Camera
  18925. this.near = this.cameraP.near;
  18926. this.far = this.cameraP.far;
  18927. this.cameraP.fov = this.fov / this.zoom ;
  18928. this.cameraP.updateProjectionMatrix();
  18929. this.projectionMatrix = this.cameraP.projectionMatrix;
  18930. this.inPerspectiveMode = true;
  18931. this.inOrthographicMode = false;
  18932. };
  18933. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18934. // Switches to the Orthographic camera estimating viewport from Perspective
  18935. var fov = this.fov;
  18936. var aspect = this.cameraP.aspect;
  18937. var near = this.cameraP.near;
  18938. var far = this.cameraP.far;
  18939. // The size that we set is the mid plane of the viewing frustum
  18940. var hyperfocus = ( near + far ) / 2;
  18941. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18942. var planeHeight = 2 * halfHeight;
  18943. var planeWidth = planeHeight * aspect;
  18944. var halfWidth = planeWidth / 2;
  18945. halfHeight /= this.zoom;
  18946. halfWidth /= this.zoom;
  18947. this.cameraO.left = -halfWidth;
  18948. this.cameraO.right = halfWidth;
  18949. this.cameraO.top = halfHeight;
  18950. this.cameraO.bottom = -halfHeight;
  18951. // this.cameraO.left = -farHalfWidth;
  18952. // this.cameraO.right = farHalfWidth;
  18953. // this.cameraO.top = farHalfHeight;
  18954. // this.cameraO.bottom = -farHalfHeight;
  18955. // this.cameraO.left = this.left / this.zoom;
  18956. // this.cameraO.right = this.right / this.zoom;
  18957. // this.cameraO.top = this.top / this.zoom;
  18958. // this.cameraO.bottom = this.bottom / this.zoom;
  18959. this.cameraO.updateProjectionMatrix();
  18960. this.near = this.cameraO.near;
  18961. this.far = this.cameraO.far;
  18962. this.projectionMatrix = this.cameraO.projectionMatrix;
  18963. this.inPerspectiveMode = false;
  18964. this.inOrthographicMode = true;
  18965. };
  18966. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18967. this.cameraP.aspect = width / height;
  18968. this.left = -width / 2;
  18969. this.right = width / 2
  18970. this.top = height / 2;
  18971. this.bottom = -height / 2;
  18972. };
  18973. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18974. this.fov = fov;
  18975. if ( this.inPerspectiveMode ) {
  18976. this.toPerspective();
  18977. } else {
  18978. this.toOrthographic();
  18979. }
  18980. };
  18981. // For mantaining similar API with PerspectiveCamera
  18982. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18983. if ( this.inPerspectiveMode ) {
  18984. this.toPerspective();
  18985. } else {
  18986. this.toPerspective();
  18987. this.toOrthographic();
  18988. }
  18989. };
  18990. /*
  18991. * Uses Focal Length (in mm) to estimate and set FOV
  18992. * 35mm (fullframe) camera is used if frame size is not specified;
  18993. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18994. */
  18995. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18996. if ( frameHeight === undefined ) frameHeight = 24;
  18997. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18998. this.setFov( fov );
  18999. return fov;
  19000. };
  19001. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  19002. this.zoom = zoom;
  19003. if ( this.inPerspectiveMode ) {
  19004. this.toPerspective();
  19005. } else {
  19006. this.toOrthographic();
  19007. }
  19008. };
  19009. THREE.CombinedCamera.prototype.toFrontView = function() {
  19010. this.rotation.x = 0;
  19011. this.rotation.y = 0;
  19012. this.rotation.z = 0;
  19013. // should we be modifing the matrix instead?
  19014. this.rotationAutoUpdate = false;
  19015. };
  19016. THREE.CombinedCamera.prototype.toBackView = function() {
  19017. this.rotation.x = 0;
  19018. this.rotation.y = Math.PI;
  19019. this.rotation.z = 0;
  19020. this.rotationAutoUpdate = false;
  19021. };
  19022. THREE.CombinedCamera.prototype.toLeftView = function() {
  19023. this.rotation.x = 0;
  19024. this.rotation.y = - Math.PI / 2;
  19025. this.rotation.z = 0;
  19026. this.rotationAutoUpdate = false;
  19027. };
  19028. THREE.CombinedCamera.prototype.toRightView = function() {
  19029. this.rotation.x = 0;
  19030. this.rotation.y = Math.PI / 2;
  19031. this.rotation.z = 0;
  19032. this.rotationAutoUpdate = false;
  19033. };
  19034. THREE.CombinedCamera.prototype.toTopView = function() {
  19035. this.rotation.x = - Math.PI / 2;
  19036. this.rotation.y = 0;
  19037. this.rotation.z = 0;
  19038. this.rotationAutoUpdate = false;
  19039. };
  19040. THREE.CombinedCamera.prototype.toBottomView = function() {
  19041. this.rotation.x = Math.PI / 2;
  19042. this.rotation.y = 0;
  19043. this.rotation.z = 0;
  19044. this.rotationAutoUpdate = false;
  19045. };
  19046. /**
  19047. * @author mrdoob / http://mrdoob.com/
  19048. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19049. */
  19050. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19051. THREE.Geometry.call( this );
  19052. var scope = this;
  19053. this.width = width;
  19054. this.height = height;
  19055. this.depth = depth;
  19056. this.widthSegments = widthSegments || 1;
  19057. this.heightSegments = heightSegments || 1;
  19058. this.depthSegments = depthSegments || 1;
  19059. var width_half = this.width / 2;
  19060. var height_half = this.height / 2;
  19061. var depth_half = this.depth / 2;
  19062. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  19063. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  19064. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  19065. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  19066. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  19067. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  19068. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19069. var w, ix, iy,
  19070. gridX = scope.widthSegments,
  19071. gridY = scope.heightSegments,
  19072. width_half = width / 2,
  19073. height_half = height / 2,
  19074. offset = scope.vertices.length;
  19075. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19076. w = 'z';
  19077. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19078. w = 'y';
  19079. gridY = scope.depthSegments;
  19080. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19081. w = 'x';
  19082. gridX = scope.depthSegments;
  19083. }
  19084. var gridX1 = gridX + 1,
  19085. gridY1 = gridY + 1,
  19086. segment_width = width / gridX,
  19087. segment_height = height / gridY,
  19088. normal = new THREE.Vector3();
  19089. normal[ w ] = depth > 0 ? 1 : - 1;
  19090. for ( iy = 0; iy < gridY1; iy ++ ) {
  19091. for ( ix = 0; ix < gridX1; ix ++ ) {
  19092. var vector = new THREE.Vector3();
  19093. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19094. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19095. vector[ w ] = depth;
  19096. scope.vertices.push( vector );
  19097. }
  19098. }
  19099. for ( iy = 0; iy < gridY; iy++ ) {
  19100. for ( ix = 0; ix < gridX; ix++ ) {
  19101. var a = ix + gridX1 * iy;
  19102. var b = ix + gridX1 * ( iy + 1 );
  19103. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19104. var d = ( ix + 1 ) + gridX1 * iy;
  19105. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  19106. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  19107. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  19108. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  19109. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  19110. face.normal.copy( normal );
  19111. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19112. face.materialIndex = materialIndex;
  19113. scope.faces.push( face );
  19114. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19115. face = new THREE.Face3( b + offset, c + offset, d + offset );
  19116. face.normal.copy( normal );
  19117. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19118. face.materialIndex = materialIndex;
  19119. scope.faces.push( face );
  19120. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19121. }
  19122. }
  19123. }
  19124. this.mergeVertices();
  19125. };
  19126. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19127. /**
  19128. * @author hughes
  19129. */
  19130. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  19131. THREE.Geometry.call( this );
  19132. this.radius = radius = radius || 50;
  19133. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19134. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19135. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19136. var i, uvs = [],
  19137. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  19138. this.vertices.push(center);
  19139. uvs.push( centerUV );
  19140. for ( i = 0; i <= segments; i ++ ) {
  19141. var vertex = new THREE.Vector3();
  19142. var segment = thetaStart + i / segments * thetaLength;
  19143. vertex.x = radius * Math.cos( segment );
  19144. vertex.y = radius * Math.sin( segment );
  19145. this.vertices.push( vertex );
  19146. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  19147. }
  19148. var n = new THREE.Vector3( 0, 0, 1 );
  19149. for ( i = 1; i <= segments; i ++ ) {
  19150. var v1 = i;
  19151. var v2 = i + 1 ;
  19152. var v3 = 0;
  19153. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19154. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  19155. }
  19156. this.computeFaceNormals();
  19157. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19158. };
  19159. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19160. // DEPRECATED
  19161. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19162. console.warn( 'DEPRECATED: THREE.CubeGeometry is deprecated. Use THREE.BoxGeometry instead.' );
  19163. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  19164. };
  19165. /**
  19166. * @author mrdoob / http://mrdoob.com/
  19167. */
  19168. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19169. THREE.Geometry.call( this );
  19170. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19171. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19172. this.height = height = height !== undefined ? height : 100;
  19173. this.radialSegments = radialSegments = radialSegments || 8;
  19174. this.heightSegments = heightSegments = heightSegments || 1;
  19175. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  19176. var heightHalf = height / 2;
  19177. var x, y, vertices = [], uvs = [];
  19178. for ( y = 0; y <= heightSegments; y ++ ) {
  19179. var verticesRow = [];
  19180. var uvsRow = [];
  19181. var v = y / heightSegments;
  19182. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19183. for ( x = 0; x <= radialSegments; x ++ ) {
  19184. var u = x / radialSegments;
  19185. var vertex = new THREE.Vector3();
  19186. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19187. vertex.y = - v * height + heightHalf;
  19188. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19189. this.vertices.push( vertex );
  19190. verticesRow.push( this.vertices.length - 1 );
  19191. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19192. }
  19193. vertices.push( verticesRow );
  19194. uvs.push( uvsRow );
  19195. }
  19196. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19197. var na, nb;
  19198. for ( x = 0; x < radialSegments; x ++ ) {
  19199. if ( radiusTop !== 0 ) {
  19200. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19201. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19202. } else {
  19203. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19204. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19205. }
  19206. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19207. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19208. for ( y = 0; y < heightSegments; y ++ ) {
  19209. var v1 = vertices[ y ][ x ];
  19210. var v2 = vertices[ y + 1 ][ x ];
  19211. var v3 = vertices[ y + 1 ][ x + 1 ];
  19212. var v4 = vertices[ y ][ x + 1 ];
  19213. var n1 = na.clone();
  19214. var n2 = na.clone();
  19215. var n3 = nb.clone();
  19216. var n4 = nb.clone();
  19217. var uv1 = uvs[ y ][ x ].clone();
  19218. var uv2 = uvs[ y + 1 ][ x ].clone();
  19219. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19220. var uv4 = uvs[ y ][ x + 1 ].clone();
  19221. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19222. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19223. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19224. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19225. }
  19226. }
  19227. // top cap
  19228. if ( openEnded === false && radiusTop > 0 ) {
  19229. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19230. for ( x = 0; x < radialSegments; x ++ ) {
  19231. var v1 = vertices[ 0 ][ x ];
  19232. var v2 = vertices[ 0 ][ x + 1 ];
  19233. var v3 = this.vertices.length - 1;
  19234. var n1 = new THREE.Vector3( 0, 1, 0 );
  19235. var n2 = new THREE.Vector3( 0, 1, 0 );
  19236. var n3 = new THREE.Vector3( 0, 1, 0 );
  19237. var uv1 = uvs[ 0 ][ x ].clone();
  19238. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19239. var uv3 = new THREE.Vector2( uv2.x, 0 );
  19240. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19241. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19242. }
  19243. }
  19244. // bottom cap
  19245. if ( openEnded === false && radiusBottom > 0 ) {
  19246. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19247. for ( x = 0; x < radialSegments; x ++ ) {
  19248. var v1 = vertices[ y ][ x + 1 ];
  19249. var v2 = vertices[ y ][ x ];
  19250. var v3 = this.vertices.length - 1;
  19251. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19252. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19253. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19254. var uv1 = uvs[ y ][ x + 1 ].clone();
  19255. var uv2 = uvs[ y ][ x ].clone();
  19256. var uv3 = new THREE.Vector2( uv2.x, 1 );
  19257. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19258. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19259. }
  19260. }
  19261. this.computeFaceNormals();
  19262. }
  19263. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19264. /**
  19265. * @author zz85 / http://www.lab4games.net/zz85/blog
  19266. *
  19267. * Creates extruded geometry from a path shape.
  19268. *
  19269. * parameters = {
  19270. *
  19271. * curveSegments: <int>, // number of points on the curves
  19272. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19273. * amount: <int>, // Depth to extrude the shape
  19274. *
  19275. * bevelEnabled: <bool>, // turn on bevel
  19276. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19277. * bevelSize: <float>, // how far from shape outline is bevel
  19278. * bevelSegments: <int>, // number of bevel layers
  19279. *
  19280. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19281. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19282. *
  19283. * material: <int> // material index for front and back faces
  19284. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19285. * uvGenerator: <Object> // object that provides UV generator functions
  19286. *
  19287. * }
  19288. **/
  19289. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19290. if ( typeof( shapes ) === "undefined" ) {
  19291. shapes = [];
  19292. return;
  19293. }
  19294. THREE.Geometry.call( this );
  19295. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19296. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19297. this.addShapeList( shapes, options );
  19298. this.computeFaceNormals();
  19299. // can't really use automatic vertex normals
  19300. // as then front and back sides get smoothed too
  19301. // should do separate smoothing just for sides
  19302. //this.computeVertexNormals();
  19303. //console.log( "took", ( Date.now() - startTime ) );
  19304. };
  19305. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19306. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19307. var sl = shapes.length;
  19308. for ( var s = 0; s < sl; s ++ ) {
  19309. var shape = shapes[ s ];
  19310. this.addShape( shape, options );
  19311. }
  19312. };
  19313. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19314. var amount = options.amount !== undefined ? options.amount : 100;
  19315. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19316. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19317. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19318. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19319. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19320. var steps = options.steps !== undefined ? options.steps : 1;
  19321. var extrudePath = options.extrudePath;
  19322. var extrudePts, extrudeByPath = false;
  19323. var material = options.material;
  19324. var extrudeMaterial = options.extrudeMaterial;
  19325. // Use default WorldUVGenerator if no UV generators are specified.
  19326. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19327. var shapebb = this.shapebb;
  19328. //shapebb = shape.getBoundingBox();
  19329. var splineTube, binormal, normal, position2;
  19330. if ( extrudePath ) {
  19331. extrudePts = extrudePath.getSpacedPoints( steps );
  19332. extrudeByPath = true;
  19333. bevelEnabled = false; // bevels not supported for path extrusion
  19334. // SETUP TNB variables
  19335. // Reuse TNB from TubeGeomtry for now.
  19336. // TODO1 - have a .isClosed in spline?
  19337. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19338. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19339. binormal = new THREE.Vector3();
  19340. normal = new THREE.Vector3();
  19341. position2 = new THREE.Vector3();
  19342. }
  19343. // Safeguards if bevels are not enabled
  19344. if ( ! bevelEnabled ) {
  19345. bevelSegments = 0;
  19346. bevelThickness = 0;
  19347. bevelSize = 0;
  19348. }
  19349. // Variables initalization
  19350. var ahole, h, hl; // looping of holes
  19351. var scope = this;
  19352. var bevelPoints = [];
  19353. var shapesOffset = this.vertices.length;
  19354. var shapePoints = shape.extractPoints( curveSegments );
  19355. var vertices = shapePoints.shape;
  19356. var holes = shapePoints.holes;
  19357. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19358. if ( reverse ) {
  19359. vertices = vertices.reverse();
  19360. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19361. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19362. ahole = holes[ h ];
  19363. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19364. holes[ h ] = ahole.reverse();
  19365. }
  19366. }
  19367. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19368. }
  19369. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19370. /* Vertices */
  19371. var contour = vertices; // vertices has all points but contour has only points of circumference
  19372. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19373. ahole = holes[ h ];
  19374. vertices = vertices.concat( ahole );
  19375. }
  19376. function scalePt2 ( pt, vec, size ) {
  19377. if ( !vec ) console.log( "die" );
  19378. return vec.clone().multiplyScalar( size ).add( pt );
  19379. }
  19380. var b, bs, t, z,
  19381. vert, vlen = vertices.length,
  19382. face, flen = faces.length,
  19383. cont, clen = contour.length;
  19384. // Find directions for point movement
  19385. var RAD_TO_DEGREES = 180 / Math.PI;
  19386. function getBevelVec( inPt, inPrev, inNext ) {
  19387. var EPSILON = 0.0000000001;
  19388. var sign = THREE.Math.sign;
  19389. // computes for inPt the corresponding point inPt' on a new contour
  19390. // shiftet by 1 unit (length of normalized vector) to the left
  19391. // if we walk along contour clockwise, this new contour is outside the old one
  19392. //
  19393. // inPt' is the intersection of the two lines parallel to the two
  19394. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19395. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19396. // good reading for geometry algorithms (here: line-line intersection)
  19397. // http://geomalgorithms.com/a05-_intersect-1.html
  19398. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19399. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19400. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19401. // check for colinear edges
  19402. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19403. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  19404. // length of vectors for normalizing
  19405. var v_prev_len = Math.sqrt( v_prev_lensq );
  19406. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19407. // shift adjacent points by unit vectors to the left
  19408. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19409. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19410. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19411. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19412. // scaling factor for v_prev to intersection point
  19413. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19414. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19415. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19416. // vector from inPt to intersection point
  19417. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19418. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19419. // Don't normalize!, otherwise sharp corners become ugly
  19420. // but prevent crazy spikes
  19421. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  19422. if ( v_trans_lensq <= 2 ) {
  19423. return new THREE.Vector2( v_trans_x, v_trans_y );
  19424. } else {
  19425. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19426. }
  19427. } else { // handle special case of colinear edges
  19428. var direction_eq = false; // assumes: opposite
  19429. if ( v_prev_x > EPSILON ) {
  19430. if ( v_next_x > EPSILON ) { direction_eq = true; }
  19431. } else {
  19432. if ( v_prev_x < -EPSILON ) {
  19433. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  19434. } else {
  19435. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  19436. }
  19437. }
  19438. if ( direction_eq ) {
  19439. // console.log("Warning: lines are a straight sequence");
  19440. v_trans_x = -v_prev_y;
  19441. v_trans_y = v_prev_x;
  19442. shrink_by = Math.sqrt( v_prev_lensq );
  19443. } else {
  19444. // console.log("Warning: lines are a straight spike");
  19445. v_trans_x = v_prev_x;
  19446. v_trans_y = v_prev_y;
  19447. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19448. }
  19449. }
  19450. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19451. }
  19452. var contourMovements = [];
  19453. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19454. if ( j === il ) j = 0;
  19455. if ( k === il ) k = 0;
  19456. // (j)---(i)---(k)
  19457. // console.log('i,j,k', i, j , k)
  19458. var pt_i = contour[ i ];
  19459. var pt_j = contour[ j ];
  19460. var pt_k = contour[ k ];
  19461. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19462. }
  19463. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19464. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19465. ahole = holes[ h ];
  19466. oneHoleMovements = [];
  19467. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19468. if ( j === il ) j = 0;
  19469. if ( k === il ) k = 0;
  19470. // (j)---(i)---(k)
  19471. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19472. }
  19473. holesMovements.push( oneHoleMovements );
  19474. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19475. }
  19476. // Loop bevelSegments, 1 for the front, 1 for the back
  19477. for ( b = 0; b < bevelSegments; b ++ ) {
  19478. //for ( b = bevelSegments; b > 0; b -- ) {
  19479. t = b / bevelSegments;
  19480. z = bevelThickness * ( 1 - t );
  19481. //z = bevelThickness * t;
  19482. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19483. //bs = bevelSize * t ; // linear
  19484. // contract shape
  19485. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19486. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19487. v( vert.x, vert.y, - z );
  19488. }
  19489. // expand holes
  19490. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19491. ahole = holes[ h ];
  19492. oneHoleMovements = holesMovements[ h ];
  19493. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19494. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19495. v( vert.x, vert.y, -z );
  19496. }
  19497. }
  19498. }
  19499. bs = bevelSize;
  19500. // Back facing vertices
  19501. for ( i = 0; i < vlen; i ++ ) {
  19502. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19503. if ( !extrudeByPath ) {
  19504. v( vert.x, vert.y, 0 );
  19505. } else {
  19506. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19507. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19508. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19509. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19510. v( position2.x, position2.y, position2.z );
  19511. }
  19512. }
  19513. // Add stepped vertices...
  19514. // Including front facing vertices
  19515. var s;
  19516. for ( s = 1; s <= steps; s ++ ) {
  19517. for ( i = 0; i < vlen; i ++ ) {
  19518. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19519. if ( !extrudeByPath ) {
  19520. v( vert.x, vert.y, amount / steps * s );
  19521. } else {
  19522. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19523. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19524. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19525. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19526. v( position2.x, position2.y, position2.z );
  19527. }
  19528. }
  19529. }
  19530. // Add bevel segments planes
  19531. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19532. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19533. t = b / bevelSegments;
  19534. z = bevelThickness * ( 1 - t );
  19535. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19536. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19537. // contract shape
  19538. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19539. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19540. v( vert.x, vert.y, amount + z );
  19541. }
  19542. // expand holes
  19543. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19544. ahole = holes[ h ];
  19545. oneHoleMovements = holesMovements[ h ];
  19546. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19547. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19548. if ( !extrudeByPath ) {
  19549. v( vert.x, vert.y, amount + z );
  19550. } else {
  19551. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19552. }
  19553. }
  19554. }
  19555. }
  19556. /* Faces */
  19557. // Top and bottom faces
  19558. buildLidFaces();
  19559. // Sides faces
  19560. buildSideFaces();
  19561. ///// Internal functions
  19562. function buildLidFaces() {
  19563. if ( bevelEnabled ) {
  19564. var layer = 0 ; // steps + 1
  19565. var offset = vlen * layer;
  19566. // Bottom faces
  19567. for ( i = 0; i < flen; i ++ ) {
  19568. face = faces[ i ];
  19569. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19570. }
  19571. layer = steps + bevelSegments * 2;
  19572. offset = vlen * layer;
  19573. // Top faces
  19574. for ( i = 0; i < flen; i ++ ) {
  19575. face = faces[ i ];
  19576. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19577. }
  19578. } else {
  19579. // Bottom faces
  19580. for ( i = 0; i < flen; i++ ) {
  19581. face = faces[ i ];
  19582. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19583. }
  19584. // Top faces
  19585. for ( i = 0; i < flen; i ++ ) {
  19586. face = faces[ i ];
  19587. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19588. }
  19589. }
  19590. }
  19591. // Create faces for the z-sides of the shape
  19592. function buildSideFaces() {
  19593. var layeroffset = 0;
  19594. sidewalls( contour, layeroffset );
  19595. layeroffset += contour.length;
  19596. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19597. ahole = holes[ h ];
  19598. sidewalls( ahole, layeroffset );
  19599. //, true
  19600. layeroffset += ahole.length;
  19601. }
  19602. }
  19603. function sidewalls( contour, layeroffset ) {
  19604. var j, k;
  19605. i = contour.length;
  19606. while ( --i >= 0 ) {
  19607. j = i;
  19608. k = i - 1;
  19609. if ( k < 0 ) k = contour.length - 1;
  19610. //console.log('b', i,j, i-1, k,vertices.length);
  19611. var s = 0, sl = steps + bevelSegments * 2;
  19612. for ( s = 0; s < sl; s ++ ) {
  19613. var slen1 = vlen * s;
  19614. var slen2 = vlen * ( s + 1 );
  19615. var a = layeroffset + j + slen1,
  19616. b = layeroffset + k + slen1,
  19617. c = layeroffset + k + slen2,
  19618. d = layeroffset + j + slen2;
  19619. f4( a, b, c, d, contour, s, sl, j, k );
  19620. }
  19621. }
  19622. }
  19623. function v( x, y, z ) {
  19624. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19625. }
  19626. function f3( a, b, c, isBottom ) {
  19627. a += shapesOffset;
  19628. b += shapesOffset;
  19629. c += shapesOffset;
  19630. // normal, color, material
  19631. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19632. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19633. scope.faceVertexUvs[ 0 ].push( uvs );
  19634. }
  19635. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19636. a += shapesOffset;
  19637. b += shapesOffset;
  19638. c += shapesOffset;
  19639. d += shapesOffset;
  19640. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19641. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19642. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19643. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19644. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19645. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19646. }
  19647. };
  19648. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19649. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19650. var ax = geometry.vertices[ indexA ].x,
  19651. ay = geometry.vertices[ indexA ].y,
  19652. bx = geometry.vertices[ indexB ].x,
  19653. by = geometry.vertices[ indexB ].y,
  19654. cx = geometry.vertices[ indexC ].x,
  19655. cy = geometry.vertices[ indexC ].y;
  19656. return [
  19657. new THREE.Vector2( ax, ay ),
  19658. new THREE.Vector2( bx, by ),
  19659. new THREE.Vector2( cx, cy )
  19660. ];
  19661. },
  19662. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19663. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19664. },
  19665. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19666. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19667. contourIndex1, contourIndex2 ) {
  19668. var ax = geometry.vertices[ indexA ].x,
  19669. ay = geometry.vertices[ indexA ].y,
  19670. az = geometry.vertices[ indexA ].z,
  19671. bx = geometry.vertices[ indexB ].x,
  19672. by = geometry.vertices[ indexB ].y,
  19673. bz = geometry.vertices[ indexB ].z,
  19674. cx = geometry.vertices[ indexC ].x,
  19675. cy = geometry.vertices[ indexC ].y,
  19676. cz = geometry.vertices[ indexC ].z,
  19677. dx = geometry.vertices[ indexD ].x,
  19678. dy = geometry.vertices[ indexD ].y,
  19679. dz = geometry.vertices[ indexD ].z;
  19680. if ( Math.abs( ay - by ) < 0.01 ) {
  19681. return [
  19682. new THREE.Vector2( ax, 1 - az ),
  19683. new THREE.Vector2( bx, 1 - bz ),
  19684. new THREE.Vector2( cx, 1 - cz ),
  19685. new THREE.Vector2( dx, 1 - dz )
  19686. ];
  19687. } else {
  19688. return [
  19689. new THREE.Vector2( ay, 1 - az ),
  19690. new THREE.Vector2( by, 1 - bz ),
  19691. new THREE.Vector2( cy, 1 - cz ),
  19692. new THREE.Vector2( dy, 1 - dz )
  19693. ];
  19694. }
  19695. }
  19696. };
  19697. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19698. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19699. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19700. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19701. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19702. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19703. /**
  19704. * @author jonobr1 / http://jonobr1.com
  19705. *
  19706. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19707. * ExtrudeGeometry.
  19708. *
  19709. * parameters = {
  19710. *
  19711. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19712. *
  19713. * material: <int> // material index for front and back faces
  19714. * uvGenerator: <Object> // object that provides UV generator functions
  19715. *
  19716. * }
  19717. **/
  19718. THREE.ShapeGeometry = function ( shapes, options ) {
  19719. THREE.Geometry.call( this );
  19720. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19721. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19722. this.addShapeList( shapes, options );
  19723. this.computeFaceNormals();
  19724. };
  19725. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19726. /**
  19727. * Add an array of shapes to THREE.ShapeGeometry.
  19728. */
  19729. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19730. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19731. this.addShape( shapes[ i ], options );
  19732. }
  19733. return this;
  19734. };
  19735. /**
  19736. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19737. */
  19738. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19739. if ( options === undefined ) options = {};
  19740. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19741. var material = options.material;
  19742. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19743. var shapebb = this.shapebb;
  19744. //
  19745. var i, l, hole, s;
  19746. var shapesOffset = this.vertices.length;
  19747. var shapePoints = shape.extractPoints( curveSegments );
  19748. var vertices = shapePoints.shape;
  19749. var holes = shapePoints.holes;
  19750. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19751. if ( reverse ) {
  19752. vertices = vertices.reverse();
  19753. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19754. for ( i = 0, l = holes.length; i < l; i++ ) {
  19755. hole = holes[ i ];
  19756. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19757. holes[ i ] = hole.reverse();
  19758. }
  19759. }
  19760. reverse = false;
  19761. }
  19762. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19763. // Vertices
  19764. var contour = vertices;
  19765. for ( i = 0, l = holes.length; i < l; i++ ) {
  19766. hole = holes[ i ];
  19767. vertices = vertices.concat( hole );
  19768. }
  19769. //
  19770. var vert, vlen = vertices.length;
  19771. var face, flen = faces.length;
  19772. var cont, clen = contour.length;
  19773. for ( i = 0; i < vlen; i++ ) {
  19774. vert = vertices[ i ];
  19775. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19776. }
  19777. for ( i = 0; i < flen; i++ ) {
  19778. face = faces[ i ];
  19779. var a = face[ 0 ] + shapesOffset;
  19780. var b = face[ 1 ] + shapesOffset;
  19781. var c = face[ 2 ] + shapesOffset;
  19782. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19783. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19784. }
  19785. };
  19786. /**
  19787. * @author astrodud / http://astrodud.isgreat.org/
  19788. * @author zz85 / https://github.com/zz85
  19789. * @author bhouston / http://exocortex.com
  19790. */
  19791. // points - to create a closed torus, one must use a set of points
  19792. // like so: [ a, b, c, d, a ], see first is the same as last.
  19793. // segments - the number of circumference segments to create
  19794. // phiStart - the starting radian
  19795. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19796. // 2*pi is a closed lathe, less than 2PI is a portion.
  19797. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19798. THREE.Geometry.call( this );
  19799. segments = segments || 12;
  19800. phiStart = phiStart || 0;
  19801. phiLength = phiLength || 2 * Math.PI;
  19802. var inversePointLength = 1.0 / ( points.length - 1 );
  19803. var inverseSegments = 1.0 / segments;
  19804. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19805. var phi = phiStart + i * inverseSegments * phiLength;
  19806. var c = Math.cos( phi ),
  19807. s = Math.sin( phi );
  19808. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19809. var pt = points[ j ];
  19810. var vertex = new THREE.Vector3();
  19811. vertex.x = c * pt.x - s * pt.y;
  19812. vertex.y = s * pt.x + c * pt.y;
  19813. vertex.z = pt.z;
  19814. this.vertices.push( vertex );
  19815. }
  19816. }
  19817. var np = points.length;
  19818. for ( var i = 0, il = segments; i < il; i ++ ) {
  19819. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19820. var base = j + np * i;
  19821. var a = base;
  19822. var b = base + np;
  19823. var c = base + 1 + np;
  19824. var d = base + 1;
  19825. var u0 = i * inverseSegments;
  19826. var v0 = j * inversePointLength;
  19827. var u1 = u0 + inverseSegments;
  19828. var v1 = v0 + inversePointLength;
  19829. this.faces.push( new THREE.Face3( a, b, d ) );
  19830. this.faceVertexUvs[ 0 ].push( [
  19831. new THREE.Vector2( u0, v0 ),
  19832. new THREE.Vector2( u1, v0 ),
  19833. new THREE.Vector2( u0, v1 )
  19834. ] );
  19835. this.faces.push( new THREE.Face3( b, c, d ) );
  19836. this.faceVertexUvs[ 0 ].push( [
  19837. new THREE.Vector2( u1, v0 ),
  19838. new THREE.Vector2( u1, v1 ),
  19839. new THREE.Vector2( u0, v1 )
  19840. ] );
  19841. }
  19842. }
  19843. this.mergeVertices();
  19844. this.computeFaceNormals();
  19845. this.computeVertexNormals();
  19846. };
  19847. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19848. /**
  19849. * @author mrdoob / http://mrdoob.com/
  19850. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19851. */
  19852. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19853. THREE.Geometry.call( this );
  19854. this.width = width;
  19855. this.height = height;
  19856. this.widthSegments = widthSegments || 1;
  19857. this.heightSegments = heightSegments || 1;
  19858. var ix, iz;
  19859. var width_half = width / 2;
  19860. var height_half = height / 2;
  19861. var gridX = this.widthSegments;
  19862. var gridZ = this.heightSegments;
  19863. var gridX1 = gridX + 1;
  19864. var gridZ1 = gridZ + 1;
  19865. var segment_width = this.width / gridX;
  19866. var segment_height = this.height / gridZ;
  19867. var normal = new THREE.Vector3( 0, 0, 1 );
  19868. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19869. for ( ix = 0; ix < gridX1; ix ++ ) {
  19870. var x = ix * segment_width - width_half;
  19871. var y = iz * segment_height - height_half;
  19872. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19873. }
  19874. }
  19875. for ( iz = 0; iz < gridZ; iz ++ ) {
  19876. for ( ix = 0; ix < gridX; ix ++ ) {
  19877. var a = ix + gridX1 * iz;
  19878. var b = ix + gridX1 * ( iz + 1 );
  19879. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19880. var d = ( ix + 1 ) + gridX1 * iz;
  19881. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19882. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19883. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19884. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19885. var face = new THREE.Face3( a, b, d );
  19886. face.normal.copy( normal );
  19887. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19888. this.faces.push( face );
  19889. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19890. face = new THREE.Face3( b, c, d );
  19891. face.normal.copy( normal );
  19892. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19893. this.faces.push( face );
  19894. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19895. }
  19896. }
  19897. };
  19898. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19899. /**
  19900. * @author Kaleb Murphy
  19901. */
  19902. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19903. THREE.Geometry.call( this );
  19904. innerRadius = innerRadius || 0;
  19905. outerRadius = outerRadius || 50;
  19906. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19907. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19908. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19909. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19910. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19911. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19912. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19913. var vertex = new THREE.Vector3();
  19914. var segment = thetaStart + o / thetaSegments * thetaLength;
  19915. vertex.x = radius * Math.cos( segment );
  19916. vertex.y = radius * Math.sin( segment );
  19917. this.vertices.push( vertex );
  19918. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19919. }
  19920. radius += radiusStep;
  19921. }
  19922. var n = new THREE.Vector3( 0, 0, 1 );
  19923. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19924. var thetaSegment = i * thetaSegments;
  19925. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19926. var segment = o + thetaSegment;
  19927. var v1 = segment + i;
  19928. var v2 = segment + thetaSegments + i;
  19929. var v3 = segment + thetaSegments + 1 + i;
  19930. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19931. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19932. v1 = segment + i;
  19933. v2 = segment + thetaSegments + 1 + i;
  19934. v3 = segment + 1 + i;
  19935. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19936. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19937. }
  19938. }
  19939. this.computeFaceNormals();
  19940. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19941. };
  19942. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19943. /**
  19944. * @author mrdoob / http://mrdoob.com/
  19945. */
  19946. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19947. THREE.Geometry.call( this );
  19948. this.radius = radius = radius || 50;
  19949. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19950. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19951. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19952. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19953. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19954. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19955. var x, y, vertices = [], uvs = [];
  19956. for ( y = 0; y <= heightSegments; y ++ ) {
  19957. var verticesRow = [];
  19958. var uvsRow = [];
  19959. for ( x = 0; x <= widthSegments; x ++ ) {
  19960. var u = x / widthSegments;
  19961. var v = y / heightSegments;
  19962. var vertex = new THREE.Vector3();
  19963. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19964. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19965. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19966. this.vertices.push( vertex );
  19967. verticesRow.push( this.vertices.length - 1 );
  19968. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19969. }
  19970. vertices.push( verticesRow );
  19971. uvs.push( uvsRow );
  19972. }
  19973. for ( y = 0; y < this.heightSegments; y ++ ) {
  19974. for ( x = 0; x < this.widthSegments; x ++ ) {
  19975. var v1 = vertices[ y ][ x + 1 ];
  19976. var v2 = vertices[ y ][ x ];
  19977. var v3 = vertices[ y + 1 ][ x ];
  19978. var v4 = vertices[ y + 1 ][ x + 1 ];
  19979. var n1 = this.vertices[ v1 ].clone().normalize();
  19980. var n2 = this.vertices[ v2 ].clone().normalize();
  19981. var n3 = this.vertices[ v3 ].clone().normalize();
  19982. var n4 = this.vertices[ v4 ].clone().normalize();
  19983. var uv1 = uvs[ y ][ x + 1 ].clone();
  19984. var uv2 = uvs[ y ][ x ].clone();
  19985. var uv3 = uvs[ y + 1 ][ x ].clone();
  19986. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19987. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19988. uv1.x = ( uv1.x + uv2.x ) / 2;
  19989. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19990. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19991. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19992. uv3.x = ( uv3.x + uv4.x ) / 2;
  19993. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19994. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19995. } else {
  19996. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19997. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19998. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19999. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  20000. }
  20001. }
  20002. }
  20003. this.computeFaceNormals();
  20004. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20005. };
  20006. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20007. /**
  20008. * @author zz85 / http://www.lab4games.net/zz85/blog
  20009. * @author alteredq / http://alteredqualia.com/
  20010. *
  20011. * For creating 3D text geometry in three.js
  20012. *
  20013. * Text = 3D Text
  20014. *
  20015. * parameters = {
  20016. * size: <float>, // size of the text
  20017. * height: <float>, // thickness to extrude text
  20018. * curveSegments: <int>, // number of points on the curves
  20019. *
  20020. * font: <string>, // font name
  20021. * weight: <string>, // font weight (normal, bold)
  20022. * style: <string>, // font style (normal, italics)
  20023. *
  20024. * bevelEnabled: <bool>, // turn on bevel
  20025. * bevelThickness: <float>, // how deep into text bevel goes
  20026. * bevelSize: <float>, // how far from text outline is bevel
  20027. * }
  20028. *
  20029. */
  20030. /* Usage Examples
  20031. // TextGeometry wrapper
  20032. var text3d = new TextGeometry( text, options );
  20033. // Complete manner
  20034. var textShapes = THREE.FontUtils.generateShapes( text, options );
  20035. var text3d = new ExtrudeGeometry( textShapes, options );
  20036. */
  20037. THREE.TextGeometry = function ( text, parameters ) {
  20038. parameters = parameters || {};
  20039. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  20040. // translate parameters to ExtrudeGeometry API
  20041. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20042. // defaults
  20043. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20044. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20045. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20046. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  20047. };
  20048. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  20049. /**
  20050. * @author oosmoxiecode
  20051. * @author mrdoob / http://mrdoob.com/
  20052. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  20053. */
  20054. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  20055. THREE.Geometry.call( this );
  20056. var scope = this;
  20057. this.radius = radius || 100;
  20058. this.tube = tube || 40;
  20059. this.radialSegments = radialSegments || 8;
  20060. this.tubularSegments = tubularSegments || 6;
  20061. this.arc = arc || Math.PI * 2;
  20062. var center = new THREE.Vector3(), uvs = [], normals = [];
  20063. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  20064. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  20065. var u = i / this.tubularSegments * this.arc;
  20066. var v = j / this.radialSegments * Math.PI * 2;
  20067. center.x = this.radius * Math.cos( u );
  20068. center.y = this.radius * Math.sin( u );
  20069. var vertex = new THREE.Vector3();
  20070. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  20071. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  20072. vertex.z = this.tube * Math.sin( v );
  20073. this.vertices.push( vertex );
  20074. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  20075. normals.push( vertex.clone().sub( center ).normalize() );
  20076. }
  20077. }
  20078. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  20079. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  20080. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  20081. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20082. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  20083. var d = ( this.tubularSegments + 1 ) * j + i;
  20084. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  20085. this.faces.push( face );
  20086. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  20087. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  20088. this.faces.push( face );
  20089. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20090. }
  20091. }
  20092. this.computeFaceNormals();
  20093. };
  20094. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20095. /**
  20096. * @author oosmoxiecode
  20097. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20098. */
  20099. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20100. THREE.Geometry.call( this );
  20101. var scope = this;
  20102. this.radius = radius || 100;
  20103. this.tube = tube || 40;
  20104. this.radialSegments = radialSegments || 64;
  20105. this.tubularSegments = tubularSegments || 8;
  20106. this.p = p || 2;
  20107. this.q = q || 3;
  20108. this.heightScale = heightScale || 1;
  20109. this.grid = new Array( this.radialSegments );
  20110. var tang = new THREE.Vector3();
  20111. var n = new THREE.Vector3();
  20112. var bitan = new THREE.Vector3();
  20113. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20114. this.grid[ i ] = new Array( this.tubularSegments );
  20115. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  20116. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  20117. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  20118. tang.subVectors( p2, p1 );
  20119. n.addVectors( p2, p1 );
  20120. bitan.crossVectors( tang, n );
  20121. n.crossVectors( bitan, tang );
  20122. bitan.normalize();
  20123. n.normalize();
  20124. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20125. var v = j / this.tubularSegments * 2 * Math.PI;
  20126. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20127. var cy = this.tube * Math.sin( v );
  20128. var pos = new THREE.Vector3();
  20129. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20130. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20131. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20132. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  20133. }
  20134. }
  20135. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20136. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20137. var ip = ( i + 1 ) % this.radialSegments;
  20138. var jp = ( j + 1 ) % this.tubularSegments;
  20139. var a = this.grid[ i ][ j ];
  20140. var b = this.grid[ ip ][ j ];
  20141. var c = this.grid[ ip ][ jp ];
  20142. var d = this.grid[ i ][ jp ];
  20143. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  20144. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  20145. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20146. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20147. this.faces.push( new THREE.Face3( a, b, d ) );
  20148. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20149. this.faces.push( new THREE.Face3( b, c, d ) );
  20150. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20151. }
  20152. }
  20153. this.computeFaceNormals();
  20154. this.computeVertexNormals();
  20155. function getPos( u, in_q, in_p, radius, heightScale ) {
  20156. var cu = Math.cos( u );
  20157. var su = Math.sin( u );
  20158. var quOverP = in_q / in_p * u;
  20159. var cs = Math.cos( quOverP );
  20160. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20161. var ty = radius * ( 2 + cs ) * su * 0.5;
  20162. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20163. return new THREE.Vector3( tx, ty, tz );
  20164. }
  20165. };
  20166. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20167. /**
  20168. * @author WestLangley / https://github.com/WestLangley
  20169. * @author zz85 / https://github.com/zz85
  20170. * @author miningold / https://github.com/miningold
  20171. *
  20172. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20173. *
  20174. * Creates a tube which extrudes along a 3d spline
  20175. *
  20176. * Uses parallel transport frames as described in
  20177. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20178. */
  20179. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20180. THREE.Geometry.call( this );
  20181. this.path = path;
  20182. this.segments = segments || 64;
  20183. this.radius = radius || 1;
  20184. this.radialSegments = radialSegments || 8;
  20185. this.closed = closed || false;
  20186. this.grid = [];
  20187. var scope = this,
  20188. tangent,
  20189. normal,
  20190. binormal,
  20191. numpoints = this.segments + 1,
  20192. x, y, z,
  20193. tx, ty, tz,
  20194. u, v,
  20195. cx, cy,
  20196. pos, pos2 = new THREE.Vector3(),
  20197. i, j,
  20198. ip, jp,
  20199. a, b, c, d,
  20200. uva, uvb, uvc, uvd;
  20201. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20202. tangents = frames.tangents,
  20203. normals = frames.normals,
  20204. binormals = frames.binormals;
  20205. // proxy internals
  20206. this.tangents = tangents;
  20207. this.normals = normals;
  20208. this.binormals = binormals;
  20209. function vert( x, y, z ) {
  20210. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20211. }
  20212. // consruct the grid
  20213. for ( i = 0; i < numpoints; i++ ) {
  20214. this.grid[ i ] = [];
  20215. u = i / ( numpoints - 1 );
  20216. pos = path.getPointAt( u );
  20217. tangent = tangents[ i ];
  20218. normal = normals[ i ];
  20219. binormal = binormals[ i ];
  20220. for ( j = 0; j < this.radialSegments; j++ ) {
  20221. v = j / this.radialSegments * 2 * Math.PI;
  20222. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20223. cy = this.radius * Math.sin( v );
  20224. pos2.copy( pos );
  20225. pos2.x += cx * normal.x + cy * binormal.x;
  20226. pos2.y += cx * normal.y + cy * binormal.y;
  20227. pos2.z += cx * normal.z + cy * binormal.z;
  20228. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20229. }
  20230. }
  20231. // construct the mesh
  20232. for ( i = 0; i < this.segments; i++ ) {
  20233. for ( j = 0; j < this.radialSegments; j++ ) {
  20234. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20235. jp = (j + 1) % this.radialSegments;
  20236. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20237. b = this.grid[ ip ][ j ];
  20238. c = this.grid[ ip ][ jp ];
  20239. d = this.grid[ i ][ jp ];
  20240. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20241. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20242. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20243. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20244. this.faces.push( new THREE.Face3( a, b, d ) );
  20245. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20246. this.faces.push( new THREE.Face3( b, c, d ) );
  20247. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20248. }
  20249. }
  20250. this.computeFaceNormals();
  20251. this.computeVertexNormals();
  20252. };
  20253. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20254. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20255. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20256. var tangent = new THREE.Vector3(),
  20257. normal = new THREE.Vector3(),
  20258. binormal = new THREE.Vector3(),
  20259. tangents = [],
  20260. normals = [],
  20261. binormals = [],
  20262. vec = new THREE.Vector3(),
  20263. mat = new THREE.Matrix4(),
  20264. numpoints = segments + 1,
  20265. theta,
  20266. epsilon = 0.0001,
  20267. smallest,
  20268. tx, ty, tz,
  20269. i, u, v;
  20270. // expose internals
  20271. this.tangents = tangents;
  20272. this.normals = normals;
  20273. this.binormals = binormals;
  20274. // compute the tangent vectors for each segment on the path
  20275. for ( i = 0; i < numpoints; i++ ) {
  20276. u = i / ( numpoints - 1 );
  20277. tangents[ i ] = path.getTangentAt( u );
  20278. tangents[ i ].normalize();
  20279. }
  20280. initialNormal3();
  20281. function initialNormal1(lastBinormal) {
  20282. // fixed start binormal. Has dangers of 0 vectors
  20283. normals[ 0 ] = new THREE.Vector3();
  20284. binormals[ 0 ] = new THREE.Vector3();
  20285. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20286. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20287. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20288. }
  20289. function initialNormal2() {
  20290. // This uses the Frenet-Serret formula for deriving binormal
  20291. var t2 = path.getTangentAt( epsilon );
  20292. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20293. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20294. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20295. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20296. }
  20297. function initialNormal3() {
  20298. // select an initial normal vector perpenicular to the first tangent vector,
  20299. // and in the direction of the smallest tangent xyz component
  20300. normals[ 0 ] = new THREE.Vector3();
  20301. binormals[ 0 ] = new THREE.Vector3();
  20302. smallest = Number.MAX_VALUE;
  20303. tx = Math.abs( tangents[ 0 ].x );
  20304. ty = Math.abs( tangents[ 0 ].y );
  20305. tz = Math.abs( tangents[ 0 ].z );
  20306. if ( tx <= smallest ) {
  20307. smallest = tx;
  20308. normal.set( 1, 0, 0 );
  20309. }
  20310. if ( ty <= smallest ) {
  20311. smallest = ty;
  20312. normal.set( 0, 1, 0 );
  20313. }
  20314. if ( tz <= smallest ) {
  20315. normal.set( 0, 0, 1 );
  20316. }
  20317. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20318. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20319. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20320. }
  20321. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20322. for ( i = 1; i < numpoints; i++ ) {
  20323. normals[ i ] = normals[ i-1 ].clone();
  20324. binormals[ i ] = binormals[ i-1 ].clone();
  20325. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20326. if ( vec.length() > epsilon ) {
  20327. vec.normalize();
  20328. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20329. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20330. }
  20331. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20332. }
  20333. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20334. if ( closed ) {
  20335. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20336. theta /= ( numpoints - 1 );
  20337. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20338. theta = -theta;
  20339. }
  20340. for ( i = 1; i < numpoints; i++ ) {
  20341. // twist a little...
  20342. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20343. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20344. }
  20345. }
  20346. };
  20347. /**
  20348. * @author clockworkgeek / https://github.com/clockworkgeek
  20349. * @author timothypratley / https://github.com/timothypratley
  20350. * @author WestLangley / http://github.com/WestLangley
  20351. */
  20352. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20353. THREE.Geometry.call( this );
  20354. radius = radius || 1;
  20355. detail = detail || 0;
  20356. var that = this;
  20357. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20358. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20359. }
  20360. var midpoints = [], p = this.vertices;
  20361. var f = [];
  20362. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20363. var v1 = p[ faces[ i ][ 0 ] ];
  20364. var v2 = p[ faces[ i ][ 1 ] ];
  20365. var v3 = p[ faces[ i ][ 2 ] ];
  20366. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20367. }
  20368. var centroid = new THREE.Vector3();
  20369. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20370. subdivide(f[ i ], detail);
  20371. }
  20372. // Handle case when face straddles the seam
  20373. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20374. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20375. var x0 = uvs[ 0 ].x;
  20376. var x1 = uvs[ 1 ].x;
  20377. var x2 = uvs[ 2 ].x;
  20378. var max = Math.max( x0, Math.max( x1, x2 ) );
  20379. var min = Math.min( x0, Math.min( x1, x2 ) );
  20380. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20381. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20382. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20383. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20384. }
  20385. }
  20386. // Apply radius
  20387. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20388. this.vertices[ i ].multiplyScalar( radius );
  20389. }
  20390. // Merge vertices
  20391. this.mergeVertices();
  20392. this.computeFaceNormals();
  20393. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20394. // Project vector onto sphere's surface
  20395. function prepare( vector ) {
  20396. var vertex = vector.normalize().clone();
  20397. vertex.index = that.vertices.push( vertex ) - 1;
  20398. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20399. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20400. var v = inclination( vector ) / Math.PI + 0.5;
  20401. vertex.uv = new THREE.Vector2( u, 1 - v );
  20402. return vertex;
  20403. }
  20404. // Approximate a curved face with recursively sub-divided triangles.
  20405. function make( v1, v2, v3 ) {
  20406. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20407. that.faces.push( face );
  20408. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20409. var azi = azimuth( centroid );
  20410. that.faceVertexUvs[ 0 ].push( [
  20411. correctUV( v1.uv, v1, azi ),
  20412. correctUV( v2.uv, v2, azi ),
  20413. correctUV( v3.uv, v3, azi )
  20414. ] );
  20415. }
  20416. // Analytically subdivide a face to the required detail level.
  20417. function subdivide( face, detail ) {
  20418. var cols = Math.pow(2, detail);
  20419. var cells = Math.pow(4, detail);
  20420. var a = prepare( that.vertices[ face.a ] );
  20421. var b = prepare( that.vertices[ face.b ] );
  20422. var c = prepare( that.vertices[ face.c ] );
  20423. var v = [];
  20424. // Construct all of the vertices for this subdivision.
  20425. for ( var i = 0 ; i <= cols; i ++ ) {
  20426. v[ i ] = [];
  20427. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20428. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20429. var rows = cols - i;
  20430. for ( var j = 0; j <= rows; j ++) {
  20431. if ( j == 0 && i == cols ) {
  20432. v[ i ][ j ] = aj;
  20433. } else {
  20434. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20435. }
  20436. }
  20437. }
  20438. // Construct all of the faces.
  20439. for ( var i = 0; i < cols ; i ++ ) {
  20440. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20441. var k = Math.floor( j / 2 );
  20442. if ( j % 2 == 0 ) {
  20443. make(
  20444. v[ i ][ k + 1],
  20445. v[ i + 1 ][ k ],
  20446. v[ i ][ k ]
  20447. );
  20448. } else {
  20449. make(
  20450. v[ i ][ k + 1 ],
  20451. v[ i + 1][ k + 1],
  20452. v[ i + 1 ][ k ]
  20453. );
  20454. }
  20455. }
  20456. }
  20457. }
  20458. // Angle around the Y axis, counter-clockwise when looking from above.
  20459. function azimuth( vector ) {
  20460. return Math.atan2( vector.z, -vector.x );
  20461. }
  20462. // Angle above the XZ plane.
  20463. function inclination( vector ) {
  20464. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20465. }
  20466. // Texture fixing helper. Spheres have some odd behaviours.
  20467. function correctUV( uv, vector, azimuth ) {
  20468. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20469. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20470. return uv.clone();
  20471. }
  20472. };
  20473. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20474. /**
  20475. * @author timothypratley / https://github.com/timothypratley
  20476. */
  20477. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20478. this.radius = radius;
  20479. this.detail = detail;
  20480. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20481. var vertices = [
  20482. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20483. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20484. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20485. ];
  20486. var faces = [
  20487. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20488. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20489. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20490. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20491. ];
  20492. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20493. };
  20494. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20495. /**
  20496. * @author timothypratley / https://github.com/timothypratley
  20497. */
  20498. THREE.OctahedronGeometry = function ( radius, detail ) {
  20499. var vertices = [
  20500. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20501. ];
  20502. var faces = [
  20503. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20504. ];
  20505. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20506. };
  20507. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20508. /**
  20509. * @author timothypratley / https://github.com/timothypratley
  20510. */
  20511. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20512. var vertices = [
  20513. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20514. ];
  20515. var faces = [
  20516. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20517. ];
  20518. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20519. };
  20520. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20521. /**
  20522. * @author zz85 / https://github.com/zz85
  20523. * Parametric Surfaces Geometry
  20524. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20525. *
  20526. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20527. *
  20528. */
  20529. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20530. THREE.Geometry.call( this );
  20531. var verts = this.vertices;
  20532. var faces = this.faces;
  20533. var uvs = this.faceVertexUvs[ 0 ];
  20534. var i, il, j, p;
  20535. var u, v;
  20536. var stackCount = stacks + 1;
  20537. var sliceCount = slices + 1;
  20538. for ( i = 0; i <= stacks; i ++ ) {
  20539. v = i / stacks;
  20540. for ( j = 0; j <= slices; j ++ ) {
  20541. u = j / slices;
  20542. p = func( u, v );
  20543. verts.push( p );
  20544. }
  20545. }
  20546. var a, b, c, d;
  20547. var uva, uvb, uvc, uvd;
  20548. for ( i = 0; i < stacks; i ++ ) {
  20549. for ( j = 0; j < slices; j ++ ) {
  20550. a = i * sliceCount + j;
  20551. b = i * sliceCount + j + 1;
  20552. c = (i + 1) * sliceCount + j + 1;
  20553. d = (i + 1) * sliceCount + j;
  20554. uva = new THREE.Vector2( j / slices, i / stacks );
  20555. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20556. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20557. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20558. faces.push( new THREE.Face3( a, b, d ) );
  20559. uvs.push( [ uva, uvb, uvd ] );
  20560. faces.push( new THREE.Face3( b, c, d ) );
  20561. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20562. }
  20563. }
  20564. // console.log(this);
  20565. // magic bullet
  20566. // var diff = this.mergeVertices();
  20567. // console.log('removed ', diff, ' vertices by merging');
  20568. this.computeFaceNormals();
  20569. this.computeVertexNormals();
  20570. };
  20571. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20572. /**
  20573. * @author sroucheray / http://sroucheray.org/
  20574. * @author mrdoob / http://mrdoob.com/
  20575. */
  20576. THREE.AxisHelper = function ( size ) {
  20577. size = size || 1;
  20578. var geometry = new THREE.Geometry();
  20579. geometry.vertices.push(
  20580. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20581. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20582. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20583. );
  20584. geometry.colors.push(
  20585. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20586. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20587. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20588. );
  20589. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20590. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20591. };
  20592. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20593. /**
  20594. * @author WestLangley / http://github.com/WestLangley
  20595. * @author zz85 / http://github.com/zz85
  20596. * @author bhouston / http://exocortex.com
  20597. *
  20598. * Creates an arrow for visualizing directions
  20599. *
  20600. * Parameters:
  20601. * dir - Vector3
  20602. * origin - Vector3
  20603. * length - Number
  20604. * hex - color in hex value
  20605. * headLength - Number
  20606. * headWidth - Number
  20607. */
  20608. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  20609. // dir is assumed to be normalized
  20610. THREE.Object3D.call( this );
  20611. if ( hex === undefined ) hex = 0xffff00;
  20612. if ( length === undefined ) length = 1;
  20613. if ( headLength === undefined ) headLength = 0.2 * length;
  20614. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20615. this.position = origin;
  20616. var lineGeometry = new THREE.Geometry();
  20617. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20618. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20619. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20620. this.line.matrixAutoUpdate = false;
  20621. this.add( this.line );
  20622. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20623. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20624. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20625. this.cone.matrixAutoUpdate = false;
  20626. this.add( this.cone );
  20627. this.setDirection( dir );
  20628. this.setLength( length, headLength, headWidth );
  20629. };
  20630. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20631. THREE.ArrowHelper.prototype.setDirection = function () {
  20632. var axis = new THREE.Vector3();
  20633. var radians;
  20634. return function ( dir ) {
  20635. // dir is assumed to be normalized
  20636. if ( dir.y > 0.99999 ) {
  20637. this.quaternion.set( 0, 0, 0, 1 );
  20638. } else if ( dir.y < - 0.99999 ) {
  20639. this.quaternion.set( 1, 0, 0, 0 );
  20640. } else {
  20641. axis.set( dir.z, 0, - dir.x ).normalize();
  20642. radians = Math.acos( dir.y );
  20643. this.quaternion.setFromAxisAngle( axis, radians );
  20644. }
  20645. };
  20646. }();
  20647. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20648. if ( headLength === undefined ) headLength = 0.2 * length;
  20649. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20650. this.line.scale.set( 1, length, 1 );
  20651. this.line.updateMatrix();
  20652. this.cone.scale.set( headWidth, headLength, headWidth );
  20653. this.cone.position.y = length;
  20654. this.cone.updateMatrix();
  20655. };
  20656. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20657. this.line.material.color.setHex( hex );
  20658. this.cone.material.color.setHex( hex );
  20659. };
  20660. /**
  20661. * @author mrdoob / http://mrdoob.com/
  20662. */
  20663. THREE.BoxHelper = function ( object ) {
  20664. // 5____4
  20665. // 1/___0/|
  20666. // | 6__|_7
  20667. // 2/___3/
  20668. var vertices = [
  20669. new THREE.Vector3( 1, 1, 1 ),
  20670. new THREE.Vector3( - 1, 1, 1 ),
  20671. new THREE.Vector3( - 1, - 1, 1 ),
  20672. new THREE.Vector3( 1, - 1, 1 ),
  20673. new THREE.Vector3( 1, 1, - 1 ),
  20674. new THREE.Vector3( - 1, 1, - 1 ),
  20675. new THREE.Vector3( - 1, - 1, - 1 ),
  20676. new THREE.Vector3( 1, - 1, - 1 )
  20677. ];
  20678. this.vertices = vertices;
  20679. // TODO: Wouldn't be nice if Line had .segments?
  20680. var geometry = new THREE.Geometry();
  20681. geometry.vertices.push(
  20682. vertices[ 0 ], vertices[ 1 ],
  20683. vertices[ 1 ], vertices[ 2 ],
  20684. vertices[ 2 ], vertices[ 3 ],
  20685. vertices[ 3 ], vertices[ 0 ],
  20686. vertices[ 4 ], vertices[ 5 ],
  20687. vertices[ 5 ], vertices[ 6 ],
  20688. vertices[ 6 ], vertices[ 7 ],
  20689. vertices[ 7 ], vertices[ 4 ],
  20690. vertices[ 0 ], vertices[ 4 ],
  20691. vertices[ 1 ], vertices[ 5 ],
  20692. vertices[ 2 ], vertices[ 6 ],
  20693. vertices[ 3 ], vertices[ 7 ]
  20694. );
  20695. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20696. if ( object !== undefined ) {
  20697. this.update( object );
  20698. }
  20699. };
  20700. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20701. THREE.BoxHelper.prototype.update = function ( object ) {
  20702. var geometry = object.geometry;
  20703. if ( geometry.boundingBox === null ) {
  20704. geometry.computeBoundingBox();
  20705. }
  20706. var min = geometry.boundingBox.min;
  20707. var max = geometry.boundingBox.max;
  20708. var vertices = this.vertices;
  20709. vertices[ 0 ].set( max.x, max.y, max.z );
  20710. vertices[ 1 ].set( min.x, max.y, max.z );
  20711. vertices[ 2 ].set( min.x, min.y, max.z );
  20712. vertices[ 3 ].set( max.x, min.y, max.z );
  20713. vertices[ 4 ].set( max.x, max.y, min.z );
  20714. vertices[ 5 ].set( min.x, max.y, min.z );
  20715. vertices[ 6 ].set( min.x, min.y, min.z );
  20716. vertices[ 7 ].set( max.x, min.y, min.z );
  20717. this.geometry.computeBoundingSphere();
  20718. this.geometry.verticesNeedUpdate = true;
  20719. this.matrixAutoUpdate = false;
  20720. this.matrixWorld = object.matrixWorld;
  20721. };
  20722. /**
  20723. * @author WestLangley / http://github.com/WestLangley
  20724. */
  20725. // a helper to show the world-axis-aligned bounding box for an object
  20726. THREE.BoundingBoxHelper = function ( object, hex ) {
  20727. var color = ( hex !== undefined ) ? hex : 0x888888;
  20728. this.object = object;
  20729. this.box = new THREE.Box3();
  20730. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20731. };
  20732. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20733. THREE.BoundingBoxHelper.prototype.update = function () {
  20734. this.box.setFromObject( this.object );
  20735. this.box.size( this.scale );
  20736. this.box.center( this.position );
  20737. };
  20738. /**
  20739. * @author alteredq / http://alteredqualia.com/
  20740. *
  20741. * - shows frustum, line of sight and up of the camera
  20742. * - suitable for fast updates
  20743. * - based on frustum visualization in lightgl.js shadowmap example
  20744. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20745. */
  20746. THREE.CameraHelper = function ( camera ) {
  20747. var geometry = new THREE.Geometry();
  20748. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20749. var pointMap = {};
  20750. // colors
  20751. var hexFrustum = 0xffaa00;
  20752. var hexCone = 0xff0000;
  20753. var hexUp = 0x00aaff;
  20754. var hexTarget = 0xffffff;
  20755. var hexCross = 0x333333;
  20756. // near
  20757. addLine( "n1", "n2", hexFrustum );
  20758. addLine( "n2", "n4", hexFrustum );
  20759. addLine( "n4", "n3", hexFrustum );
  20760. addLine( "n3", "n1", hexFrustum );
  20761. // far
  20762. addLine( "f1", "f2", hexFrustum );
  20763. addLine( "f2", "f4", hexFrustum );
  20764. addLine( "f4", "f3", hexFrustum );
  20765. addLine( "f3", "f1", hexFrustum );
  20766. // sides
  20767. addLine( "n1", "f1", hexFrustum );
  20768. addLine( "n2", "f2", hexFrustum );
  20769. addLine( "n3", "f3", hexFrustum );
  20770. addLine( "n4", "f4", hexFrustum );
  20771. // cone
  20772. addLine( "p", "n1", hexCone );
  20773. addLine( "p", "n2", hexCone );
  20774. addLine( "p", "n3", hexCone );
  20775. addLine( "p", "n4", hexCone );
  20776. // up
  20777. addLine( "u1", "u2", hexUp );
  20778. addLine( "u2", "u3", hexUp );
  20779. addLine( "u3", "u1", hexUp );
  20780. // target
  20781. addLine( "c", "t", hexTarget );
  20782. addLine( "p", "c", hexCross );
  20783. // cross
  20784. addLine( "cn1", "cn2", hexCross );
  20785. addLine( "cn3", "cn4", hexCross );
  20786. addLine( "cf1", "cf2", hexCross );
  20787. addLine( "cf3", "cf4", hexCross );
  20788. function addLine( a, b, hex ) {
  20789. addPoint( a, hex );
  20790. addPoint( b, hex );
  20791. }
  20792. function addPoint( id, hex ) {
  20793. geometry.vertices.push( new THREE.Vector3() );
  20794. geometry.colors.push( new THREE.Color( hex ) );
  20795. if ( pointMap[ id ] === undefined ) {
  20796. pointMap[ id ] = [];
  20797. }
  20798. pointMap[ id ].push( geometry.vertices.length - 1 );
  20799. }
  20800. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20801. this.camera = camera;
  20802. this.matrixWorld = camera.matrixWorld;
  20803. this.matrixAutoUpdate = false;
  20804. this.pointMap = pointMap;
  20805. this.update();
  20806. };
  20807. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20808. THREE.CameraHelper.prototype.update = function () {
  20809. var vector = new THREE.Vector3();
  20810. var camera = new THREE.Camera();
  20811. var projector = new THREE.Projector();
  20812. return function () {
  20813. var scope = this;
  20814. var w = 1, h = 1;
  20815. // we need just camera projection matrix
  20816. // world matrix must be identity
  20817. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20818. // center / target
  20819. setPoint( "c", 0, 0, -1 );
  20820. setPoint( "t", 0, 0, 1 );
  20821. // near
  20822. setPoint( "n1", -w, -h, -1 );
  20823. setPoint( "n2", w, -h, -1 );
  20824. setPoint( "n3", -w, h, -1 );
  20825. setPoint( "n4", w, h, -1 );
  20826. // far
  20827. setPoint( "f1", -w, -h, 1 );
  20828. setPoint( "f2", w, -h, 1 );
  20829. setPoint( "f3", -w, h, 1 );
  20830. setPoint( "f4", w, h, 1 );
  20831. // up
  20832. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20833. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20834. setPoint( "u3", 0, h * 2, -1 );
  20835. // cross
  20836. setPoint( "cf1", -w, 0, 1 );
  20837. setPoint( "cf2", w, 0, 1 );
  20838. setPoint( "cf3", 0, -h, 1 );
  20839. setPoint( "cf4", 0, h, 1 );
  20840. setPoint( "cn1", -w, 0, -1 );
  20841. setPoint( "cn2", w, 0, -1 );
  20842. setPoint( "cn3", 0, -h, -1 );
  20843. setPoint( "cn4", 0, h, -1 );
  20844. function setPoint( point, x, y, z ) {
  20845. vector.set( x, y, z );
  20846. projector.unprojectVector( vector, camera );
  20847. var points = scope.pointMap[ point ];
  20848. if ( points !== undefined ) {
  20849. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20850. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20851. }
  20852. }
  20853. }
  20854. this.geometry.verticesNeedUpdate = true;
  20855. };
  20856. }();
  20857. /**
  20858. * @author alteredq / http://alteredqualia.com/
  20859. * @author mrdoob / http://mrdoob.com/
  20860. * @author WestLangley / http://github.com/WestLangley
  20861. */
  20862. THREE.DirectionalLightHelper = function ( light, size ) {
  20863. THREE.Object3D.call( this );
  20864. this.light = light;
  20865. this.light.updateMatrixWorld();
  20866. this.matrixWorld = light.matrixWorld;
  20867. this.matrixAutoUpdate = false;
  20868. size = size || 1;
  20869. var geometry = new THREE.Geometry();
  20870. geometry.vertices.push(
  20871. new THREE.Vector3( - size, size, 0 ),
  20872. new THREE.Vector3( size, size, 0 ),
  20873. new THREE.Vector3( size, - size, 0 ),
  20874. new THREE.Vector3( - size, - size, 0 ),
  20875. new THREE.Vector3( - size, size, 0 )
  20876. );
  20877. var material = new THREE.LineBasicMaterial( { fog: false } );
  20878. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20879. this.lightPlane = new THREE.Line( geometry, material );
  20880. this.add( this.lightPlane );
  20881. geometry = new THREE.Geometry();
  20882. geometry.vertices.push(
  20883. new THREE.Vector3(),
  20884. new THREE.Vector3()
  20885. );
  20886. material = new THREE.LineBasicMaterial( { fog: false } );
  20887. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20888. this.targetLine = new THREE.Line( geometry, material );
  20889. this.add( this.targetLine );
  20890. this.update();
  20891. };
  20892. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20893. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20894. this.lightPlane.geometry.dispose();
  20895. this.lightPlane.material.dispose();
  20896. this.targetLine.geometry.dispose();
  20897. this.targetLine.material.dispose();
  20898. };
  20899. THREE.DirectionalLightHelper.prototype.update = function () {
  20900. var v1 = new THREE.Vector3();
  20901. var v2 = new THREE.Vector3();
  20902. var v3 = new THREE.Vector3();
  20903. return function () {
  20904. v1.setFromMatrixPosition( this.light.matrixWorld );
  20905. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20906. v3.subVectors( v2, v1 );
  20907. this.lightPlane.lookAt( v3 );
  20908. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20909. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20910. this.targetLine.geometry.verticesNeedUpdate = true;
  20911. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20912. }
  20913. }();
  20914. /**
  20915. * @author WestLangley / http://github.com/WestLangley
  20916. */
  20917. THREE.EdgesHelper = function ( object, hex ) {
  20918. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20919. var edge = [ 0, 0 ], hash = {};
  20920. var sortFunction = function ( a, b ) { return a - b };
  20921. var keys = [ 'a', 'b', 'c' ];
  20922. var geometry = new THREE.BufferGeometry();
  20923. var geometry2 = object.geometry.clone();
  20924. geometry2.mergeVertices();
  20925. geometry2.computeFaceNormals();
  20926. var vertices = geometry2.vertices;
  20927. var faces = geometry2.faces;
  20928. var numEdges = 0;
  20929. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20930. var face = faces[ i ];
  20931. for ( var j = 0; j < 3; j ++ ) {
  20932. edge[ 0 ] = face[ keys[ j ] ];
  20933. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20934. edge.sort( sortFunction );
  20935. var key = edge.toString();
  20936. if ( hash[ key ] === undefined ) {
  20937. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20938. numEdges ++;
  20939. } else {
  20940. hash[ key ].face2 = i;
  20941. }
  20942. }
  20943. }
  20944. geometry.addAttribute( 'position', new Float32Array( numEdges * 2 * 3 ), 3 );
  20945. var coords = geometry.attributes.position.array;
  20946. var index = 0;
  20947. for ( var key in hash ) {
  20948. var h = hash[ key ];
  20949. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  20950. var vertex = vertices[ h.vert1 ];
  20951. coords[ index ++ ] = vertex.x;
  20952. coords[ index ++ ] = vertex.y;
  20953. coords[ index ++ ] = vertex.z;
  20954. vertex = vertices[ h.vert2 ];
  20955. coords[ index ++ ] = vertex.x;
  20956. coords[ index ++ ] = vertex.y;
  20957. coords[ index ++ ] = vertex.z;
  20958. }
  20959. }
  20960. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20961. this.matrixAutoUpdate = false;
  20962. this.matrixWorld = object.matrixWorld;
  20963. };
  20964. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20965. /**
  20966. * @author mrdoob / http://mrdoob.com/
  20967. * @author WestLangley / http://github.com/WestLangley
  20968. */
  20969. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20970. this.object = object;
  20971. this.size = ( size !== undefined ) ? size : 1;
  20972. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20973. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20974. var geometry = new THREE.Geometry();
  20975. var faces = this.object.geometry.faces;
  20976. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20977. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20978. }
  20979. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20980. this.matrixAutoUpdate = false;
  20981. this.normalMatrix = new THREE.Matrix3();
  20982. this.update();
  20983. };
  20984. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20985. THREE.FaceNormalsHelper.prototype.update = function () {
  20986. var vertices = this.geometry.vertices;
  20987. var object = this.object;
  20988. var objectVertices = object.geometry.vertices;
  20989. var objectFaces = object.geometry.faces;
  20990. var objectWorldMatrix = object.matrixWorld;
  20991. object.updateMatrixWorld( true );
  20992. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20993. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20994. var face = objectFaces[ i ];
  20995. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20996. .add( objectVertices[ face.b ] )
  20997. .add( objectVertices[ face.c ] )
  20998. .divideScalar( 3 )
  20999. .applyMatrix4( objectWorldMatrix );
  21000. vertices[ i2 + 1 ].copy( face.normal )
  21001. .applyMatrix3( this.normalMatrix )
  21002. .normalize()
  21003. .multiplyScalar( this.size )
  21004. .add( vertices[ i2 ] );
  21005. }
  21006. this.geometry.verticesNeedUpdate = true;
  21007. return this;
  21008. };
  21009. /**
  21010. * @author mrdoob / http://mrdoob.com/
  21011. */
  21012. THREE.GridHelper = function ( size, step ) {
  21013. var geometry = new THREE.Geometry();
  21014. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21015. this.color1 = new THREE.Color( 0x444444 );
  21016. this.color2 = new THREE.Color( 0x888888 );
  21017. for ( var i = - size; i <= size; i += step ) {
  21018. geometry.vertices.push(
  21019. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21020. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21021. );
  21022. var color = i === 0 ? this.color1 : this.color2;
  21023. geometry.colors.push( color, color, color, color );
  21024. }
  21025. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21026. };
  21027. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21028. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21029. this.color1.set( colorCenterLine );
  21030. this.color2.set( colorGrid );
  21031. this.geometry.colorsNeedUpdate = true;
  21032. }
  21033. /**
  21034. * @author alteredq / http://alteredqualia.com/
  21035. * @author mrdoob / http://mrdoob.com/
  21036. */
  21037. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21038. THREE.Object3D.call( this );
  21039. this.light = light;
  21040. this.light.updateMatrixWorld();
  21041. this.matrixWorld = light.matrixWorld;
  21042. this.matrixAutoUpdate = false;
  21043. this.colors = [ new THREE.Color(), new THREE.Color() ];
  21044. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21045. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21046. for ( var i = 0, il = 8; i < il; i ++ ) {
  21047. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  21048. }
  21049. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  21050. this.lightSphere = new THREE.Mesh( geometry, material );
  21051. this.add( this.lightSphere );
  21052. this.update();
  21053. };
  21054. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21055. THREE.HemisphereLightHelper.prototype.dispose = function () {
  21056. this.lightSphere.geometry.dispose();
  21057. this.lightSphere.material.dispose();
  21058. };
  21059. THREE.HemisphereLightHelper.prototype.update = function () {
  21060. var vector = new THREE.Vector3();
  21061. return function () {
  21062. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  21063. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21064. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  21065. this.lightSphere.geometry.colorsNeedUpdate = true;
  21066. }
  21067. }();
  21068. /**
  21069. * @author alteredq / http://alteredqualia.com/
  21070. * @author mrdoob / http://mrdoob.com/
  21071. */
  21072. THREE.PointLightHelper = function ( light, sphereSize ) {
  21073. this.light = light;
  21074. this.light.updateMatrixWorld();
  21075. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21076. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21077. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21078. THREE.Mesh.call( this, geometry, material );
  21079. this.matrixWorld = this.light.matrixWorld;
  21080. this.matrixAutoUpdate = false;
  21081. /*
  21082. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21083. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21084. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21085. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21086. var d = light.distance;
  21087. if ( d === 0.0 ) {
  21088. this.lightDistance.visible = false;
  21089. } else {
  21090. this.lightDistance.scale.set( d, d, d );
  21091. }
  21092. this.add( this.lightDistance );
  21093. */
  21094. };
  21095. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21096. THREE.PointLightHelper.prototype.dispose = function () {
  21097. this.geometry.dispose();
  21098. this.material.dispose();
  21099. };
  21100. THREE.PointLightHelper.prototype.update = function () {
  21101. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21102. /*
  21103. var d = this.light.distance;
  21104. if ( d === 0.0 ) {
  21105. this.lightDistance.visible = false;
  21106. } else {
  21107. this.lightDistance.visible = true;
  21108. this.lightDistance.scale.set( d, d, d );
  21109. }
  21110. */
  21111. };
  21112. /**
  21113. * @author alteredq / http://alteredqualia.com/
  21114. * @author mrdoob / http://mrdoob.com/
  21115. * @author WestLangley / http://github.com/WestLangley
  21116. */
  21117. THREE.SpotLightHelper = function ( light ) {
  21118. THREE.Object3D.call( this );
  21119. this.light = light;
  21120. this.light.updateMatrixWorld();
  21121. this.matrixWorld = light.matrixWorld;
  21122. this.matrixAutoUpdate = false;
  21123. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21124. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21125. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21126. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21127. this.cone = new THREE.Mesh( geometry, material );
  21128. this.add( this.cone );
  21129. this.update();
  21130. };
  21131. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21132. THREE.SpotLightHelper.prototype.dispose = function () {
  21133. this.cone.geometry.dispose();
  21134. this.cone.material.dispose();
  21135. };
  21136. THREE.SpotLightHelper.prototype.update = function () {
  21137. var vector = new THREE.Vector3();
  21138. var vector2 = new THREE.Vector3();
  21139. return function () {
  21140. var coneLength = this.light.distance ? this.light.distance : 10000;
  21141. var coneWidth = coneLength * Math.tan( this.light.angle );
  21142. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  21143. vector.setFromMatrixPosition( this.light.matrixWorld );
  21144. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  21145. this.cone.lookAt( vector2.sub( vector ) );
  21146. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21147. };
  21148. }();
  21149. /**
  21150. * @author mrdoob / http://mrdoob.com/
  21151. * @author WestLangley / http://github.com/WestLangley
  21152. */
  21153. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21154. this.object = object;
  21155. this.size = ( size !== undefined ) ? size : 1;
  21156. var color = ( hex !== undefined ) ? hex : 0xff0000;
  21157. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21158. var geometry = new THREE.Geometry();
  21159. var vertices = object.geometry.vertices;
  21160. var faces = object.geometry.faces;
  21161. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21162. var face = faces[ i ];
  21163. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21164. geometry.vertices.push( new THREE.Vector3() );
  21165. geometry.vertices.push( new THREE.Vector3() );
  21166. }
  21167. }
  21168. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21169. this.matrixAutoUpdate = false;
  21170. this.normalMatrix = new THREE.Matrix3();
  21171. this.update();
  21172. };
  21173. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21174. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21175. var v1 = new THREE.Vector3();
  21176. return function( object ) {
  21177. var keys = [ 'a', 'b', 'c', 'd' ];
  21178. this.object.updateMatrixWorld( true );
  21179. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21180. var vertices = this.geometry.vertices;
  21181. var verts = this.object.geometry.vertices;
  21182. var faces = this.object.geometry.faces;
  21183. var worldMatrix = this.object.matrixWorld;
  21184. var idx = 0;
  21185. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21186. var face = faces[ i ];
  21187. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21188. var vertexId = face[ keys[ j ] ];
  21189. var vertex = verts[ vertexId ];
  21190. var normal = face.vertexNormals[ j ];
  21191. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21192. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21193. v1.add( vertices[ idx ] );
  21194. idx = idx + 1;
  21195. vertices[ idx ].copy( v1 );
  21196. idx = idx + 1;
  21197. }
  21198. }
  21199. this.geometry.verticesNeedUpdate = true;
  21200. return this;
  21201. }
  21202. }());
  21203. /**
  21204. * @author mrdoob / http://mrdoob.com/
  21205. * @author WestLangley / http://github.com/WestLangley
  21206. */
  21207. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21208. this.object = object;
  21209. this.size = ( size !== undefined ) ? size : 1;
  21210. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  21211. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21212. var geometry = new THREE.Geometry();
  21213. var vertices = object.geometry.vertices;
  21214. var faces = object.geometry.faces;
  21215. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21216. var face = faces[ i ];
  21217. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21218. geometry.vertices.push( new THREE.Vector3() );
  21219. geometry.vertices.push( new THREE.Vector3() );
  21220. }
  21221. }
  21222. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21223. this.matrixAutoUpdate = false;
  21224. this.update();
  21225. };
  21226. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21227. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21228. var v1 = new THREE.Vector3();
  21229. return function( object ) {
  21230. var keys = [ 'a', 'b', 'c', 'd' ];
  21231. this.object.updateMatrixWorld( true );
  21232. var vertices = this.geometry.vertices;
  21233. var verts = this.object.geometry.vertices;
  21234. var faces = this.object.geometry.faces;
  21235. var worldMatrix = this.object.matrixWorld;
  21236. var idx = 0;
  21237. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21238. var face = faces[ i ];
  21239. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21240. var vertexId = face[ keys[ j ] ];
  21241. var vertex = verts[ vertexId ];
  21242. var tangent = face.vertexTangents[ j ];
  21243. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21244. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21245. v1.add( vertices[ idx ] );
  21246. idx = idx + 1;
  21247. vertices[ idx ].copy( v1 );
  21248. idx = idx + 1;
  21249. }
  21250. }
  21251. this.geometry.verticesNeedUpdate = true;
  21252. return this;
  21253. }
  21254. }());
  21255. /**
  21256. * @author mrdoob / http://mrdoob.com/
  21257. */
  21258. THREE.WireframeHelper = function ( object, hex ) {
  21259. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21260. var edge = [ 0, 0 ], hash = {};
  21261. var sortFunction = function ( a, b ) { return a - b };
  21262. var keys = [ 'a', 'b', 'c' ];
  21263. var geometry = new THREE.BufferGeometry();
  21264. if ( object.geometry instanceof THREE.Geometry ) {
  21265. var vertices = object.geometry.vertices;
  21266. var faces = object.geometry.faces;
  21267. var numEdges = 0;
  21268. // allocate maximal size
  21269. var edges = new Uint32Array( 6 * faces.length );
  21270. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21271. var face = faces[ i ];
  21272. for ( var j = 0; j < 3; j ++ ) {
  21273. edge[ 0 ] = face[ keys[ j ] ];
  21274. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21275. edge.sort( sortFunction );
  21276. var key = edge.toString();
  21277. if ( hash[ key ] === undefined ) {
  21278. edges[ 2 * numEdges ] = edge[ 0 ];
  21279. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21280. hash[ key ] = true;
  21281. numEdges ++;
  21282. }
  21283. }
  21284. }
  21285. geometry.addAttribute( 'position', new Float32Array( numEdges * 2 * 3 ), 3 );
  21286. var coords = geometry.attributes.position.array;
  21287. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21288. for ( var j = 0; j < 2; j ++ ) {
  21289. var vertex = vertices[ edges [ 2 * i + j] ];
  21290. var index = 6 * i + 3 * j;
  21291. coords[ index + 0 ] = vertex.x;
  21292. coords[ index + 1 ] = vertex.y;
  21293. coords[ index + 2 ] = vertex.z;
  21294. }
  21295. }
  21296. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  21297. var vertices = object.geometry.attributes.position.array;
  21298. var indices = object.geometry.attributes.index.array;
  21299. var offsets = object.geometry.offsets;
  21300. var numEdges = 0;
  21301. // allocate maximal size
  21302. var edges = new Uint32Array( 2 * indices.length );
  21303. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  21304. var start = offsets[ o ].start;
  21305. var count = offsets[ o ].count;
  21306. var index = offsets[ o ].index;
  21307. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21308. for ( var j = 0; j < 3; j ++ ) {
  21309. edge[ 0 ] = index + indices[ i + j ];
  21310. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  21311. edge.sort( sortFunction );
  21312. var key = edge.toString();
  21313. if ( hash[ key ] === undefined ) {
  21314. edges[ 2 * numEdges ] = edge[ 0 ];
  21315. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21316. hash[ key ] = true;
  21317. numEdges ++;
  21318. }
  21319. }
  21320. }
  21321. }
  21322. geometry.addAttribute( 'position', new Float32Array( numEdges * 2 * 3 ), 3 );
  21323. var coords = geometry.attributes.position.array;
  21324. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21325. for ( var j = 0; j < 2; j ++ ) {
  21326. var index = 6 * i + 3 * j;
  21327. var index2 = 3 * edges[ 2 * i + j];
  21328. coords[ index + 0 ] = vertices[ index2 ];
  21329. coords[ index + 1 ] = vertices[ index2 + 1 ];
  21330. coords[ index + 2 ] = vertices[ index2 + 2 ];
  21331. }
  21332. }
  21333. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  21334. var vertices = object.geometry.attributes.position.array;
  21335. var numEdges = vertices.length / 3;
  21336. var numTris = numEdges / 3;
  21337. geometry.addAttribute( 'position', new Float32Array( numEdges * 2 * 3 ), 3 );
  21338. var coords = geometry.attributes.position.array;
  21339. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21340. for ( var j = 0; j < 3; j ++ ) {
  21341. var index = 18 * i + 6 * j;
  21342. var index1 = 9 * i + 3 * j;
  21343. coords[ index + 0 ] = vertices[ index1 ];
  21344. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21345. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21346. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21347. coords[ index + 3 ] = vertices[ index2 ];
  21348. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21349. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21350. }
  21351. }
  21352. }
  21353. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21354. this.matrixAutoUpdate = false;
  21355. this.matrixWorld = object.matrixWorld;
  21356. };
  21357. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21358. /**
  21359. * @author alteredq / http://alteredqualia.com/
  21360. */
  21361. THREE.ImmediateRenderObject = function () {
  21362. THREE.Object3D.call( this );
  21363. this.render = function ( renderCallback ) { };
  21364. };
  21365. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21366. /**
  21367. * @author mikael emtinger / http://gomo.se/
  21368. * @author alteredq / http://alteredqualia.com/
  21369. */
  21370. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21371. THREE.Object3D.call( this );
  21372. this.lensFlares = [];
  21373. this.positionScreen = new THREE.Vector3();
  21374. this.customUpdateCallback = undefined;
  21375. if( texture !== undefined ) {
  21376. this.add( texture, size, distance, blending, color );
  21377. }
  21378. };
  21379. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21380. /*
  21381. * Add: adds another flare
  21382. */
  21383. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21384. if( size === undefined ) size = -1;
  21385. if( distance === undefined ) distance = 0;
  21386. if( opacity === undefined ) opacity = 1;
  21387. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21388. if( blending === undefined ) blending = THREE.NormalBlending;
  21389. distance = Math.min( distance, Math.max( 0, distance ) );
  21390. this.lensFlares.push( { texture: texture, // THREE.Texture
  21391. size: size, // size in pixels (-1 = use texture.width)
  21392. distance: distance, // distance (0-1) from light source (0=at light source)
  21393. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21394. scale: 1, // scale
  21395. rotation: 1, // rotation
  21396. opacity: opacity, // opacity
  21397. color: color, // color
  21398. blending: blending } ); // blending
  21399. };
  21400. /*
  21401. * Update lens flares update positions on all flares based on the screen position
  21402. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21403. */
  21404. THREE.LensFlare.prototype.updateLensFlares = function () {
  21405. var f, fl = this.lensFlares.length;
  21406. var flare;
  21407. var vecX = -this.positionScreen.x * 2;
  21408. var vecY = -this.positionScreen.y * 2;
  21409. for( f = 0; f < fl; f ++ ) {
  21410. flare = this.lensFlares[ f ];
  21411. flare.x = this.positionScreen.x + vecX * flare.distance;
  21412. flare.y = this.positionScreen.y + vecY * flare.distance;
  21413. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21414. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21415. }
  21416. };
  21417. /**
  21418. * @author alteredq / http://alteredqualia.com/
  21419. */
  21420. THREE.MorphBlendMesh = function( geometry, material ) {
  21421. THREE.Mesh.call( this, geometry, material );
  21422. this.animationsMap = {};
  21423. this.animationsList = [];
  21424. // prepare default animation
  21425. // (all frames played together in 1 second)
  21426. var numFrames = this.geometry.morphTargets.length;
  21427. var name = "__default";
  21428. var startFrame = 0;
  21429. var endFrame = numFrames - 1;
  21430. var fps = numFrames / 1;
  21431. this.createAnimation( name, startFrame, endFrame, fps );
  21432. this.setAnimationWeight( name, 1 );
  21433. };
  21434. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21435. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21436. var animation = {
  21437. startFrame: start,
  21438. endFrame: end,
  21439. length: end - start + 1,
  21440. fps: fps,
  21441. duration: ( end - start ) / fps,
  21442. lastFrame: 0,
  21443. currentFrame: 0,
  21444. active: false,
  21445. time: 0,
  21446. direction: 1,
  21447. weight: 1,
  21448. directionBackwards: false,
  21449. mirroredLoop: false
  21450. };
  21451. this.animationsMap[ name ] = animation;
  21452. this.animationsList.push( animation );
  21453. };
  21454. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21455. var pattern = /([a-z]+)(\d+)/;
  21456. var firstAnimation, frameRanges = {};
  21457. var geometry = this.geometry;
  21458. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21459. var morph = geometry.morphTargets[ i ];
  21460. var chunks = morph.name.match( pattern );
  21461. if ( chunks && chunks.length > 1 ) {
  21462. var name = chunks[ 1 ];
  21463. var num = chunks[ 2 ];
  21464. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21465. var range = frameRanges[ name ];
  21466. if ( i < range.start ) range.start = i;
  21467. if ( i > range.end ) range.end = i;
  21468. if ( ! firstAnimation ) firstAnimation = name;
  21469. }
  21470. }
  21471. for ( var name in frameRanges ) {
  21472. var range = frameRanges[ name ];
  21473. this.createAnimation( name, range.start, range.end, fps );
  21474. }
  21475. this.firstAnimation = firstAnimation;
  21476. };
  21477. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21478. var animation = this.animationsMap[ name ];
  21479. if ( animation ) {
  21480. animation.direction = 1;
  21481. animation.directionBackwards = false;
  21482. }
  21483. };
  21484. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21485. var animation = this.animationsMap[ name ];
  21486. if ( animation ) {
  21487. animation.direction = -1;
  21488. animation.directionBackwards = true;
  21489. }
  21490. };
  21491. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21492. var animation = this.animationsMap[ name ];
  21493. if ( animation ) {
  21494. animation.fps = fps;
  21495. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21496. }
  21497. };
  21498. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21499. var animation = this.animationsMap[ name ];
  21500. if ( animation ) {
  21501. animation.duration = duration;
  21502. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21503. }
  21504. };
  21505. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21506. var animation = this.animationsMap[ name ];
  21507. if ( animation ) {
  21508. animation.weight = weight;
  21509. }
  21510. };
  21511. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21512. var animation = this.animationsMap[ name ];
  21513. if ( animation ) {
  21514. animation.time = time;
  21515. }
  21516. };
  21517. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21518. var time = 0;
  21519. var animation = this.animationsMap[ name ];
  21520. if ( animation ) {
  21521. time = animation.time;
  21522. }
  21523. return time;
  21524. };
  21525. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21526. var duration = -1;
  21527. var animation = this.animationsMap[ name ];
  21528. if ( animation ) {
  21529. duration = animation.duration;
  21530. }
  21531. return duration;
  21532. };
  21533. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21534. var animation = this.animationsMap[ name ];
  21535. if ( animation ) {
  21536. animation.time = 0;
  21537. animation.active = true;
  21538. } else {
  21539. console.warn( "animation[" + name + "] undefined" );
  21540. }
  21541. };
  21542. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21543. var animation = this.animationsMap[ name ];
  21544. if ( animation ) {
  21545. animation.active = false;
  21546. }
  21547. };
  21548. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21549. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21550. var animation = this.animationsList[ i ];
  21551. if ( ! animation.active ) continue;
  21552. var frameTime = animation.duration / animation.length;
  21553. animation.time += animation.direction * delta;
  21554. if ( animation.mirroredLoop ) {
  21555. if ( animation.time > animation.duration || animation.time < 0 ) {
  21556. animation.direction *= -1;
  21557. if ( animation.time > animation.duration ) {
  21558. animation.time = animation.duration;
  21559. animation.directionBackwards = true;
  21560. }
  21561. if ( animation.time < 0 ) {
  21562. animation.time = 0;
  21563. animation.directionBackwards = false;
  21564. }
  21565. }
  21566. } else {
  21567. animation.time = animation.time % animation.duration;
  21568. if ( animation.time < 0 ) animation.time += animation.duration;
  21569. }
  21570. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21571. var weight = animation.weight;
  21572. if ( keyframe !== animation.currentFrame ) {
  21573. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21574. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21575. this.morphTargetInfluences[ keyframe ] = 0;
  21576. animation.lastFrame = animation.currentFrame;
  21577. animation.currentFrame = keyframe;
  21578. }
  21579. var mix = ( animation.time % frameTime ) / frameTime;
  21580. if ( animation.directionBackwards ) mix = 1 - mix;
  21581. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21582. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21583. }
  21584. };
  21585. /**
  21586. * @author mikael emtinger / http://gomo.se/
  21587. * @author alteredq / http://alteredqualia.com/
  21588. */
  21589. THREE.LensFlarePlugin = function () {
  21590. var _gl, _renderer, _precision, _lensFlare = {};
  21591. this.init = function ( renderer ) {
  21592. _gl = renderer.context;
  21593. _renderer = renderer;
  21594. _precision = renderer.getPrecision();
  21595. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21596. _lensFlare.faces = new Uint16Array( 6 );
  21597. var i = 0;
  21598. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21599. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21600. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21601. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21602. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21603. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21604. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21605. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21606. i = 0;
  21607. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21608. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21609. // buffers
  21610. _lensFlare.vertexBuffer = _gl.createBuffer();
  21611. _lensFlare.elementBuffer = _gl.createBuffer();
  21612. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21613. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21614. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21615. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21616. // textures
  21617. _lensFlare.tempTexture = _gl.createTexture();
  21618. _lensFlare.occlusionTexture = _gl.createTexture();
  21619. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21620. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21621. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21622. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21623. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21624. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21625. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21626. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21627. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21628. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21629. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21630. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21631. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21632. _lensFlare.hasVertexTexture = false;
  21633. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21634. } else {
  21635. _lensFlare.hasVertexTexture = true;
  21636. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21637. }
  21638. _lensFlare.attributes = {};
  21639. _lensFlare.uniforms = {};
  21640. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21641. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21642. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21643. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21644. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21645. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21646. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21647. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21648. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21649. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21650. };
  21651. /*
  21652. * Render lens flares
  21653. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21654. * reads these back and calculates occlusion.
  21655. * Then _lensFlare.update_lensFlares() is called to re-position and
  21656. * update transparency of flares. Then they are rendered.
  21657. *
  21658. */
  21659. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21660. var flares = scene.__webglFlares,
  21661. nFlares = flares.length;
  21662. if ( ! nFlares ) return;
  21663. var tempPosition = new THREE.Vector3();
  21664. var invAspect = viewportHeight / viewportWidth,
  21665. halfViewportWidth = viewportWidth * 0.5,
  21666. halfViewportHeight = viewportHeight * 0.5;
  21667. var size = 16 / viewportHeight,
  21668. scale = new THREE.Vector2( size * invAspect, size );
  21669. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21670. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21671. var uniforms = _lensFlare.uniforms,
  21672. attributes = _lensFlare.attributes;
  21673. // set _lensFlare program and reset blending
  21674. _gl.useProgram( _lensFlare.program );
  21675. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21676. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21677. // loop through all lens flares to update their occlusion and positions
  21678. // setup gl and common used attribs/unforms
  21679. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21680. _gl.uniform1i( uniforms.map, 1 );
  21681. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21682. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21683. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21684. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21685. _gl.disable( _gl.CULL_FACE );
  21686. _gl.depthMask( false );
  21687. var i, j, jl, flare, sprite;
  21688. for ( i = 0; i < nFlares; i ++ ) {
  21689. size = 16 / viewportHeight;
  21690. scale.set( size * invAspect, size );
  21691. // calc object screen position
  21692. flare = flares[ i ];
  21693. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21694. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21695. tempPosition.applyProjection( camera.projectionMatrix );
  21696. // setup arrays for gl programs
  21697. screenPosition.copy( tempPosition )
  21698. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21699. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21700. // screen cull
  21701. if ( _lensFlare.hasVertexTexture || (
  21702. screenPositionPixels.x > 0 &&
  21703. screenPositionPixels.x < viewportWidth &&
  21704. screenPositionPixels.y > 0 &&
  21705. screenPositionPixels.y < viewportHeight ) ) {
  21706. // save current RGB to temp texture
  21707. _gl.activeTexture( _gl.TEXTURE1 );
  21708. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21709. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21710. // render pink quad
  21711. _gl.uniform1i( uniforms.renderType, 0 );
  21712. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21713. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21714. _gl.disable( _gl.BLEND );
  21715. _gl.enable( _gl.DEPTH_TEST );
  21716. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21717. // copy result to occlusionMap
  21718. _gl.activeTexture( _gl.TEXTURE0 );
  21719. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21720. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21721. // restore graphics
  21722. _gl.uniform1i( uniforms.renderType, 1 );
  21723. _gl.disable( _gl.DEPTH_TEST );
  21724. _gl.activeTexture( _gl.TEXTURE1 );
  21725. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21726. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21727. // update object positions
  21728. flare.positionScreen.copy( screenPosition )
  21729. if ( flare.customUpdateCallback ) {
  21730. flare.customUpdateCallback( flare );
  21731. } else {
  21732. flare.updateLensFlares();
  21733. }
  21734. // render flares
  21735. _gl.uniform1i( uniforms.renderType, 2 );
  21736. _gl.enable( _gl.BLEND );
  21737. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21738. sprite = flare.lensFlares[ j ];
  21739. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21740. screenPosition.x = sprite.x;
  21741. screenPosition.y = sprite.y;
  21742. screenPosition.z = sprite.z;
  21743. size = sprite.size * sprite.scale / viewportHeight;
  21744. scale.x = size * invAspect;
  21745. scale.y = size;
  21746. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21747. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21748. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21749. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21750. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21751. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21752. _renderer.setTexture( sprite.texture, 1 );
  21753. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21754. }
  21755. }
  21756. }
  21757. }
  21758. // restore gl
  21759. _gl.enable( _gl.CULL_FACE );
  21760. _gl.enable( _gl.DEPTH_TEST );
  21761. _gl.depthMask( true );
  21762. };
  21763. function createProgram ( shader, precision ) {
  21764. var program = _gl.createProgram();
  21765. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21766. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21767. var prefix = "precision " + precision + " float;\n";
  21768. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21769. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21770. _gl.compileShader( fragmentShader );
  21771. _gl.compileShader( vertexShader );
  21772. _gl.attachShader( program, fragmentShader );
  21773. _gl.attachShader( program, vertexShader );
  21774. _gl.linkProgram( program );
  21775. return program;
  21776. };
  21777. };
  21778. /**
  21779. * @author alteredq / http://alteredqualia.com/
  21780. */
  21781. THREE.ShadowMapPlugin = function () {
  21782. var _gl,
  21783. _renderer,
  21784. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21785. _frustum = new THREE.Frustum(),
  21786. _projScreenMatrix = new THREE.Matrix4(),
  21787. _min = new THREE.Vector3(),
  21788. _max = new THREE.Vector3(),
  21789. _matrixPosition = new THREE.Vector3();
  21790. this.init = function ( renderer ) {
  21791. _gl = renderer.context;
  21792. _renderer = renderer;
  21793. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21794. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21795. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21796. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21797. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21798. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21799. _depthMaterial._shadowPass = true;
  21800. _depthMaterialMorph._shadowPass = true;
  21801. _depthMaterialSkin._shadowPass = true;
  21802. _depthMaterialMorphSkin._shadowPass = true;
  21803. };
  21804. this.render = function ( scene, camera ) {
  21805. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21806. this.update( scene, camera );
  21807. };
  21808. this.update = function ( scene, camera ) {
  21809. var i, il, j, jl, n,
  21810. shadowMap, shadowMatrix, shadowCamera,
  21811. program, buffer, material,
  21812. webglObject, object, light,
  21813. renderList,
  21814. lights = [],
  21815. k = 0,
  21816. fog = null;
  21817. // set GL state for depth map
  21818. _gl.clearColor( 1, 1, 1, 1 );
  21819. _gl.disable( _gl.BLEND );
  21820. _gl.enable( _gl.CULL_FACE );
  21821. _gl.frontFace( _gl.CCW );
  21822. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21823. _gl.cullFace( _gl.FRONT );
  21824. } else {
  21825. _gl.cullFace( _gl.BACK );
  21826. }
  21827. _renderer.setDepthTest( true );
  21828. // preprocess lights
  21829. // - skip lights that are not casting shadows
  21830. // - create virtual lights for cascaded shadow maps
  21831. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21832. light = scene.__lights[ i ];
  21833. if ( ! light.castShadow ) continue;
  21834. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21835. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21836. var virtualLight;
  21837. if ( ! light.shadowCascadeArray[ n ] ) {
  21838. virtualLight = createVirtualLight( light, n );
  21839. virtualLight.originalCamera = camera;
  21840. var gyro = new THREE.Gyroscope();
  21841. gyro.position = light.shadowCascadeOffset;
  21842. gyro.add( virtualLight );
  21843. gyro.add( virtualLight.target );
  21844. camera.add( gyro );
  21845. light.shadowCascadeArray[ n ] = virtualLight;
  21846. console.log( "Created virtualLight", virtualLight );
  21847. } else {
  21848. virtualLight = light.shadowCascadeArray[ n ];
  21849. }
  21850. updateVirtualLight( light, n );
  21851. lights[ k ] = virtualLight;
  21852. k ++;
  21853. }
  21854. } else {
  21855. lights[ k ] = light;
  21856. k ++;
  21857. }
  21858. }
  21859. // render depth map
  21860. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21861. light = lights[ i ];
  21862. if ( ! light.shadowMap ) {
  21863. var shadowFilter = THREE.LinearFilter;
  21864. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21865. shadowFilter = THREE.NearestFilter;
  21866. }
  21867. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21868. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21869. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21870. light.shadowMatrix = new THREE.Matrix4();
  21871. }
  21872. if ( ! light.shadowCamera ) {
  21873. if ( light instanceof THREE.SpotLight ) {
  21874. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21875. } else if ( light instanceof THREE.DirectionalLight ) {
  21876. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21877. } else {
  21878. console.error( "Unsupported light type for shadow" );
  21879. continue;
  21880. }
  21881. scene.add( light.shadowCamera );
  21882. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21883. }
  21884. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21885. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21886. light.shadowCamera.add( light.cameraHelper );
  21887. }
  21888. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21889. updateShadowCamera( camera, light );
  21890. }
  21891. shadowMap = light.shadowMap;
  21892. shadowMatrix = light.shadowMatrix;
  21893. shadowCamera = light.shadowCamera;
  21894. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21895. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21896. shadowCamera.lookAt( _matrixPosition );
  21897. shadowCamera.updateMatrixWorld();
  21898. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21899. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21900. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21901. // compute shadow matrix
  21902. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21903. 0.0, 0.5, 0.0, 0.5,
  21904. 0.0, 0.0, 0.5, 0.5,
  21905. 0.0, 0.0, 0.0, 1.0 );
  21906. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21907. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21908. // update camera matrices and frustum
  21909. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21910. _frustum.setFromMatrix( _projScreenMatrix );
  21911. // render shadow map
  21912. _renderer.setRenderTarget( shadowMap );
  21913. _renderer.clear();
  21914. // set object matrices & frustum culling
  21915. renderList = scene.__webglObjects;
  21916. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21917. webglObject = renderList[ j ];
  21918. object = webglObject.object;
  21919. webglObject.render = false;
  21920. if ( object.visible && object.castShadow ) {
  21921. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21922. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21923. webglObject.render = true;
  21924. }
  21925. }
  21926. }
  21927. // render regular objects
  21928. var objectMaterial, useMorphing, useSkinning;
  21929. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21930. webglObject = renderList[ j ];
  21931. if ( webglObject.render ) {
  21932. object = webglObject.object;
  21933. buffer = webglObject.buffer;
  21934. // culling is overriden globally for all objects
  21935. // while rendering depth map
  21936. // need to deal with MeshFaceMaterial somehow
  21937. // in that case just use the first of material.materials for now
  21938. // (proper solution would require to break objects by materials
  21939. // similarly to regular rendering and then set corresponding
  21940. // depth materials per each chunk instead of just once per object)
  21941. objectMaterial = getObjectMaterial( object );
  21942. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21943. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21944. if ( object.customDepthMaterial ) {
  21945. material = object.customDepthMaterial;
  21946. } else if ( useSkinning ) {
  21947. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21948. } else if ( useMorphing ) {
  21949. material = _depthMaterialMorph;
  21950. } else {
  21951. material = _depthMaterial;
  21952. }
  21953. if ( buffer instanceof THREE.BufferGeometry ) {
  21954. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21955. } else {
  21956. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21957. }
  21958. }
  21959. }
  21960. // set matrices and render immediate objects
  21961. renderList = scene.__webglObjectsImmediate;
  21962. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21963. webglObject = renderList[ j ];
  21964. object = webglObject.object;
  21965. if ( object.visible && object.castShadow ) {
  21966. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21967. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21968. }
  21969. }
  21970. }
  21971. // restore GL state
  21972. var clearColor = _renderer.getClearColor(),
  21973. clearAlpha = _renderer.getClearAlpha();
  21974. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21975. _gl.enable( _gl.BLEND );
  21976. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21977. _gl.cullFace( _gl.BACK );
  21978. }
  21979. };
  21980. function createVirtualLight( light, cascade ) {
  21981. var virtualLight = new THREE.DirectionalLight();
  21982. virtualLight.isVirtual = true;
  21983. virtualLight.onlyShadow = true;
  21984. virtualLight.castShadow = true;
  21985. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21986. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21987. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21988. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21989. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21990. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21991. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21992. virtualLight.shadowDarkness = light.shadowDarkness;
  21993. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21994. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21995. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21996. virtualLight.pointsWorld = [];
  21997. virtualLight.pointsFrustum = [];
  21998. var pointsWorld = virtualLight.pointsWorld,
  21999. pointsFrustum = virtualLight.pointsFrustum;
  22000. for ( var i = 0; i < 8; i ++ ) {
  22001. pointsWorld[ i ] = new THREE.Vector3();
  22002. pointsFrustum[ i ] = new THREE.Vector3();
  22003. }
  22004. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22005. var farZ = light.shadowCascadeFarZ[ cascade ];
  22006. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  22007. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  22008. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  22009. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  22010. pointsFrustum[ 4 ].set( -1, -1, farZ );
  22011. pointsFrustum[ 5 ].set( 1, -1, farZ );
  22012. pointsFrustum[ 6 ].set( -1, 1, farZ );
  22013. pointsFrustum[ 7 ].set( 1, 1, farZ );
  22014. return virtualLight;
  22015. }
  22016. // Synchronize virtual light with the original light
  22017. function updateVirtualLight( light, cascade ) {
  22018. var virtualLight = light.shadowCascadeArray[ cascade ];
  22019. virtualLight.position.copy( light.position );
  22020. virtualLight.target.position.copy( light.target.position );
  22021. virtualLight.lookAt( virtualLight.target );
  22022. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22023. virtualLight.shadowDarkness = light.shadowDarkness;
  22024. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22025. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22026. var farZ = light.shadowCascadeFarZ[ cascade ];
  22027. var pointsFrustum = virtualLight.pointsFrustum;
  22028. pointsFrustum[ 0 ].z = nearZ;
  22029. pointsFrustum[ 1 ].z = nearZ;
  22030. pointsFrustum[ 2 ].z = nearZ;
  22031. pointsFrustum[ 3 ].z = nearZ;
  22032. pointsFrustum[ 4 ].z = farZ;
  22033. pointsFrustum[ 5 ].z = farZ;
  22034. pointsFrustum[ 6 ].z = farZ;
  22035. pointsFrustum[ 7 ].z = farZ;
  22036. }
  22037. // Fit shadow camera's ortho frustum to camera frustum
  22038. function updateShadowCamera( camera, light ) {
  22039. var shadowCamera = light.shadowCamera,
  22040. pointsFrustum = light.pointsFrustum,
  22041. pointsWorld = light.pointsWorld;
  22042. _min.set( Infinity, Infinity, Infinity );
  22043. _max.set( -Infinity, -Infinity, -Infinity );
  22044. for ( var i = 0; i < 8; i ++ ) {
  22045. var p = pointsWorld[ i ];
  22046. p.copy( pointsFrustum[ i ] );
  22047. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  22048. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  22049. if ( p.x < _min.x ) _min.x = p.x;
  22050. if ( p.x > _max.x ) _max.x = p.x;
  22051. if ( p.y < _min.y ) _min.y = p.y;
  22052. if ( p.y > _max.y ) _max.y = p.y;
  22053. if ( p.z < _min.z ) _min.z = p.z;
  22054. if ( p.z > _max.z ) _max.z = p.z;
  22055. }
  22056. shadowCamera.left = _min.x;
  22057. shadowCamera.right = _max.x;
  22058. shadowCamera.top = _max.y;
  22059. shadowCamera.bottom = _min.y;
  22060. // can't really fit near/far
  22061. //shadowCamera.near = _min.z;
  22062. //shadowCamera.far = _max.z;
  22063. shadowCamera.updateProjectionMatrix();
  22064. }
  22065. // For the moment just ignore objects that have multiple materials with different animation methods
  22066. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  22067. function getObjectMaterial( object ) {
  22068. return object.material instanceof THREE.MeshFaceMaterial
  22069. ? object.material.materials[ 0 ]
  22070. : object.material;
  22071. };
  22072. };
  22073. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  22074. /**
  22075. * @author mikael emtinger / http://gomo.se/
  22076. * @author alteredq / http://alteredqualia.com/
  22077. */
  22078. THREE.SpritePlugin = function () {
  22079. var _gl, _renderer, _texture;
  22080. var vertices, faces, vertexBuffer, elementBuffer;
  22081. var program, attributes, uniforms;
  22082. this.init = function ( renderer ) {
  22083. _gl = renderer.context;
  22084. _renderer = renderer;
  22085. vertices = new Float32Array( [
  22086. - 0.5, - 0.5, 0, 0,
  22087. 0.5, - 0.5, 1, 0,
  22088. 0.5, 0.5, 1, 1,
  22089. - 0.5, 0.5, 0, 1
  22090. ] );
  22091. faces = new Uint16Array( [
  22092. 0, 1, 2,
  22093. 0, 2, 3
  22094. ] );
  22095. vertexBuffer = _gl.createBuffer();
  22096. elementBuffer = _gl.createBuffer();
  22097. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22098. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  22099. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22100. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  22101. program = createProgram();
  22102. attributes = {
  22103. position: _gl.getAttribLocation ( program, 'position' ),
  22104. uv: _gl.getAttribLocation ( program, 'uv' )
  22105. };
  22106. uniforms = {
  22107. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  22108. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  22109. rotation: _gl.getUniformLocation( program, 'rotation' ),
  22110. scale: _gl.getUniformLocation( program, 'scale' ),
  22111. color: _gl.getUniformLocation( program, 'color' ),
  22112. map: _gl.getUniformLocation( program, 'map' ),
  22113. opacity: _gl.getUniformLocation( program, 'opacity' ),
  22114. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  22115. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  22116. fogType: _gl.getUniformLocation( program, 'fogType' ),
  22117. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  22118. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  22119. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  22120. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  22121. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  22122. };
  22123. var canvas = document.createElement( 'canvas' );
  22124. canvas.width = 8;
  22125. canvas.height = 8;
  22126. var context = canvas.getContext( '2d' );
  22127. context.fillStyle = '#ffffff';
  22128. context.fillRect( 0, 0, canvas.width, canvas.height );
  22129. _texture = new THREE.Texture( canvas );
  22130. _texture.needsUpdate = true;
  22131. };
  22132. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22133. var sprites = scene.__webglSprites,
  22134. nSprites = sprites.length;
  22135. if ( ! nSprites ) return;
  22136. // setup gl
  22137. _gl.useProgram( program );
  22138. _gl.enableVertexAttribArray( attributes.position );
  22139. _gl.enableVertexAttribArray( attributes.uv );
  22140. _gl.disable( _gl.CULL_FACE );
  22141. _gl.enable( _gl.BLEND );
  22142. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22143. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22144. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22145. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22146. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22147. _gl.activeTexture( _gl.TEXTURE0 );
  22148. _gl.uniform1i( uniforms.map, 0 );
  22149. var oldFogType = 0;
  22150. var sceneFogType = 0;
  22151. var fog = scene.fog;
  22152. if ( fog ) {
  22153. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22154. if ( fog instanceof THREE.Fog ) {
  22155. _gl.uniform1f( uniforms.fogNear, fog.near );
  22156. _gl.uniform1f( uniforms.fogFar, fog.far );
  22157. _gl.uniform1i( uniforms.fogType, 1 );
  22158. oldFogType = 1;
  22159. sceneFogType = 1;
  22160. } else if ( fog instanceof THREE.FogExp2 ) {
  22161. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22162. _gl.uniform1i( uniforms.fogType, 2 );
  22163. oldFogType = 2;
  22164. sceneFogType = 2;
  22165. }
  22166. } else {
  22167. _gl.uniform1i( uniforms.fogType, 0 );
  22168. oldFogType = 0;
  22169. sceneFogType = 0;
  22170. }
  22171. // update positions and sort
  22172. var i, sprite, material, fogType, scale = [];
  22173. for( i = 0; i < nSprites; i ++ ) {
  22174. sprite = sprites[ i ];
  22175. material = sprite.material;
  22176. if ( sprite.visible === false ) continue;
  22177. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22178. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22179. }
  22180. sprites.sort( painterSortStable );
  22181. // render all sprites
  22182. for( i = 0; i < nSprites; i ++ ) {
  22183. sprite = sprites[ i ];
  22184. if ( sprite.visible === false ) continue;
  22185. material = sprite.material;
  22186. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22187. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22188. scale[ 0 ] = sprite.scale.x;
  22189. scale[ 1 ] = sprite.scale.y;
  22190. if ( scene.fog && material.fog ) {
  22191. fogType = sceneFogType;
  22192. } else {
  22193. fogType = 0;
  22194. }
  22195. if ( oldFogType !== fogType ) {
  22196. _gl.uniform1i( uniforms.fogType, fogType );
  22197. oldFogType = fogType;
  22198. }
  22199. if ( material.map !== null ) {
  22200. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  22201. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  22202. } else {
  22203. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  22204. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  22205. }
  22206. _gl.uniform1f( uniforms.opacity, material.opacity );
  22207. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22208. _gl.uniform1f( uniforms.rotation, material.rotation );
  22209. _gl.uniform2fv( uniforms.scale, scale );
  22210. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22211. _renderer.setDepthTest( material.depthTest );
  22212. _renderer.setDepthWrite( material.depthWrite );
  22213. if ( material.map && material.map.image && material.map.image.width ) {
  22214. _renderer.setTexture( material.map, 0 );
  22215. } else {
  22216. _renderer.setTexture( _texture, 0 );
  22217. }
  22218. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22219. }
  22220. // restore gl
  22221. _gl.enable( _gl.CULL_FACE );
  22222. };
  22223. function createProgram () {
  22224. var program = _gl.createProgram();
  22225. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22226. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22227. _gl.shaderSource( vertexShader, [
  22228. 'precision ' + _renderer.getPrecision() + ' float;',
  22229. 'uniform mat4 modelViewMatrix;',
  22230. 'uniform mat4 projectionMatrix;',
  22231. 'uniform float rotation;',
  22232. 'uniform vec2 scale;',
  22233. 'uniform vec2 uvOffset;',
  22234. 'uniform vec2 uvScale;',
  22235. 'attribute vec2 position;',
  22236. 'attribute vec2 uv;',
  22237. 'varying vec2 vUV;',
  22238. 'void main() {',
  22239. 'vUV = uvOffset + uv * uvScale;',
  22240. 'vec2 alignedPosition = position * scale;',
  22241. 'vec2 rotatedPosition;',
  22242. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  22243. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  22244. 'vec4 finalPosition;',
  22245. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  22246. 'finalPosition.xy += rotatedPosition;',
  22247. 'finalPosition = projectionMatrix * finalPosition;',
  22248. 'gl_Position = finalPosition;',
  22249. '}'
  22250. ].join( '\n' ) );
  22251. _gl.shaderSource( fragmentShader, [
  22252. 'precision ' + _renderer.getPrecision() + ' float;',
  22253. 'uniform vec3 color;',
  22254. 'uniform sampler2D map;',
  22255. 'uniform float opacity;',
  22256. 'uniform int fogType;',
  22257. 'uniform vec3 fogColor;',
  22258. 'uniform float fogDensity;',
  22259. 'uniform float fogNear;',
  22260. 'uniform float fogFar;',
  22261. 'uniform float alphaTest;',
  22262. 'varying vec2 vUV;',
  22263. 'void main() {',
  22264. 'vec4 texture = texture2D( map, vUV );',
  22265. 'if ( texture.a < alphaTest ) discard;',
  22266. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  22267. 'if ( fogType > 0 ) {',
  22268. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  22269. 'float fogFactor = 0.0;',
  22270. 'if ( fogType == 1 ) {',
  22271. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  22272. '} else {',
  22273. 'const float LOG2 = 1.442695;',
  22274. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  22275. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  22276. '}',
  22277. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  22278. '}',
  22279. '}'
  22280. ].join( '\n' ) );
  22281. _gl.compileShader( vertexShader );
  22282. _gl.compileShader( fragmentShader );
  22283. _gl.attachShader( program, vertexShader );
  22284. _gl.attachShader( program, fragmentShader );
  22285. _gl.linkProgram( program );
  22286. return program;
  22287. };
  22288. function painterSortStable ( a, b ) {
  22289. if ( a.z !== b.z ) {
  22290. return b.z - a.z;
  22291. } else {
  22292. return b.id - a.id;
  22293. }
  22294. };
  22295. };
  22296. /**
  22297. * @author alteredq / http://alteredqualia.com/
  22298. */
  22299. THREE.DepthPassPlugin = function () {
  22300. this.enabled = false;
  22301. this.renderTarget = null;
  22302. var _gl,
  22303. _renderer,
  22304. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22305. _frustum = new THREE.Frustum(),
  22306. _projScreenMatrix = new THREE.Matrix4();
  22307. this.init = function ( renderer ) {
  22308. _gl = renderer.context;
  22309. _renderer = renderer;
  22310. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22311. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22312. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22313. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22314. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22315. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22316. _depthMaterial._shadowPass = true;
  22317. _depthMaterialMorph._shadowPass = true;
  22318. _depthMaterialSkin._shadowPass = true;
  22319. _depthMaterialMorphSkin._shadowPass = true;
  22320. };
  22321. this.render = function ( scene, camera ) {
  22322. if ( ! this.enabled ) return;
  22323. this.update( scene, camera );
  22324. };
  22325. this.update = function ( scene, camera ) {
  22326. var i, il, j, jl, n,
  22327. program, buffer, material,
  22328. webglObject, object, light,
  22329. renderList,
  22330. fog = null;
  22331. // set GL state for depth map
  22332. _gl.clearColor( 1, 1, 1, 1 );
  22333. _gl.disable( _gl.BLEND );
  22334. _renderer.setDepthTest( true );
  22335. // update scene
  22336. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22337. // update camera matrices and frustum
  22338. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22339. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22340. _frustum.setFromMatrix( _projScreenMatrix );
  22341. // render depth map
  22342. _renderer.setRenderTarget( this.renderTarget );
  22343. _renderer.clear();
  22344. // set object matrices & frustum culling
  22345. renderList = scene.__webglObjects;
  22346. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22347. webglObject = renderList[ j ];
  22348. object = webglObject.object;
  22349. webglObject.render = false;
  22350. if ( object.visible ) {
  22351. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22352. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22353. webglObject.render = true;
  22354. }
  22355. }
  22356. }
  22357. // render regular objects
  22358. var objectMaterial, useMorphing, useSkinning;
  22359. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22360. webglObject = renderList[ j ];
  22361. if ( webglObject.render ) {
  22362. object = webglObject.object;
  22363. buffer = webglObject.buffer;
  22364. // todo: create proper depth material for particles
  22365. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22366. objectMaterial = getObjectMaterial( object );
  22367. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22368. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22369. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22370. if ( object.customDepthMaterial ) {
  22371. material = object.customDepthMaterial;
  22372. } else if ( useSkinning ) {
  22373. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22374. } else if ( useMorphing ) {
  22375. material = _depthMaterialMorph;
  22376. } else {
  22377. material = _depthMaterial;
  22378. }
  22379. if ( buffer instanceof THREE.BufferGeometry ) {
  22380. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22381. } else {
  22382. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22383. }
  22384. }
  22385. }
  22386. // set matrices and render immediate objects
  22387. renderList = scene.__webglObjectsImmediate;
  22388. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22389. webglObject = renderList[ j ];
  22390. object = webglObject.object;
  22391. if ( object.visible ) {
  22392. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22393. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22394. }
  22395. }
  22396. // restore GL state
  22397. var clearColor = _renderer.getClearColor(),
  22398. clearAlpha = _renderer.getClearAlpha();
  22399. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22400. _gl.enable( _gl.BLEND );
  22401. };
  22402. // For the moment just ignore objects that have multiple materials with different animation methods
  22403. // Only the first material will be taken into account for deciding which depth material to use
  22404. function getObjectMaterial( object ) {
  22405. return object.material instanceof THREE.MeshFaceMaterial
  22406. ? object.material.materials[ 0 ]
  22407. : object.material;
  22408. };
  22409. };
  22410. /**
  22411. * @author mikael emtinger / http://gomo.se/
  22412. */
  22413. THREE.ShaderFlares = {
  22414. 'lensFlareVertexTexture': {
  22415. vertexShader: [
  22416. "uniform lowp int renderType;",
  22417. "uniform vec3 screenPosition;",
  22418. "uniform vec2 scale;",
  22419. "uniform float rotation;",
  22420. "uniform sampler2D occlusionMap;",
  22421. "attribute vec2 position;",
  22422. "attribute vec2 uv;",
  22423. "varying vec2 vUV;",
  22424. "varying float vVisibility;",
  22425. "void main() {",
  22426. "vUV = uv;",
  22427. "vec2 pos = position;",
  22428. "if( renderType == 2 ) {",
  22429. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22430. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22431. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22432. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22433. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22434. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22435. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22436. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22437. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22438. "vVisibility = visibility.r / 9.0;",
  22439. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22440. "vVisibility *= visibility.b / 9.0;",
  22441. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22442. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22443. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22444. "}",
  22445. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22446. "}"
  22447. ].join( "\n" ),
  22448. fragmentShader: [
  22449. "uniform lowp int renderType;",
  22450. "uniform sampler2D map;",
  22451. "uniform float opacity;",
  22452. "uniform vec3 color;",
  22453. "varying vec2 vUV;",
  22454. "varying float vVisibility;",
  22455. "void main() {",
  22456. // pink square
  22457. "if( renderType == 0 ) {",
  22458. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22459. // restore
  22460. "} else if( renderType == 1 ) {",
  22461. "gl_FragColor = texture2D( map, vUV );",
  22462. // flare
  22463. "} else {",
  22464. "vec4 texture = texture2D( map, vUV );",
  22465. "texture.a *= opacity * vVisibility;",
  22466. "gl_FragColor = texture;",
  22467. "gl_FragColor.rgb *= color;",
  22468. "}",
  22469. "}"
  22470. ].join( "\n" )
  22471. },
  22472. 'lensFlare': {
  22473. vertexShader: [
  22474. "uniform lowp int renderType;",
  22475. "uniform vec3 screenPosition;",
  22476. "uniform vec2 scale;",
  22477. "uniform float rotation;",
  22478. "attribute vec2 position;",
  22479. "attribute vec2 uv;",
  22480. "varying vec2 vUV;",
  22481. "void main() {",
  22482. "vUV = uv;",
  22483. "vec2 pos = position;",
  22484. "if( renderType == 2 ) {",
  22485. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22486. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22487. "}",
  22488. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22489. "}"
  22490. ].join( "\n" ),
  22491. fragmentShader: [
  22492. "precision mediump float;",
  22493. "uniform lowp int renderType;",
  22494. "uniform sampler2D map;",
  22495. "uniform sampler2D occlusionMap;",
  22496. "uniform float opacity;",
  22497. "uniform vec3 color;",
  22498. "varying vec2 vUV;",
  22499. "void main() {",
  22500. // pink square
  22501. "if( renderType == 0 ) {",
  22502. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22503. // restore
  22504. "} else if( renderType == 1 ) {",
  22505. "gl_FragColor = texture2D( map, vUV );",
  22506. // flare
  22507. "} else {",
  22508. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22509. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22510. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22511. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22512. "visibility = ( 1.0 - visibility / 4.0 );",
  22513. "vec4 texture = texture2D( map, vUV );",
  22514. "texture.a *= opacity * visibility;",
  22515. "gl_FragColor = texture;",
  22516. "gl_FragColor.rgb *= color;",
  22517. "}",
  22518. "}"
  22519. ].join( "\n" )
  22520. }
  22521. };
粤ICP备19079148号