three.js 825 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121
  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. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  499. // assumes axis is 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. setFromUnitVectors: function () {
  546. // http://lolengine.net/blog/2013/09/18/beautiful-maths-quaternion-from-vectors
  547. // assumes direction vectors vFrom and vTo are normalized
  548. var v1;
  549. return function( vFrom, vTo ) {
  550. if ( v1 === undefined ) v1 = new THREE.Vector3();
  551. v1.crossVectors( vFrom, vTo );
  552. this.set( v1.x, v1.y, v1.z, vFrom.dot( vTo ) + 1 ).normalize();
  553. this._updateEuler();
  554. return this;
  555. }
  556. }(),
  557. inverse: function () {
  558. this.conjugate().normalize();
  559. return this;
  560. },
  561. conjugate: function () {
  562. this._x *= -1;
  563. this._y *= -1;
  564. this._z *= -1;
  565. this._updateEuler();
  566. return this;
  567. },
  568. lengthSq: function () {
  569. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  570. },
  571. length: function () {
  572. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  573. },
  574. normalize: function () {
  575. var l = this.length();
  576. if ( l === 0 ) {
  577. this._x = 0;
  578. this._y = 0;
  579. this._z = 0;
  580. this._w = 1;
  581. } else {
  582. l = 1 / l;
  583. this._x = this._x * l;
  584. this._y = this._y * l;
  585. this._z = this._z * l;
  586. this._w = this._w * l;
  587. }
  588. return this;
  589. },
  590. multiply: function ( q, p ) {
  591. if ( p !== undefined ) {
  592. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  593. return this.multiplyQuaternions( q, p );
  594. }
  595. return this.multiplyQuaternions( this, q );
  596. },
  597. multiplyQuaternions: function ( a, b ) {
  598. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  599. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  600. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  601. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  602. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  603. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  604. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  605. this._updateEuler();
  606. return this;
  607. },
  608. multiplyVector3: function ( vector ) {
  609. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  610. return vector.applyQuaternion( this );
  611. },
  612. slerp: function ( qb, t ) {
  613. var x = this._x, y = this._y, z = this._z, w = this._w;
  614. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  615. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  616. if ( cosHalfTheta < 0 ) {
  617. this._w = -qb._w;
  618. this._x = -qb._x;
  619. this._y = -qb._y;
  620. this._z = -qb._z;
  621. cosHalfTheta = -cosHalfTheta;
  622. } else {
  623. this.copy( qb );
  624. }
  625. if ( cosHalfTheta >= 1.0 ) {
  626. this._w = w;
  627. this._x = x;
  628. this._y = y;
  629. this._z = z;
  630. return this;
  631. }
  632. var halfTheta = Math.acos( cosHalfTheta );
  633. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  634. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  635. this._w = 0.5 * ( w + this._w );
  636. this._x = 0.5 * ( x + this._x );
  637. this._y = 0.5 * ( y + this._y );
  638. this._z = 0.5 * ( z + this._z );
  639. return this;
  640. }
  641. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  642. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  643. this._w = ( w * ratioA + this._w * ratioB );
  644. this._x = ( x * ratioA + this._x * ratioB );
  645. this._y = ( y * ratioA + this._y * ratioB );
  646. this._z = ( z * ratioA + this._z * ratioB );
  647. this._updateEuler();
  648. return this;
  649. },
  650. equals: function ( quaternion ) {
  651. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  652. },
  653. fromArray: function ( array ) {
  654. this._x = array[ 0 ];
  655. this._y = array[ 1 ];
  656. this._z = array[ 2 ];
  657. this._w = array[ 3 ];
  658. this._updateEuler();
  659. return this;
  660. },
  661. toArray: function () {
  662. return [ this._x, this._y, this._z, this._w ];
  663. },
  664. clone: function () {
  665. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  666. }
  667. };
  668. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  669. return qm.copy( qa ).slerp( qb, t );
  670. }
  671. /**
  672. * @author mrdoob / http://mrdoob.com/
  673. * @author philogb / http://blog.thejit.org/
  674. * @author egraether / http://egraether.com/
  675. * @author zz85 / http://www.lab4games.net/zz85/blog
  676. */
  677. THREE.Vector2 = function ( x, y ) {
  678. this.x = x || 0;
  679. this.y = y || 0;
  680. };
  681. THREE.Vector2.prototype = {
  682. constructor: THREE.Vector2,
  683. set: function ( x, y ) {
  684. this.x = x;
  685. this.y = y;
  686. return this;
  687. },
  688. setX: function ( x ) {
  689. this.x = x;
  690. return this;
  691. },
  692. setY: function ( y ) {
  693. this.y = y;
  694. return this;
  695. },
  696. setComponent: function ( index, value ) {
  697. switch ( index ) {
  698. case 0: this.x = value; break;
  699. case 1: this.y = value; break;
  700. default: throw new Error( "index is out of range: " + index );
  701. }
  702. },
  703. getComponent: function ( index ) {
  704. switch ( index ) {
  705. case 0: return this.x;
  706. case 1: return this.y;
  707. default: throw new Error( "index is out of range: " + index );
  708. }
  709. },
  710. copy: function ( v ) {
  711. this.x = v.x;
  712. this.y = v.y;
  713. return this;
  714. },
  715. add: function ( v, w ) {
  716. if ( w !== undefined ) {
  717. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  718. return this.addVectors( v, w );
  719. }
  720. this.x += v.x;
  721. this.y += v.y;
  722. return this;
  723. },
  724. addVectors: function ( a, b ) {
  725. this.x = a.x + b.x;
  726. this.y = a.y + b.y;
  727. return this;
  728. },
  729. addScalar: function ( s ) {
  730. this.x += s;
  731. this.y += s;
  732. return this;
  733. },
  734. sub: function ( v, w ) {
  735. if ( w !== undefined ) {
  736. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  737. return this.subVectors( v, w );
  738. }
  739. this.x -= v.x;
  740. this.y -= v.y;
  741. return this;
  742. },
  743. subVectors: function ( a, b ) {
  744. this.x = a.x - b.x;
  745. this.y = a.y - b.y;
  746. return this;
  747. },
  748. multiply: function ( v ) {
  749. this.x *= v.x;
  750. this.y *= v.y;
  751. return this;
  752. },
  753. multiplyScalar: function ( s ) {
  754. this.x *= s;
  755. this.y *= s;
  756. return this;
  757. },
  758. divide: function ( v ) {
  759. this.x /= v.x;
  760. this.y /= v.y;
  761. return this;
  762. },
  763. divideScalar: function ( scalar ) {
  764. if ( scalar !== 0 ) {
  765. var invScalar = 1 / scalar;
  766. this.x *= invScalar;
  767. this.y *= invScalar;
  768. } else {
  769. this.x = 0;
  770. this.y = 0;
  771. }
  772. return this;
  773. },
  774. min: function ( v ) {
  775. if ( this.x > v.x ) {
  776. this.x = v.x;
  777. }
  778. if ( this.y > v.y ) {
  779. this.y = v.y;
  780. }
  781. return this;
  782. },
  783. max: function ( v ) {
  784. if ( this.x < v.x ) {
  785. this.x = v.x;
  786. }
  787. if ( this.y < v.y ) {
  788. this.y = v.y;
  789. }
  790. return this;
  791. },
  792. clamp: function ( min, max ) {
  793. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  794. if ( this.x < min.x ) {
  795. this.x = min.x;
  796. } else if ( this.x > max.x ) {
  797. this.x = max.x;
  798. }
  799. if ( this.y < min.y ) {
  800. this.y = min.y;
  801. } else if ( this.y > max.y ) {
  802. this.y = max.y;
  803. }
  804. return this;
  805. },
  806. clampScalar: ( function () {
  807. var min, max;
  808. return function ( minVal, maxVal ) {
  809. if ( min === undefined ) {
  810. min = new THREE.Vector2();
  811. max = new THREE.Vector2();
  812. }
  813. min.set( minVal, minVal );
  814. max.set( maxVal, maxVal );
  815. return this.clamp( min, max );
  816. };
  817. } )(),
  818. floor: function () {
  819. this.x = Math.floor( this.x );
  820. this.y = Math.floor( this.y );
  821. return this;
  822. },
  823. ceil: function () {
  824. this.x = Math.ceil( this.x );
  825. this.y = Math.ceil( this.y );
  826. return this;
  827. },
  828. round: function () {
  829. this.x = Math.round( this.x );
  830. this.y = Math.round( this.y );
  831. return this;
  832. },
  833. roundToZero: function () {
  834. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  835. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  836. return this;
  837. },
  838. negate: function () {
  839. return this.multiplyScalar( - 1 );
  840. },
  841. dot: function ( v ) {
  842. return this.x * v.x + this.y * v.y;
  843. },
  844. lengthSq: function () {
  845. return this.x * this.x + this.y * this.y;
  846. },
  847. length: function () {
  848. return Math.sqrt( this.x * this.x + this.y * this.y );
  849. },
  850. normalize: function () {
  851. return this.divideScalar( this.length() );
  852. },
  853. distanceTo: function ( v ) {
  854. return Math.sqrt( this.distanceToSquared( v ) );
  855. },
  856. distanceToSquared: function ( v ) {
  857. var dx = this.x - v.x, dy = this.y - v.y;
  858. return dx * dx + dy * dy;
  859. },
  860. setLength: function ( l ) {
  861. var oldLength = this.length();
  862. if ( oldLength !== 0 && l !== oldLength ) {
  863. this.multiplyScalar( l / oldLength );
  864. }
  865. return this;
  866. },
  867. lerp: function ( v, alpha ) {
  868. this.x += ( v.x - this.x ) * alpha;
  869. this.y += ( v.y - this.y ) * alpha;
  870. return this;
  871. },
  872. equals: function( v ) {
  873. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  874. },
  875. fromArray: function ( array ) {
  876. this.x = array[ 0 ];
  877. this.y = array[ 1 ];
  878. return this;
  879. },
  880. toArray: function () {
  881. return [ this.x, this.y ];
  882. },
  883. clone: function () {
  884. return new THREE.Vector2( this.x, this.y );
  885. }
  886. };
  887. /**
  888. * @author mrdoob / http://mrdoob.com/
  889. * @author *kile / http://kile.stravaganza.org/
  890. * @author philogb / http://blog.thejit.org/
  891. * @author mikael emtinger / http://gomo.se/
  892. * @author egraether / http://egraether.com/
  893. * @author WestLangley / http://github.com/WestLangley
  894. */
  895. THREE.Vector3 = function ( x, y, z ) {
  896. this.x = x || 0;
  897. this.y = y || 0;
  898. this.z = z || 0;
  899. };
  900. THREE.Vector3.prototype = {
  901. constructor: THREE.Vector3,
  902. set: function ( x, y, z ) {
  903. this.x = x;
  904. this.y = y;
  905. this.z = z;
  906. return this;
  907. },
  908. setX: function ( x ) {
  909. this.x = x;
  910. return this;
  911. },
  912. setY: function ( y ) {
  913. this.y = y;
  914. return this;
  915. },
  916. setZ: function ( z ) {
  917. this.z = z;
  918. return this;
  919. },
  920. setComponent: function ( index, value ) {
  921. switch ( index ) {
  922. case 0: this.x = value; break;
  923. case 1: this.y = value; break;
  924. case 2: this.z = value; break;
  925. default: throw new Error( "index is out of range: " + index );
  926. }
  927. },
  928. getComponent: function ( index ) {
  929. switch ( index ) {
  930. case 0: return this.x;
  931. case 1: return this.y;
  932. case 2: return this.z;
  933. default: throw new Error( "index is out of range: " + index );
  934. }
  935. },
  936. copy: function ( v ) {
  937. this.x = v.x;
  938. this.y = v.y;
  939. this.z = v.z;
  940. return this;
  941. },
  942. add: function ( v, w ) {
  943. if ( w !== undefined ) {
  944. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  945. return this.addVectors( v, w );
  946. }
  947. this.x += v.x;
  948. this.y += v.y;
  949. this.z += v.z;
  950. return this;
  951. },
  952. addScalar: function ( s ) {
  953. this.x += s;
  954. this.y += s;
  955. this.z += s;
  956. return this;
  957. },
  958. addVectors: function ( a, b ) {
  959. this.x = a.x + b.x;
  960. this.y = a.y + b.y;
  961. this.z = a.z + b.z;
  962. return this;
  963. },
  964. sub: function ( v, w ) {
  965. if ( w !== undefined ) {
  966. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  967. return this.subVectors( v, w );
  968. }
  969. this.x -= v.x;
  970. this.y -= v.y;
  971. this.z -= v.z;
  972. return this;
  973. },
  974. subVectors: 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. multiply: function ( v, w ) {
  981. if ( w !== undefined ) {
  982. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  983. return this.multiplyVectors( v, w );
  984. }
  985. this.x *= v.x;
  986. this.y *= v.y;
  987. this.z *= v.z;
  988. return this;
  989. },
  990. multiplyScalar: function ( scalar ) {
  991. this.x *= scalar;
  992. this.y *= scalar;
  993. this.z *= scalar;
  994. return this;
  995. },
  996. multiplyVectors: function ( a, b ) {
  997. this.x = a.x * b.x;
  998. this.y = a.y * b.y;
  999. this.z = a.z * b.z;
  1000. return this;
  1001. },
  1002. applyEuler: function () {
  1003. var quaternion;
  1004. return function ( euler ) {
  1005. if ( euler instanceof THREE.Euler === false ) {
  1006. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1007. }
  1008. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1009. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1010. return this;
  1011. };
  1012. }(),
  1013. applyAxisAngle: function () {
  1014. var quaternion;
  1015. return function ( axis, angle ) {
  1016. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1017. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1018. return this;
  1019. };
  1020. }(),
  1021. applyMatrix3: function ( m ) {
  1022. var x = this.x;
  1023. var y = this.y;
  1024. var z = this.z;
  1025. var e = m.elements;
  1026. this.x = e[0] * x + e[3] * y + e[6] * z;
  1027. this.y = e[1] * x + e[4] * y + e[7] * z;
  1028. this.z = e[2] * x + e[5] * y + e[8] * z;
  1029. return this;
  1030. },
  1031. applyMatrix4: function ( m ) {
  1032. // input: THREE.Matrix4 affine matrix
  1033. var x = this.x, y = this.y, z = this.z;
  1034. var e = m.elements;
  1035. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  1036. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  1037. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  1038. return this;
  1039. },
  1040. applyProjection: function ( m ) {
  1041. // input: THREE.Matrix4 projection matrix
  1042. var x = this.x, y = this.y, z = this.z;
  1043. var e = m.elements;
  1044. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  1045. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  1046. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  1047. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  1048. return this;
  1049. },
  1050. applyQuaternion: function ( q ) {
  1051. var x = this.x;
  1052. var y = this.y;
  1053. var z = this.z;
  1054. var qx = q.x;
  1055. var qy = q.y;
  1056. var qz = q.z;
  1057. var qw = q.w;
  1058. // calculate quat * vector
  1059. var ix = qw * x + qy * z - qz * y;
  1060. var iy = qw * y + qz * x - qx * z;
  1061. var iz = qw * z + qx * y - qy * x;
  1062. var iw = -qx * x - qy * y - qz * z;
  1063. // calculate result * inverse quat
  1064. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1065. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1066. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1067. return this;
  1068. },
  1069. transformDirection: function ( m ) {
  1070. // input: THREE.Matrix4 affine matrix
  1071. // vector interpreted as a direction
  1072. var x = this.x, y = this.y, z = this.z;
  1073. var e = m.elements;
  1074. this.x = e[0] * x + e[4] * y + e[8] * z;
  1075. this.y = e[1] * x + e[5] * y + e[9] * z;
  1076. this.z = e[2] * x + e[6] * y + e[10] * z;
  1077. this.normalize();
  1078. return this;
  1079. },
  1080. divide: function ( v ) {
  1081. this.x /= v.x;
  1082. this.y /= v.y;
  1083. this.z /= v.z;
  1084. return this;
  1085. },
  1086. divideScalar: function ( scalar ) {
  1087. if ( scalar !== 0 ) {
  1088. var invScalar = 1 / scalar;
  1089. this.x *= invScalar;
  1090. this.y *= invScalar;
  1091. this.z *= invScalar;
  1092. } else {
  1093. this.x = 0;
  1094. this.y = 0;
  1095. this.z = 0;
  1096. }
  1097. return this;
  1098. },
  1099. min: function ( v ) {
  1100. if ( this.x > v.x ) {
  1101. this.x = v.x;
  1102. }
  1103. if ( this.y > v.y ) {
  1104. this.y = v.y;
  1105. }
  1106. if ( this.z > v.z ) {
  1107. this.z = v.z;
  1108. }
  1109. return this;
  1110. },
  1111. max: function ( v ) {
  1112. if ( this.x < v.x ) {
  1113. this.x = v.x;
  1114. }
  1115. if ( this.y < v.y ) {
  1116. this.y = v.y;
  1117. }
  1118. if ( this.z < v.z ) {
  1119. this.z = v.z;
  1120. }
  1121. return this;
  1122. },
  1123. clamp: function ( min, max ) {
  1124. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1125. if ( this.x < min.x ) {
  1126. this.x = min.x;
  1127. } else if ( this.x > max.x ) {
  1128. this.x = max.x;
  1129. }
  1130. if ( this.y < min.y ) {
  1131. this.y = min.y;
  1132. } else if ( this.y > max.y ) {
  1133. this.y = max.y;
  1134. }
  1135. if ( this.z < min.z ) {
  1136. this.z = min.z;
  1137. } else if ( this.z > max.z ) {
  1138. this.z = max.z;
  1139. }
  1140. return this;
  1141. },
  1142. clampScalar: ( function () {
  1143. var min, max;
  1144. return function ( minVal, maxVal ) {
  1145. if ( min === undefined ) {
  1146. min = new THREE.Vector3();
  1147. max = new THREE.Vector3();
  1148. }
  1149. min.set( minVal, minVal, minVal );
  1150. max.set( maxVal, maxVal, maxVal );
  1151. return this.clamp( min, max );
  1152. };
  1153. } )(),
  1154. floor: function () {
  1155. this.x = Math.floor( this.x );
  1156. this.y = Math.floor( this.y );
  1157. this.z = Math.floor( this.z );
  1158. return this;
  1159. },
  1160. ceil: function () {
  1161. this.x = Math.ceil( this.x );
  1162. this.y = Math.ceil( this.y );
  1163. this.z = Math.ceil( this.z );
  1164. return this;
  1165. },
  1166. round: function () {
  1167. this.x = Math.round( this.x );
  1168. this.y = Math.round( this.y );
  1169. this.z = Math.round( this.z );
  1170. return this;
  1171. },
  1172. roundToZero: function () {
  1173. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1174. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1175. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1176. return this;
  1177. },
  1178. negate: function () {
  1179. return this.multiplyScalar( - 1 );
  1180. },
  1181. dot: function ( v ) {
  1182. return this.x * v.x + this.y * v.y + this.z * v.z;
  1183. },
  1184. lengthSq: function () {
  1185. return this.x * this.x + this.y * this.y + this.z * this.z;
  1186. },
  1187. length: function () {
  1188. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1189. },
  1190. lengthManhattan: function () {
  1191. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1192. },
  1193. normalize: function () {
  1194. return this.divideScalar( this.length() );
  1195. },
  1196. setLength: function ( l ) {
  1197. var oldLength = this.length();
  1198. if ( oldLength !== 0 && l !== oldLength ) {
  1199. this.multiplyScalar( l / oldLength );
  1200. }
  1201. return this;
  1202. },
  1203. lerp: function ( v, alpha ) {
  1204. this.x += ( v.x - this.x ) * alpha;
  1205. this.y += ( v.y - this.y ) * alpha;
  1206. this.z += ( v.z - this.z ) * alpha;
  1207. return this;
  1208. },
  1209. cross: function ( v, w ) {
  1210. if ( w !== undefined ) {
  1211. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1212. return this.crossVectors( v, w );
  1213. }
  1214. var x = this.x, y = this.y, z = this.z;
  1215. this.x = y * v.z - z * v.y;
  1216. this.y = z * v.x - x * v.z;
  1217. this.z = x * v.y - y * v.x;
  1218. return this;
  1219. },
  1220. crossVectors: function ( a, b ) {
  1221. var ax = a.x, ay = a.y, az = a.z;
  1222. var bx = b.x, by = b.y, bz = b.z;
  1223. this.x = ay * bz - az * by;
  1224. this.y = az * bx - ax * bz;
  1225. this.z = ax * by - ay * bx;
  1226. return this;
  1227. },
  1228. projectOnVector: function () {
  1229. var v1, dot;
  1230. return function ( vector ) {
  1231. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1232. v1.copy( vector ).normalize();
  1233. dot = this.dot( v1 );
  1234. return this.copy( v1 ).multiplyScalar( dot );
  1235. };
  1236. }(),
  1237. projectOnPlane: function () {
  1238. var v1;
  1239. return function ( planeNormal ) {
  1240. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1241. v1.copy( this ).projectOnVector( planeNormal );
  1242. return this.sub( v1 );
  1243. }
  1244. }(),
  1245. reflect: function () {
  1246. // reflect incident vector off plane orthogonal to normal
  1247. // normal is assumed to have unit length
  1248. var v1;
  1249. return function ( normal ) {
  1250. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1251. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1252. }
  1253. }(),
  1254. angleTo: function ( v ) {
  1255. var theta = this.dot( v ) / ( this.length() * v.length() );
  1256. // clamp, to handle numerical problems
  1257. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1258. },
  1259. distanceTo: function ( v ) {
  1260. return Math.sqrt( this.distanceToSquared( v ) );
  1261. },
  1262. distanceToSquared: function ( v ) {
  1263. var dx = this.x - v.x;
  1264. var dy = this.y - v.y;
  1265. var dz = this.z - v.z;
  1266. return dx * dx + dy * dy + dz * dz;
  1267. },
  1268. setEulerFromRotationMatrix: function ( m, order ) {
  1269. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1270. },
  1271. setEulerFromQuaternion: function ( q, order ) {
  1272. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1273. },
  1274. getPositionFromMatrix: function ( m ) {
  1275. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1276. return this.setFromMatrixPosition( m );
  1277. },
  1278. getScaleFromMatrix: function ( m ) {
  1279. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1280. return this.setFromMatrixScale( m );
  1281. },
  1282. getColumnFromMatrix: function ( index, matrix ) {
  1283. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1284. return this.setFromMatrixColumn( index, matrix );
  1285. },
  1286. setFromMatrixPosition: function ( m ) {
  1287. this.x = m.elements[ 12 ];
  1288. this.y = m.elements[ 13 ];
  1289. this.z = m.elements[ 14 ];
  1290. return this;
  1291. },
  1292. setFromMatrixScale: function ( m ) {
  1293. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1294. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1295. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1296. this.x = sx;
  1297. this.y = sy;
  1298. this.z = sz;
  1299. return this;
  1300. },
  1301. setFromMatrixColumn: function ( index, matrix ) {
  1302. var offset = index * 4;
  1303. var me = matrix.elements;
  1304. this.x = me[ offset ];
  1305. this.y = me[ offset + 1 ];
  1306. this.z = me[ offset + 2 ];
  1307. return this;
  1308. },
  1309. equals: function ( v ) {
  1310. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1311. },
  1312. fromArray: function ( array ) {
  1313. this.x = array[ 0 ];
  1314. this.y = array[ 1 ];
  1315. this.z = array[ 2 ];
  1316. return this;
  1317. },
  1318. toArray: function () {
  1319. return [ this.x, this.y, this.z ];
  1320. },
  1321. clone: function () {
  1322. return new THREE.Vector3( this.x, this.y, this.z );
  1323. }
  1324. };
  1325. /**
  1326. * @author supereggbert / http://www.paulbrunt.co.uk/
  1327. * @author philogb / http://blog.thejit.org/
  1328. * @author mikael emtinger / http://gomo.se/
  1329. * @author egraether / http://egraether.com/
  1330. * @author WestLangley / http://github.com/WestLangley
  1331. */
  1332. THREE.Vector4 = function ( x, y, z, w ) {
  1333. this.x = x || 0;
  1334. this.y = y || 0;
  1335. this.z = z || 0;
  1336. this.w = ( w !== undefined ) ? w : 1;
  1337. };
  1338. THREE.Vector4.prototype = {
  1339. constructor: THREE.Vector4,
  1340. set: function ( x, y, z, w ) {
  1341. this.x = x;
  1342. this.y = y;
  1343. this.z = z;
  1344. this.w = w;
  1345. return this;
  1346. },
  1347. setX: function ( x ) {
  1348. this.x = x;
  1349. return this;
  1350. },
  1351. setY: function ( y ) {
  1352. this.y = y;
  1353. return this;
  1354. },
  1355. setZ: function ( z ) {
  1356. this.z = z;
  1357. return this;
  1358. },
  1359. setW: function ( w ) {
  1360. this.w = w;
  1361. return this;
  1362. },
  1363. setComponent: function ( index, value ) {
  1364. switch ( index ) {
  1365. case 0: this.x = value; break;
  1366. case 1: this.y = value; break;
  1367. case 2: this.z = value; break;
  1368. case 3: this.w = value; break;
  1369. default: throw new Error( "index is out of range: " + index );
  1370. }
  1371. },
  1372. getComponent: function ( index ) {
  1373. switch ( index ) {
  1374. case 0: return this.x;
  1375. case 1: return this.y;
  1376. case 2: return this.z;
  1377. case 3: return this.w;
  1378. default: throw new Error( "index is out of range: " + index );
  1379. }
  1380. },
  1381. copy: function ( v ) {
  1382. this.x = v.x;
  1383. this.y = v.y;
  1384. this.z = v.z;
  1385. this.w = ( v.w !== undefined ) ? v.w : 1;
  1386. return this;
  1387. },
  1388. add: function ( v, w ) {
  1389. if ( w !== undefined ) {
  1390. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1391. return this.addVectors( v, w );
  1392. }
  1393. this.x += v.x;
  1394. this.y += v.y;
  1395. this.z += v.z;
  1396. this.w += v.w;
  1397. return this;
  1398. },
  1399. addScalar: function ( s ) {
  1400. this.x += s;
  1401. this.y += s;
  1402. this.z += s;
  1403. this.w += s;
  1404. return this;
  1405. },
  1406. addVectors: function ( a, b ) {
  1407. this.x = a.x + b.x;
  1408. this.y = a.y + b.y;
  1409. this.z = a.z + b.z;
  1410. this.w = a.w + b.w;
  1411. return this;
  1412. },
  1413. sub: function ( v, w ) {
  1414. if ( w !== undefined ) {
  1415. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1416. return this.subVectors( v, w );
  1417. }
  1418. this.x -= v.x;
  1419. this.y -= v.y;
  1420. this.z -= v.z;
  1421. this.w -= v.w;
  1422. return this;
  1423. },
  1424. subVectors: function ( a, b ) {
  1425. this.x = a.x - b.x;
  1426. this.y = a.y - b.y;
  1427. this.z = a.z - b.z;
  1428. this.w = a.w - b.w;
  1429. return this;
  1430. },
  1431. multiplyScalar: function ( scalar ) {
  1432. this.x *= scalar;
  1433. this.y *= scalar;
  1434. this.z *= scalar;
  1435. this.w *= scalar;
  1436. return this;
  1437. },
  1438. applyMatrix4: function ( m ) {
  1439. var x = this.x;
  1440. var y = this.y;
  1441. var z = this.z;
  1442. var w = this.w;
  1443. var e = m.elements;
  1444. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1445. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1446. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1447. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1448. return this;
  1449. },
  1450. divideScalar: function ( scalar ) {
  1451. if ( scalar !== 0 ) {
  1452. var invScalar = 1 / scalar;
  1453. this.x *= invScalar;
  1454. this.y *= invScalar;
  1455. this.z *= invScalar;
  1456. this.w *= invScalar;
  1457. } else {
  1458. this.x = 0;
  1459. this.y = 0;
  1460. this.z = 0;
  1461. this.w = 1;
  1462. }
  1463. return this;
  1464. },
  1465. setAxisAngleFromQuaternion: function ( q ) {
  1466. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1467. // q is assumed to be normalized
  1468. this.w = 2 * Math.acos( q.w );
  1469. var s = Math.sqrt( 1 - q.w * q.w );
  1470. if ( s < 0.0001 ) {
  1471. this.x = 1;
  1472. this.y = 0;
  1473. this.z = 0;
  1474. } else {
  1475. this.x = q.x / s;
  1476. this.y = q.y / s;
  1477. this.z = q.z / s;
  1478. }
  1479. return this;
  1480. },
  1481. setAxisAngleFromRotationMatrix: function ( m ) {
  1482. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1483. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1484. var angle, x, y, z, // variables for result
  1485. epsilon = 0.01, // margin to allow for rounding errors
  1486. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1487. te = m.elements,
  1488. m11 = te[0], m12 = te[4], m13 = te[8],
  1489. m21 = te[1], m22 = te[5], m23 = te[9],
  1490. m31 = te[2], m32 = te[6], m33 = te[10];
  1491. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1492. && ( Math.abs( m13 - m31 ) < epsilon )
  1493. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1494. // singularity found
  1495. // first check for identity matrix which must have +1 for all terms
  1496. // in leading diagonal and zero in other terms
  1497. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1498. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1499. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1500. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1501. // this singularity is identity matrix so angle = 0
  1502. this.set( 1, 0, 0, 0 );
  1503. return this; // zero angle, arbitrary axis
  1504. }
  1505. // otherwise this singularity is angle = 180
  1506. angle = Math.PI;
  1507. var xx = ( m11 + 1 ) / 2;
  1508. var yy = ( m22 + 1 ) / 2;
  1509. var zz = ( m33 + 1 ) / 2;
  1510. var xy = ( m12 + m21 ) / 4;
  1511. var xz = ( m13 + m31 ) / 4;
  1512. var yz = ( m23 + m32 ) / 4;
  1513. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1514. if ( xx < epsilon ) {
  1515. x = 0;
  1516. y = 0.707106781;
  1517. z = 0.707106781;
  1518. } else {
  1519. x = Math.sqrt( xx );
  1520. y = xy / x;
  1521. z = xz / x;
  1522. }
  1523. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1524. if ( yy < epsilon ) {
  1525. x = 0.707106781;
  1526. y = 0;
  1527. z = 0.707106781;
  1528. } else {
  1529. y = Math.sqrt( yy );
  1530. x = xy / y;
  1531. z = yz / y;
  1532. }
  1533. } else { // m33 is the largest diagonal term so base result on this
  1534. if ( zz < epsilon ) {
  1535. x = 0.707106781;
  1536. y = 0.707106781;
  1537. z = 0;
  1538. } else {
  1539. z = Math.sqrt( zz );
  1540. x = xz / z;
  1541. y = yz / z;
  1542. }
  1543. }
  1544. this.set( x, y, z, angle );
  1545. return this; // return 180 deg rotation
  1546. }
  1547. // as we have reached here there are no singularities so we can handle normally
  1548. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1549. + ( m13 - m31 ) * ( m13 - m31 )
  1550. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1551. if ( Math.abs( s ) < 0.001 ) s = 1;
  1552. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1553. // caught by singularity test above, but I've left it in just in case
  1554. this.x = ( m32 - m23 ) / s;
  1555. this.y = ( m13 - m31 ) / s;
  1556. this.z = ( m21 - m12 ) / s;
  1557. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1558. return this;
  1559. },
  1560. min: function ( v ) {
  1561. if ( this.x > v.x ) {
  1562. this.x = v.x;
  1563. }
  1564. if ( this.y > v.y ) {
  1565. this.y = v.y;
  1566. }
  1567. if ( this.z > v.z ) {
  1568. this.z = v.z;
  1569. }
  1570. if ( this.w > v.w ) {
  1571. this.w = v.w;
  1572. }
  1573. return this;
  1574. },
  1575. max: function ( v ) {
  1576. if ( this.x < v.x ) {
  1577. this.x = v.x;
  1578. }
  1579. if ( this.y < v.y ) {
  1580. this.y = v.y;
  1581. }
  1582. if ( this.z < v.z ) {
  1583. this.z = v.z;
  1584. }
  1585. if ( this.w < v.w ) {
  1586. this.w = v.w;
  1587. }
  1588. return this;
  1589. },
  1590. clamp: function ( min, max ) {
  1591. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1592. if ( this.x < min.x ) {
  1593. this.x = min.x;
  1594. } else if ( this.x > max.x ) {
  1595. this.x = max.x;
  1596. }
  1597. if ( this.y < min.y ) {
  1598. this.y = min.y;
  1599. } else if ( this.y > max.y ) {
  1600. this.y = max.y;
  1601. }
  1602. if ( this.z < min.z ) {
  1603. this.z = min.z;
  1604. } else if ( this.z > max.z ) {
  1605. this.z = max.z;
  1606. }
  1607. if ( this.w < min.w ) {
  1608. this.w = min.w;
  1609. } else if ( this.w > max.w ) {
  1610. this.w = max.w;
  1611. }
  1612. return this;
  1613. },
  1614. clampScalar: ( function () {
  1615. var min, max;
  1616. return function ( minVal, maxVal ) {
  1617. if ( min === undefined ) {
  1618. min = new THREE.Vector4();
  1619. max = new THREE.Vector4();
  1620. }
  1621. min.set( minVal, minVal, minVal, minVal );
  1622. max.set( maxVal, maxVal, maxVal, maxVal );
  1623. return this.clamp( min, max );
  1624. };
  1625. } )(),
  1626. floor: function () {
  1627. this.x = Math.floor( this.x );
  1628. this.y = Math.floor( this.y );
  1629. this.z = Math.floor( this.z );
  1630. this.w = Math.floor( this.w );
  1631. return this;
  1632. },
  1633. ceil: function () {
  1634. this.x = Math.ceil( this.x );
  1635. this.y = Math.ceil( this.y );
  1636. this.z = Math.ceil( this.z );
  1637. this.w = Math.ceil( this.w );
  1638. return this;
  1639. },
  1640. round: function () {
  1641. this.x = Math.round( this.x );
  1642. this.y = Math.round( this.y );
  1643. this.z = Math.round( this.z );
  1644. this.w = Math.round( this.w );
  1645. return this;
  1646. },
  1647. roundToZero: function () {
  1648. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1649. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1650. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1651. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1652. return this;
  1653. },
  1654. negate: function () {
  1655. return this.multiplyScalar( -1 );
  1656. },
  1657. dot: function ( v ) {
  1658. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1659. },
  1660. lengthSq: function () {
  1661. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1662. },
  1663. length: function () {
  1664. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1665. },
  1666. lengthManhattan: function () {
  1667. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1668. },
  1669. normalize: function () {
  1670. return this.divideScalar( this.length() );
  1671. },
  1672. setLength: function ( l ) {
  1673. var oldLength = this.length();
  1674. if ( oldLength !== 0 && l !== oldLength ) {
  1675. this.multiplyScalar( l / oldLength );
  1676. }
  1677. return this;
  1678. },
  1679. lerp: function ( v, alpha ) {
  1680. this.x += ( v.x - this.x ) * alpha;
  1681. this.y += ( v.y - this.y ) * alpha;
  1682. this.z += ( v.z - this.z ) * alpha;
  1683. this.w += ( v.w - this.w ) * alpha;
  1684. return this;
  1685. },
  1686. equals: function ( v ) {
  1687. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1688. },
  1689. fromArray: function ( array ) {
  1690. this.x = array[ 0 ];
  1691. this.y = array[ 1 ];
  1692. this.z = array[ 2 ];
  1693. this.w = array[ 3 ];
  1694. return this;
  1695. },
  1696. toArray: function () {
  1697. return [ this.x, this.y, this.z, this.w ];
  1698. },
  1699. clone: function () {
  1700. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1701. }
  1702. };
  1703. /**
  1704. * @author mrdoob / http://mrdoob.com/
  1705. */
  1706. THREE.TypedVector2 = function ( array, offset ) {
  1707. this.array = array;
  1708. this.offset = offset;
  1709. };
  1710. THREE.TypedVector2.prototype = Object.create( THREE.Vector2.prototype );
  1711. Object.defineProperties( THREE.TypedVector2.prototype, {
  1712. 'x': {
  1713. get: function () { return this.array[ this.offset ]; },
  1714. set: function ( v ) { this.array[ this.offset ] = v; }
  1715. },
  1716. 'y': {
  1717. get: function () { return this.array[ this.offset + 1 ]; },
  1718. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  1719. }
  1720. } );
  1721. /**
  1722. * @author mrdoob / http://mrdoob.com/
  1723. */
  1724. THREE.TypedVector3 = function ( array, offset ) {
  1725. this.array = array;
  1726. this.offset = offset;
  1727. };
  1728. THREE.TypedVector3.prototype = Object.create( THREE.Vector3.prototype );
  1729. Object.defineProperties( THREE.TypedVector3.prototype, {
  1730. 'x': {
  1731. get: function () { return this.array[ this.offset ]; },
  1732. set: function ( v ) { this.array[ this.offset ] = v; }
  1733. },
  1734. 'y': {
  1735. get: function () { return this.array[ this.offset + 1 ]; },
  1736. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  1737. },
  1738. 'z': {
  1739. get: function () { return this.array[ this.offset + 2 ]; },
  1740. set: function ( v ) { this.array[ this.offset + 2 ] = v; }
  1741. }
  1742. } );
  1743. /**
  1744. * @author mrdoob / http://mrdoob.com/
  1745. * @author WestLangley / http://github.com/WestLangley
  1746. * @author bhouston / http://exocortex.com
  1747. */
  1748. THREE.Euler = function ( x, y, z, order ) {
  1749. this._x = x || 0;
  1750. this._y = y || 0;
  1751. this._z = z || 0;
  1752. this._order = order || THREE.Euler.DefaultOrder;
  1753. };
  1754. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1755. THREE.Euler.DefaultOrder = 'XYZ';
  1756. THREE.Euler.prototype = {
  1757. constructor: THREE.Euler,
  1758. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1759. _quaternion: undefined,
  1760. _updateQuaternion: function () {
  1761. if ( this._quaternion !== undefined ) {
  1762. this._quaternion.setFromEuler( this, false );
  1763. }
  1764. },
  1765. get x () {
  1766. return this._x;
  1767. },
  1768. set x ( value ) {
  1769. this._x = value;
  1770. this._updateQuaternion();
  1771. },
  1772. get y () {
  1773. return this._y;
  1774. },
  1775. set y ( value ) {
  1776. this._y = value;
  1777. this._updateQuaternion();
  1778. },
  1779. get z () {
  1780. return this._z;
  1781. },
  1782. set z ( value ) {
  1783. this._z = value;
  1784. this._updateQuaternion();
  1785. },
  1786. get order () {
  1787. return this._order;
  1788. },
  1789. set order ( value ) {
  1790. this._order = value;
  1791. this._updateQuaternion();
  1792. },
  1793. set: function ( x, y, z, order ) {
  1794. this._x = x;
  1795. this._y = y;
  1796. this._z = z;
  1797. this._order = order || this._order;
  1798. this._updateQuaternion();
  1799. return this;
  1800. },
  1801. copy: function ( euler ) {
  1802. this._x = euler._x;
  1803. this._y = euler._y;
  1804. this._z = euler._z;
  1805. this._order = euler._order;
  1806. this._updateQuaternion();
  1807. return this;
  1808. },
  1809. setFromRotationMatrix: function ( m, order ) {
  1810. var clamp = THREE.Math.clamp;
  1811. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1812. var te = m.elements;
  1813. var m11 = te[0], m12 = te[4], m13 = te[8];
  1814. var m21 = te[1], m22 = te[5], m23 = te[9];
  1815. var m31 = te[2], m32 = te[6], m33 = te[10];
  1816. order = order || this._order;
  1817. if ( order === 'XYZ' ) {
  1818. this._y = Math.asin( clamp( m13, -1, 1 ) );
  1819. if ( Math.abs( m13 ) < 0.99999 ) {
  1820. this._x = Math.atan2( - m23, m33 );
  1821. this._z = Math.atan2( - m12, m11 );
  1822. } else {
  1823. this._x = Math.atan2( m32, m22 );
  1824. this._z = 0;
  1825. }
  1826. } else if ( order === 'YXZ' ) {
  1827. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  1828. if ( Math.abs( m23 ) < 0.99999 ) {
  1829. this._y = Math.atan2( m13, m33 );
  1830. this._z = Math.atan2( m21, m22 );
  1831. } else {
  1832. this._y = Math.atan2( - m31, m11 );
  1833. this._z = 0;
  1834. }
  1835. } else if ( order === 'ZXY' ) {
  1836. this._x = Math.asin( clamp( m32, -1, 1 ) );
  1837. if ( Math.abs( m32 ) < 0.99999 ) {
  1838. this._y = Math.atan2( - m31, m33 );
  1839. this._z = Math.atan2( - m12, m22 );
  1840. } else {
  1841. this._y = 0;
  1842. this._z = Math.atan2( m21, m11 );
  1843. }
  1844. } else if ( order === 'ZYX' ) {
  1845. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  1846. if ( Math.abs( m31 ) < 0.99999 ) {
  1847. this._x = Math.atan2( m32, m33 );
  1848. this._z = Math.atan2( m21, m11 );
  1849. } else {
  1850. this._x = 0;
  1851. this._z = Math.atan2( - m12, m22 );
  1852. }
  1853. } else if ( order === 'YZX' ) {
  1854. this._z = Math.asin( clamp( m21, -1, 1 ) );
  1855. if ( Math.abs( m21 ) < 0.99999 ) {
  1856. this._x = Math.atan2( - m23, m22 );
  1857. this._y = Math.atan2( - m31, m11 );
  1858. } else {
  1859. this._x = 0;
  1860. this._y = Math.atan2( m13, m33 );
  1861. }
  1862. } else if ( order === 'XZY' ) {
  1863. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  1864. if ( Math.abs( m12 ) < 0.99999 ) {
  1865. this._x = Math.atan2( m32, m22 );
  1866. this._y = Math.atan2( m13, m11 );
  1867. } else {
  1868. this._x = Math.atan2( - m23, m33 );
  1869. this._y = 0;
  1870. }
  1871. } else {
  1872. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1873. }
  1874. this._order = order;
  1875. this._updateQuaternion();
  1876. return this;
  1877. },
  1878. setFromQuaternion: function ( q, order, update ) {
  1879. var clamp = THREE.Math.clamp;
  1880. // q is assumed to be normalized
  1881. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1882. var sqx = q.x * q.x;
  1883. var sqy = q.y * q.y;
  1884. var sqz = q.z * q.z;
  1885. var sqw = q.w * q.w;
  1886. order = order || this._order;
  1887. if ( order === 'XYZ' ) {
  1888. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1889. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), -1, 1 ) );
  1890. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1891. } else if ( order === 'YXZ' ) {
  1892. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ), -1, 1 ) );
  1893. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1894. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1895. } else if ( order === 'ZXY' ) {
  1896. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ), -1, 1 ) );
  1897. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1898. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1899. } else if ( order === 'ZYX' ) {
  1900. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1901. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ), -1, 1 ) );
  1902. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1903. } else if ( order === 'YZX' ) {
  1904. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1905. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1906. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ), -1, 1 ) );
  1907. } else if ( order === 'XZY' ) {
  1908. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1909. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1910. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ), -1, 1 ) );
  1911. } else {
  1912. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1913. }
  1914. this._order = order;
  1915. if ( update !== false ) this._updateQuaternion();
  1916. return this;
  1917. },
  1918. reorder: function () {
  1919. // WARNING: this discards revolution information -bhouston
  1920. var q = new THREE.Quaternion();
  1921. return function ( newOrder ) {
  1922. q.setFromEuler( this );
  1923. this.setFromQuaternion( q, newOrder );
  1924. };
  1925. }(),
  1926. fromArray: function ( array ) {
  1927. this._x = array[ 0 ];
  1928. this._y = array[ 1 ];
  1929. this._z = array[ 2 ];
  1930. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1931. this._updateQuaternion();
  1932. return this;
  1933. },
  1934. toArray: function () {
  1935. return [ this._x, this._y, this._z, this._order ];
  1936. },
  1937. equals: function ( euler ) {
  1938. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1939. },
  1940. clone: function () {
  1941. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1942. }
  1943. };
  1944. /**
  1945. * @author bhouston / http://exocortex.com
  1946. */
  1947. THREE.Line3 = function ( start, end ) {
  1948. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1949. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1950. };
  1951. THREE.Line3.prototype = {
  1952. constructor: THREE.Line3,
  1953. set: function ( start, end ) {
  1954. this.start.copy( start );
  1955. this.end.copy( end );
  1956. return this;
  1957. },
  1958. copy: function ( line ) {
  1959. this.start.copy( line.start );
  1960. this.end.copy( line.end );
  1961. return this;
  1962. },
  1963. center: function ( optionalTarget ) {
  1964. var result = optionalTarget || new THREE.Vector3();
  1965. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1966. },
  1967. delta: function ( optionalTarget ) {
  1968. var result = optionalTarget || new THREE.Vector3();
  1969. return result.subVectors( this.end, this.start );
  1970. },
  1971. distanceSq: function () {
  1972. return this.start.distanceToSquared( this.end );
  1973. },
  1974. distance: function () {
  1975. return this.start.distanceTo( this.end );
  1976. },
  1977. at: function ( t, optionalTarget ) {
  1978. var result = optionalTarget || new THREE.Vector3();
  1979. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1980. },
  1981. closestPointToPointParameter: function() {
  1982. var startP = new THREE.Vector3();
  1983. var startEnd = new THREE.Vector3();
  1984. return function ( point, clampToLine ) {
  1985. startP.subVectors( point, this.start );
  1986. startEnd.subVectors( this.end, this.start );
  1987. var startEnd2 = startEnd.dot( startEnd );
  1988. var startEnd_startP = startEnd.dot( startP );
  1989. var t = startEnd_startP / startEnd2;
  1990. if ( clampToLine ) {
  1991. t = THREE.Math.clamp( t, 0, 1 );
  1992. }
  1993. return t;
  1994. };
  1995. }(),
  1996. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1997. var t = this.closestPointToPointParameter( point, clampToLine );
  1998. var result = optionalTarget || new THREE.Vector3();
  1999. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2000. },
  2001. applyMatrix4: function ( matrix ) {
  2002. this.start.applyMatrix4( matrix );
  2003. this.end.applyMatrix4( matrix );
  2004. return this;
  2005. },
  2006. equals: function ( line ) {
  2007. return line.start.equals( this.start ) && line.end.equals( this.end );
  2008. },
  2009. clone: function () {
  2010. return new THREE.Line3().copy( this );
  2011. }
  2012. };
  2013. /**
  2014. * @author bhouston / http://exocortex.com
  2015. */
  2016. THREE.Box2 = function ( min, max ) {
  2017. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2018. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  2019. };
  2020. THREE.Box2.prototype = {
  2021. constructor: THREE.Box2,
  2022. set: function ( min, max ) {
  2023. this.min.copy( min );
  2024. this.max.copy( max );
  2025. return this;
  2026. },
  2027. setFromPoints: function ( points ) {
  2028. if ( points.length > 0 ) {
  2029. var point = points[ 0 ];
  2030. this.min.copy( point );
  2031. this.max.copy( point );
  2032. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2033. point = points[ i ];
  2034. if ( point.x < this.min.x ) {
  2035. this.min.x = point.x;
  2036. } else if ( point.x > this.max.x ) {
  2037. this.max.x = point.x;
  2038. }
  2039. if ( point.y < this.min.y ) {
  2040. this.min.y = point.y;
  2041. } else if ( point.y > this.max.y ) {
  2042. this.max.y = point.y;
  2043. }
  2044. }
  2045. } else {
  2046. this.makeEmpty();
  2047. }
  2048. return this;
  2049. },
  2050. setFromCenterAndSize: function () {
  2051. var v1 = new THREE.Vector2();
  2052. return function ( center, size ) {
  2053. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2054. this.min.copy( center ).sub( halfSize );
  2055. this.max.copy( center ).add( halfSize );
  2056. return this;
  2057. };
  2058. }(),
  2059. copy: function ( box ) {
  2060. this.min.copy( box.min );
  2061. this.max.copy( box.max );
  2062. return this;
  2063. },
  2064. makeEmpty: function () {
  2065. this.min.x = this.min.y = Infinity;
  2066. this.max.x = this.max.y = -Infinity;
  2067. return this;
  2068. },
  2069. empty: function () {
  2070. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2071. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2072. },
  2073. center: function ( optionalTarget ) {
  2074. var result = optionalTarget || new THREE.Vector2();
  2075. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2076. },
  2077. size: function ( optionalTarget ) {
  2078. var result = optionalTarget || new THREE.Vector2();
  2079. return result.subVectors( this.max, this.min );
  2080. },
  2081. expandByPoint: function ( point ) {
  2082. this.min.min( point );
  2083. this.max.max( point );
  2084. return this;
  2085. },
  2086. expandByVector: function ( vector ) {
  2087. this.min.sub( vector );
  2088. this.max.add( vector );
  2089. return this;
  2090. },
  2091. expandByScalar: function ( scalar ) {
  2092. this.min.addScalar( -scalar );
  2093. this.max.addScalar( scalar );
  2094. return this;
  2095. },
  2096. containsPoint: function ( point ) {
  2097. if ( point.x < this.min.x || point.x > this.max.x ||
  2098. point.y < this.min.y || point.y > this.max.y ) {
  2099. return false;
  2100. }
  2101. return true;
  2102. },
  2103. containsBox: function ( box ) {
  2104. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2105. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2106. return true;
  2107. }
  2108. return false;
  2109. },
  2110. getParameter: function ( point, optionalTarget ) {
  2111. // This can potentially have a divide by zero if the box
  2112. // has a size dimension of 0.
  2113. var result = optionalTarget || new THREE.Vector2();
  2114. return result.set(
  2115. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2116. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2117. );
  2118. },
  2119. isIntersectionBox: function ( box ) {
  2120. // using 6 splitting planes to rule out intersections.
  2121. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2122. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2123. return false;
  2124. }
  2125. return true;
  2126. },
  2127. clampPoint: function ( point, optionalTarget ) {
  2128. var result = optionalTarget || new THREE.Vector2();
  2129. return result.copy( point ).clamp( this.min, this.max );
  2130. },
  2131. distanceToPoint: function () {
  2132. var v1 = new THREE.Vector2();
  2133. return function ( point ) {
  2134. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2135. return clampedPoint.sub( point ).length();
  2136. };
  2137. }(),
  2138. intersect: function ( box ) {
  2139. this.min.max( box.min );
  2140. this.max.min( box.max );
  2141. return this;
  2142. },
  2143. union: function ( box ) {
  2144. this.min.min( box.min );
  2145. this.max.max( box.max );
  2146. return this;
  2147. },
  2148. translate: function ( offset ) {
  2149. this.min.add( offset );
  2150. this.max.add( offset );
  2151. return this;
  2152. },
  2153. equals: function ( box ) {
  2154. return box.min.equals( this.min ) && box.max.equals( this.max );
  2155. },
  2156. clone: function () {
  2157. return new THREE.Box2().copy( this );
  2158. }
  2159. };
  2160. /**
  2161. * @author bhouston / http://exocortex.com
  2162. * @author WestLangley / http://github.com/WestLangley
  2163. */
  2164. THREE.Box3 = function ( min, max ) {
  2165. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2166. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2167. };
  2168. THREE.Box3.prototype = {
  2169. constructor: THREE.Box3,
  2170. set: function ( min, max ) {
  2171. this.min.copy( min );
  2172. this.max.copy( max );
  2173. return this;
  2174. },
  2175. addPoint: function ( point ) {
  2176. if ( point.x < this.min.x ) {
  2177. this.min.x = point.x;
  2178. } else if ( point.x > this.max.x ) {
  2179. this.max.x = point.x;
  2180. }
  2181. if ( point.y < this.min.y ) {
  2182. this.min.y = point.y;
  2183. } else if ( point.y > this.max.y ) {
  2184. this.max.y = point.y;
  2185. }
  2186. if ( point.z < this.min.z ) {
  2187. this.min.z = point.z;
  2188. } else if ( point.z > this.max.z ) {
  2189. this.max.z = point.z;
  2190. }
  2191. },
  2192. setFromPoints: function ( points ) {
  2193. if ( points.length > 0 ) {
  2194. var point = points[ 0 ];
  2195. this.min.copy( point );
  2196. this.max.copy( point );
  2197. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2198. this.addPoint( points[ i ] )
  2199. }
  2200. } else {
  2201. this.makeEmpty();
  2202. }
  2203. return this;
  2204. },
  2205. setFromCenterAndSize: function() {
  2206. var v1 = new THREE.Vector3();
  2207. return function ( center, size ) {
  2208. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2209. this.min.copy( center ).sub( halfSize );
  2210. this.max.copy( center ).add( halfSize );
  2211. return this;
  2212. };
  2213. }(),
  2214. setFromObject: function() {
  2215. // Computes the world-axis-aligned bounding box of an object (including its children),
  2216. // accounting for both the object's, and childrens', world transforms
  2217. var v1 = new THREE.Vector3();
  2218. return function( object ) {
  2219. var scope = this;
  2220. object.updateMatrixWorld( true );
  2221. this.makeEmpty();
  2222. object.traverse( function ( node ) {
  2223. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2224. var vertices = node.geometry.vertices;
  2225. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2226. v1.copy( vertices[ i ] );
  2227. v1.applyMatrix4( node.matrixWorld );
  2228. scope.expandByPoint( v1 );
  2229. }
  2230. }
  2231. } );
  2232. return this;
  2233. };
  2234. }(),
  2235. copy: function ( box ) {
  2236. this.min.copy( box.min );
  2237. this.max.copy( box.max );
  2238. return this;
  2239. },
  2240. makeEmpty: function () {
  2241. this.min.x = this.min.y = this.min.z = Infinity;
  2242. this.max.x = this.max.y = this.max.z = -Infinity;
  2243. return this;
  2244. },
  2245. empty: function () {
  2246. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2247. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2248. },
  2249. center: function ( optionalTarget ) {
  2250. var result = optionalTarget || new THREE.Vector3();
  2251. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2252. },
  2253. size: function ( optionalTarget ) {
  2254. var result = optionalTarget || new THREE.Vector3();
  2255. return result.subVectors( this.max, this.min );
  2256. },
  2257. expandByPoint: function ( point ) {
  2258. this.min.min( point );
  2259. this.max.max( point );
  2260. return this;
  2261. },
  2262. expandByVector: function ( vector ) {
  2263. this.min.sub( vector );
  2264. this.max.add( vector );
  2265. return this;
  2266. },
  2267. expandByScalar: function ( scalar ) {
  2268. this.min.addScalar( -scalar );
  2269. this.max.addScalar( scalar );
  2270. return this;
  2271. },
  2272. containsPoint: function ( point ) {
  2273. if ( point.x < this.min.x || point.x > this.max.x ||
  2274. point.y < this.min.y || point.y > this.max.y ||
  2275. point.z < this.min.z || point.z > this.max.z ) {
  2276. return false;
  2277. }
  2278. return true;
  2279. },
  2280. containsBox: function ( box ) {
  2281. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2282. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2283. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2284. return true;
  2285. }
  2286. return false;
  2287. },
  2288. getParameter: function ( point, optionalTarget ) {
  2289. // This can potentially have a divide by zero if the box
  2290. // has a size dimension of 0.
  2291. var result = optionalTarget || new THREE.Vector3();
  2292. return result.set(
  2293. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2294. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2295. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2296. );
  2297. },
  2298. isIntersectionBox: function ( box ) {
  2299. // using 6 splitting planes to rule out intersections.
  2300. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2301. box.max.y < this.min.y || box.min.y > this.max.y ||
  2302. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2303. return false;
  2304. }
  2305. return true;
  2306. },
  2307. clampPoint: function ( point, optionalTarget ) {
  2308. var result = optionalTarget || new THREE.Vector3();
  2309. return result.copy( point ).clamp( this.min, this.max );
  2310. },
  2311. distanceToPoint: function() {
  2312. var v1 = new THREE.Vector3();
  2313. return function ( point ) {
  2314. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2315. return clampedPoint.sub( point ).length();
  2316. };
  2317. }(),
  2318. getBoundingSphere: function() {
  2319. var v1 = new THREE.Vector3();
  2320. return function ( optionalTarget ) {
  2321. var result = optionalTarget || new THREE.Sphere();
  2322. result.center = this.center();
  2323. result.radius = this.size( v1 ).length() * 0.5;
  2324. return result;
  2325. };
  2326. }(),
  2327. intersect: function ( box ) {
  2328. this.min.max( box.min );
  2329. this.max.min( box.max );
  2330. return this;
  2331. },
  2332. union: function ( box ) {
  2333. this.min.min( box.min );
  2334. this.max.max( box.max );
  2335. return this;
  2336. },
  2337. applyMatrix4: function() {
  2338. var points = [
  2339. new THREE.Vector3(),
  2340. new THREE.Vector3(),
  2341. new THREE.Vector3(),
  2342. new THREE.Vector3(),
  2343. new THREE.Vector3(),
  2344. new THREE.Vector3(),
  2345. new THREE.Vector3(),
  2346. new THREE.Vector3()
  2347. ];
  2348. return function ( matrix ) {
  2349. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2350. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2351. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2352. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2353. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2354. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2355. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2356. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2357. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2358. this.makeEmpty();
  2359. this.setFromPoints( points );
  2360. return this;
  2361. };
  2362. }(),
  2363. translate: function ( offset ) {
  2364. this.min.add( offset );
  2365. this.max.add( offset );
  2366. return this;
  2367. },
  2368. equals: function ( box ) {
  2369. return box.min.equals( this.min ) && box.max.equals( this.max );
  2370. },
  2371. clone: function () {
  2372. return new THREE.Box3().copy( this );
  2373. }
  2374. };
  2375. /**
  2376. * @author alteredq / http://alteredqualia.com/
  2377. * @author WestLangley / http://github.com/WestLangley
  2378. * @author bhouston / http://exocortex.com
  2379. */
  2380. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2381. this.elements = new Float32Array(9);
  2382. this.set(
  2383. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2384. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2385. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2386. );
  2387. };
  2388. THREE.Matrix3.prototype = {
  2389. constructor: THREE.Matrix3,
  2390. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2391. var te = this.elements;
  2392. te[0] = n11; te[3] = n12; te[6] = n13;
  2393. te[1] = n21; te[4] = n22; te[7] = n23;
  2394. te[2] = n31; te[5] = n32; te[8] = n33;
  2395. return this;
  2396. },
  2397. identity: function () {
  2398. this.set(
  2399. 1, 0, 0,
  2400. 0, 1, 0,
  2401. 0, 0, 1
  2402. );
  2403. return this;
  2404. },
  2405. copy: function ( m ) {
  2406. var me = m.elements;
  2407. this.set(
  2408. me[0], me[3], me[6],
  2409. me[1], me[4], me[7],
  2410. me[2], me[5], me[8]
  2411. );
  2412. return this;
  2413. },
  2414. multiplyVector3: function ( vector ) {
  2415. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2416. return vector.applyMatrix3( this );
  2417. },
  2418. multiplyVector3Array: function ( a ) {
  2419. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2420. return this.applyToVector3Array( a );
  2421. },
  2422. applyToVector3Array: function() {
  2423. var v1 = new THREE.Vector3();
  2424. return function ( a ) {
  2425. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2426. v1.x = a[ i ];
  2427. v1.y = a[ i + 1 ];
  2428. v1.z = a[ i + 2 ];
  2429. v1.applyMatrix3( this );
  2430. a[ i ] = v1.x;
  2431. a[ i + 1 ] = v1.y;
  2432. a[ i + 2 ] = v1.z;
  2433. }
  2434. return a;
  2435. };
  2436. }(),
  2437. multiplyScalar: function ( s ) {
  2438. var te = this.elements;
  2439. te[0] *= s; te[3] *= s; te[6] *= s;
  2440. te[1] *= s; te[4] *= s; te[7] *= s;
  2441. te[2] *= s; te[5] *= s; te[8] *= s;
  2442. return this;
  2443. },
  2444. determinant: function () {
  2445. var te = this.elements;
  2446. var a = te[0], b = te[1], c = te[2],
  2447. d = te[3], e = te[4], f = te[5],
  2448. g = te[6], h = te[7], i = te[8];
  2449. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2450. },
  2451. getInverse: function ( matrix, throwOnInvertible ) {
  2452. // input: THREE.Matrix4
  2453. // ( based on http://code.google.com/p/webgl-mjs/ )
  2454. var me = matrix.elements;
  2455. var te = this.elements;
  2456. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2457. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2458. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2459. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2460. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2461. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2462. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2463. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2464. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2465. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2466. // no inverse
  2467. if ( det === 0 ) {
  2468. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2469. if ( throwOnInvertible || false ) {
  2470. throw new Error( msg );
  2471. } else {
  2472. console.warn( msg );
  2473. }
  2474. this.identity();
  2475. return this;
  2476. }
  2477. this.multiplyScalar( 1.0 / det );
  2478. return this;
  2479. },
  2480. transpose: function () {
  2481. var tmp, m = this.elements;
  2482. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2483. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2484. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2485. return this;
  2486. },
  2487. getNormalMatrix: function ( m ) {
  2488. // input: THREE.Matrix4
  2489. this.getInverse( m ).transpose();
  2490. return this;
  2491. },
  2492. transposeIntoArray: function ( r ) {
  2493. var m = this.elements;
  2494. r[ 0 ] = m[ 0 ];
  2495. r[ 1 ] = m[ 3 ];
  2496. r[ 2 ] = m[ 6 ];
  2497. r[ 3 ] = m[ 1 ];
  2498. r[ 4 ] = m[ 4 ];
  2499. r[ 5 ] = m[ 7 ];
  2500. r[ 6 ] = m[ 2 ];
  2501. r[ 7 ] = m[ 5 ];
  2502. r[ 8 ] = m[ 8 ];
  2503. return this;
  2504. },
  2505. fromArray: function ( array ) {
  2506. this.elements.set( array );
  2507. return this;
  2508. },
  2509. toArray: function () {
  2510. var te = this.elements;
  2511. return [
  2512. te[ 0 ], te[ 1 ], te[ 2 ],
  2513. te[ 3 ], te[ 4 ], te[ 5 ],
  2514. te[ 6 ], te[ 7 ], te[ 8 ]
  2515. ];
  2516. },
  2517. clone: function () {
  2518. var te = this.elements;
  2519. return new THREE.Matrix3(
  2520. te[0], te[3], te[6],
  2521. te[1], te[4], te[7],
  2522. te[2], te[5], te[8]
  2523. );
  2524. }
  2525. };
  2526. /**
  2527. * @author mrdoob / http://mrdoob.com/
  2528. * @author supereggbert / http://www.paulbrunt.co.uk/
  2529. * @author philogb / http://blog.thejit.org/
  2530. * @author jordi_ros / http://plattsoft.com
  2531. * @author D1plo1d / http://github.com/D1plo1d
  2532. * @author alteredq / http://alteredqualia.com/
  2533. * @author mikael emtinger / http://gomo.se/
  2534. * @author timknip / http://www.floorplanner.com/
  2535. * @author bhouston / http://exocortex.com
  2536. * @author WestLangley / http://github.com/WestLangley
  2537. */
  2538. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2539. this.elements = new Float32Array( 16 );
  2540. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2541. // we should not support semi specification of Matrix4, it is just weird.
  2542. var te = this.elements;
  2543. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2544. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2545. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2546. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2547. };
  2548. THREE.Matrix4.prototype = {
  2549. constructor: THREE.Matrix4,
  2550. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2551. var te = this.elements;
  2552. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2553. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2554. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2555. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2556. return this;
  2557. },
  2558. identity: function () {
  2559. this.set(
  2560. 1, 0, 0, 0,
  2561. 0, 1, 0, 0,
  2562. 0, 0, 1, 0,
  2563. 0, 0, 0, 1
  2564. );
  2565. return this;
  2566. },
  2567. copy: function ( m ) {
  2568. this.elements.set( m.elements );
  2569. return this;
  2570. },
  2571. extractPosition: function ( m ) {
  2572. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2573. return this.copyPosition( m );
  2574. },
  2575. copyPosition: function ( m ) {
  2576. var te = this.elements;
  2577. var me = m.elements;
  2578. te[12] = me[12];
  2579. te[13] = me[13];
  2580. te[14] = me[14];
  2581. return this;
  2582. },
  2583. extractRotation: function () {
  2584. var v1 = new THREE.Vector3();
  2585. return function ( m ) {
  2586. var te = this.elements;
  2587. var me = m.elements;
  2588. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2589. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2590. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2591. te[0] = me[0] * scaleX;
  2592. te[1] = me[1] * scaleX;
  2593. te[2] = me[2] * scaleX;
  2594. te[4] = me[4] * scaleY;
  2595. te[5] = me[5] * scaleY;
  2596. te[6] = me[6] * scaleY;
  2597. te[8] = me[8] * scaleZ;
  2598. te[9] = me[9] * scaleZ;
  2599. te[10] = me[10] * scaleZ;
  2600. return this;
  2601. };
  2602. }(),
  2603. makeRotationFromEuler: function ( euler ) {
  2604. if ( euler instanceof THREE.Euler === false ) {
  2605. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2606. }
  2607. var te = this.elements;
  2608. var x = euler.x, y = euler.y, z = euler.z;
  2609. var a = Math.cos( x ), b = Math.sin( x );
  2610. var c = Math.cos( y ), d = Math.sin( y );
  2611. var e = Math.cos( z ), f = Math.sin( z );
  2612. if ( euler.order === 'XYZ' ) {
  2613. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2614. te[0] = c * e;
  2615. te[4] = - c * f;
  2616. te[8] = d;
  2617. te[1] = af + be * d;
  2618. te[5] = ae - bf * d;
  2619. te[9] = - b * c;
  2620. te[2] = bf - ae * d;
  2621. te[6] = be + af * d;
  2622. te[10] = a * c;
  2623. } else if ( euler.order === 'YXZ' ) {
  2624. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2625. te[0] = ce + df * b;
  2626. te[4] = de * b - cf;
  2627. te[8] = a * d;
  2628. te[1] = a * f;
  2629. te[5] = a * e;
  2630. te[9] = - b;
  2631. te[2] = cf * b - de;
  2632. te[6] = df + ce * b;
  2633. te[10] = a * c;
  2634. } else if ( euler.order === 'ZXY' ) {
  2635. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2636. te[0] = ce - df * b;
  2637. te[4] = - a * f;
  2638. te[8] = de + cf * b;
  2639. te[1] = cf + de * b;
  2640. te[5] = a * e;
  2641. te[9] = df - ce * b;
  2642. te[2] = - a * d;
  2643. te[6] = b;
  2644. te[10] = a * c;
  2645. } else if ( euler.order === 'ZYX' ) {
  2646. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2647. te[0] = c * e;
  2648. te[4] = be * d - af;
  2649. te[8] = ae * d + bf;
  2650. te[1] = c * f;
  2651. te[5] = bf * d + ae;
  2652. te[9] = af * d - be;
  2653. te[2] = - d;
  2654. te[6] = b * c;
  2655. te[10] = a * c;
  2656. } else if ( euler.order === 'YZX' ) {
  2657. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2658. te[0] = c * e;
  2659. te[4] = bd - ac * f;
  2660. te[8] = bc * f + ad;
  2661. te[1] = f;
  2662. te[5] = a * e;
  2663. te[9] = - b * e;
  2664. te[2] = - d * e;
  2665. te[6] = ad * f + bc;
  2666. te[10] = ac - bd * f;
  2667. } else if ( euler.order === 'XZY' ) {
  2668. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2669. te[0] = c * e;
  2670. te[4] = - f;
  2671. te[8] = d * e;
  2672. te[1] = ac * f + bd;
  2673. te[5] = a * e;
  2674. te[9] = ad * f - bc;
  2675. te[2] = bc * f - ad;
  2676. te[6] = b * e;
  2677. te[10] = bd * f + ac;
  2678. }
  2679. // last column
  2680. te[3] = 0;
  2681. te[7] = 0;
  2682. te[11] = 0;
  2683. // bottom row
  2684. te[12] = 0;
  2685. te[13] = 0;
  2686. te[14] = 0;
  2687. te[15] = 1;
  2688. return this;
  2689. },
  2690. setRotationFromQuaternion: function ( q ) {
  2691. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2692. return this.makeRotationFromQuaternion( q );
  2693. },
  2694. makeRotationFromQuaternion: function ( q ) {
  2695. var te = this.elements;
  2696. var x = q.x, y = q.y, z = q.z, w = q.w;
  2697. var x2 = x + x, y2 = y + y, z2 = z + z;
  2698. var xx = x * x2, xy = x * y2, xz = x * z2;
  2699. var yy = y * y2, yz = y * z2, zz = z * z2;
  2700. var wx = w * x2, wy = w * y2, wz = w * z2;
  2701. te[0] = 1 - ( yy + zz );
  2702. te[4] = xy - wz;
  2703. te[8] = xz + wy;
  2704. te[1] = xy + wz;
  2705. te[5] = 1 - ( xx + zz );
  2706. te[9] = yz - wx;
  2707. te[2] = xz - wy;
  2708. te[6] = yz + wx;
  2709. te[10] = 1 - ( xx + yy );
  2710. // last column
  2711. te[3] = 0;
  2712. te[7] = 0;
  2713. te[11] = 0;
  2714. // bottom row
  2715. te[12] = 0;
  2716. te[13] = 0;
  2717. te[14] = 0;
  2718. te[15] = 1;
  2719. return this;
  2720. },
  2721. lookAt: function() {
  2722. var x = new THREE.Vector3();
  2723. var y = new THREE.Vector3();
  2724. var z = new THREE.Vector3();
  2725. return function ( eye, target, up ) {
  2726. var te = this.elements;
  2727. z.subVectors( eye, target ).normalize();
  2728. if ( z.length() === 0 ) {
  2729. z.z = 1;
  2730. }
  2731. x.crossVectors( up, z ).normalize();
  2732. if ( x.length() === 0 ) {
  2733. z.x += 0.0001;
  2734. x.crossVectors( up, z ).normalize();
  2735. }
  2736. y.crossVectors( z, x );
  2737. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2738. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2739. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2740. return this;
  2741. };
  2742. }(),
  2743. multiply: function ( m, n ) {
  2744. if ( n !== undefined ) {
  2745. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2746. return this.multiplyMatrices( m, n );
  2747. }
  2748. return this.multiplyMatrices( this, m );
  2749. },
  2750. multiplyMatrices: function ( a, b ) {
  2751. var ae = a.elements;
  2752. var be = b.elements;
  2753. var te = this.elements;
  2754. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2755. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2756. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2757. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2758. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2759. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2760. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2761. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2762. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2763. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2764. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2765. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2766. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2767. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2768. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2769. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2770. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2771. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2772. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2773. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2774. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2775. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2776. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2777. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2778. return this;
  2779. },
  2780. multiplyToArray: function ( a, b, r ) {
  2781. var te = this.elements;
  2782. this.multiplyMatrices( a, b );
  2783. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2784. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2785. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2786. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2787. return this;
  2788. },
  2789. multiplyScalar: function ( s ) {
  2790. var te = this.elements;
  2791. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2792. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2793. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2794. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2795. return this;
  2796. },
  2797. multiplyVector3: function ( vector ) {
  2798. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2799. return vector.applyProjection( this );
  2800. },
  2801. multiplyVector4: function ( vector ) {
  2802. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2803. return vector.applyMatrix4( this );
  2804. },
  2805. multiplyVector3Array: function ( a ) {
  2806. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2807. return this.applyToVector3Array( a );
  2808. },
  2809. applyToVector3Array: function() {
  2810. var v1 = new THREE.Vector3();
  2811. return function ( a ) {
  2812. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2813. v1.x = a[ i ];
  2814. v1.y = a[ i + 1 ];
  2815. v1.z = a[ i + 2 ];
  2816. v1.applyMatrix4( this );
  2817. a[ i ] = v1.x;
  2818. a[ i + 1 ] = v1.y;
  2819. a[ i + 2 ] = v1.z;
  2820. }
  2821. return a;
  2822. };
  2823. }(),
  2824. rotateAxis: function ( v ) {
  2825. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2826. v.transformDirection( this );
  2827. },
  2828. crossVector: function ( vector ) {
  2829. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2830. return vector.applyMatrix4( this );
  2831. },
  2832. determinant: function () {
  2833. var te = this.elements;
  2834. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2835. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2836. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2837. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2838. //TODO: make this more efficient
  2839. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2840. return (
  2841. n41 * (
  2842. +n14 * n23 * n32
  2843. -n13 * n24 * n32
  2844. -n14 * n22 * n33
  2845. +n12 * n24 * n33
  2846. +n13 * n22 * n34
  2847. -n12 * n23 * n34
  2848. ) +
  2849. n42 * (
  2850. +n11 * n23 * n34
  2851. -n11 * n24 * n33
  2852. +n14 * n21 * n33
  2853. -n13 * n21 * n34
  2854. +n13 * n24 * n31
  2855. -n14 * n23 * n31
  2856. ) +
  2857. n43 * (
  2858. +n11 * n24 * n32
  2859. -n11 * n22 * n34
  2860. -n14 * n21 * n32
  2861. +n12 * n21 * n34
  2862. +n14 * n22 * n31
  2863. -n12 * n24 * n31
  2864. ) +
  2865. n44 * (
  2866. -n13 * n22 * n31
  2867. -n11 * n23 * n32
  2868. +n11 * n22 * n33
  2869. +n13 * n21 * n32
  2870. -n12 * n21 * n33
  2871. +n12 * n23 * n31
  2872. )
  2873. );
  2874. },
  2875. transpose: function () {
  2876. var te = this.elements;
  2877. var tmp;
  2878. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2879. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2880. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2881. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2882. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2883. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2884. return this;
  2885. },
  2886. flattenToArray: function ( flat ) {
  2887. var te = this.elements;
  2888. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2889. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2890. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2891. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2892. return flat;
  2893. },
  2894. flattenToArrayOffset: function( flat, offset ) {
  2895. var te = this.elements;
  2896. flat[ offset ] = te[0];
  2897. flat[ offset + 1 ] = te[1];
  2898. flat[ offset + 2 ] = te[2];
  2899. flat[ offset + 3 ] = te[3];
  2900. flat[ offset + 4 ] = te[4];
  2901. flat[ offset + 5 ] = te[5];
  2902. flat[ offset + 6 ] = te[6];
  2903. flat[ offset + 7 ] = te[7];
  2904. flat[ offset + 8 ] = te[8];
  2905. flat[ offset + 9 ] = te[9];
  2906. flat[ offset + 10 ] = te[10];
  2907. flat[ offset + 11 ] = te[11];
  2908. flat[ offset + 12 ] = te[12];
  2909. flat[ offset + 13 ] = te[13];
  2910. flat[ offset + 14 ] = te[14];
  2911. flat[ offset + 15 ] = te[15];
  2912. return flat;
  2913. },
  2914. getPosition: function() {
  2915. var v1 = new THREE.Vector3();
  2916. return function () {
  2917. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2918. var te = this.elements;
  2919. return v1.set( te[12], te[13], te[14] );
  2920. };
  2921. }(),
  2922. setPosition: function ( v ) {
  2923. var te = this.elements;
  2924. te[12] = v.x;
  2925. te[13] = v.y;
  2926. te[14] = v.z;
  2927. return this;
  2928. },
  2929. getInverse: function ( m, throwOnInvertible ) {
  2930. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2931. var te = this.elements;
  2932. var me = m.elements;
  2933. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2934. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2935. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2936. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2937. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2938. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2939. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2940. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2941. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2942. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2943. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2944. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2945. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2946. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2947. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2948. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2949. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2950. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2951. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2952. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2953. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2954. if ( det == 0 ) {
  2955. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2956. if ( throwOnInvertible || false ) {
  2957. throw new Error( msg );
  2958. } else {
  2959. console.warn( msg );
  2960. }
  2961. this.identity();
  2962. return this;
  2963. }
  2964. this.multiplyScalar( 1 / det );
  2965. return this;
  2966. },
  2967. translate: function ( v ) {
  2968. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2969. },
  2970. rotateX: function ( angle ) {
  2971. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2972. },
  2973. rotateY: function ( angle ) {
  2974. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2975. },
  2976. rotateZ: function ( angle ) {
  2977. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2978. },
  2979. rotateByAxis: function ( axis, angle ) {
  2980. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2981. },
  2982. scale: function ( v ) {
  2983. var te = this.elements;
  2984. var x = v.x, y = v.y, z = v.z;
  2985. te[0] *= x; te[4] *= y; te[8] *= z;
  2986. te[1] *= x; te[5] *= y; te[9] *= z;
  2987. te[2] *= x; te[6] *= y; te[10] *= z;
  2988. te[3] *= x; te[7] *= y; te[11] *= z;
  2989. return this;
  2990. },
  2991. getMaxScaleOnAxis: function () {
  2992. var te = this.elements;
  2993. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2994. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2995. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2996. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2997. },
  2998. makeTranslation: function ( x, y, z ) {
  2999. this.set(
  3000. 1, 0, 0, x,
  3001. 0, 1, 0, y,
  3002. 0, 0, 1, z,
  3003. 0, 0, 0, 1
  3004. );
  3005. return this;
  3006. },
  3007. makeRotationX: function ( theta ) {
  3008. var c = Math.cos( theta ), s = Math.sin( theta );
  3009. this.set(
  3010. 1, 0, 0, 0,
  3011. 0, c, -s, 0,
  3012. 0, s, c, 0,
  3013. 0, 0, 0, 1
  3014. );
  3015. return this;
  3016. },
  3017. makeRotationY: function ( theta ) {
  3018. var c = Math.cos( theta ), s = Math.sin( theta );
  3019. this.set(
  3020. c, 0, s, 0,
  3021. 0, 1, 0, 0,
  3022. -s, 0, c, 0,
  3023. 0, 0, 0, 1
  3024. );
  3025. return this;
  3026. },
  3027. makeRotationZ: function ( theta ) {
  3028. var c = Math.cos( theta ), s = Math.sin( theta );
  3029. this.set(
  3030. c, -s, 0, 0,
  3031. s, c, 0, 0,
  3032. 0, 0, 1, 0,
  3033. 0, 0, 0, 1
  3034. );
  3035. return this;
  3036. },
  3037. makeRotationAxis: function ( axis, angle ) {
  3038. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3039. var c = Math.cos( angle );
  3040. var s = Math.sin( angle );
  3041. var t = 1 - c;
  3042. var x = axis.x, y = axis.y, z = axis.z;
  3043. var tx = t * x, ty = t * y;
  3044. this.set(
  3045. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3046. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3047. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3048. 0, 0, 0, 1
  3049. );
  3050. return this;
  3051. },
  3052. makeScale: function ( x, y, z ) {
  3053. this.set(
  3054. x, 0, 0, 0,
  3055. 0, y, 0, 0,
  3056. 0, 0, z, 0,
  3057. 0, 0, 0, 1
  3058. );
  3059. return this;
  3060. },
  3061. compose: function ( position, quaternion, scale ) {
  3062. this.makeRotationFromQuaternion( quaternion );
  3063. this.scale( scale );
  3064. this.setPosition( position );
  3065. return this;
  3066. },
  3067. decompose: function () {
  3068. var vector = new THREE.Vector3();
  3069. var matrix = new THREE.Matrix4();
  3070. return function ( position, quaternion, scale ) {
  3071. var te = this.elements;
  3072. var sx = vector.set( te[0], te[1], te[2] ).length();
  3073. var sy = vector.set( te[4], te[5], te[6] ).length();
  3074. var sz = vector.set( te[8], te[9], te[10] ).length();
  3075. // if determine is negative, we need to invert one scale
  3076. var det = this.determinant();
  3077. if( det < 0 ) {
  3078. sx = -sx;
  3079. }
  3080. position.x = te[12];
  3081. position.y = te[13];
  3082. position.z = te[14];
  3083. // scale the rotation part
  3084. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3085. var invSX = 1 / sx;
  3086. var invSY = 1 / sy;
  3087. var invSZ = 1 / sz;
  3088. matrix.elements[0] *= invSX;
  3089. matrix.elements[1] *= invSX;
  3090. matrix.elements[2] *= invSX;
  3091. matrix.elements[4] *= invSY;
  3092. matrix.elements[5] *= invSY;
  3093. matrix.elements[6] *= invSY;
  3094. matrix.elements[8] *= invSZ;
  3095. matrix.elements[9] *= invSZ;
  3096. matrix.elements[10] *= invSZ;
  3097. quaternion.setFromRotationMatrix( matrix );
  3098. scale.x = sx;
  3099. scale.y = sy;
  3100. scale.z = sz;
  3101. return this;
  3102. };
  3103. }(),
  3104. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3105. var te = this.elements;
  3106. var x = 2 * near / ( right - left );
  3107. var y = 2 * near / ( top - bottom );
  3108. var a = ( right + left ) / ( right - left );
  3109. var b = ( top + bottom ) / ( top - bottom );
  3110. var c = - ( far + near ) / ( far - near );
  3111. var d = - 2 * far * near / ( far - near );
  3112. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  3113. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  3114. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  3115. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  3116. return this;
  3117. },
  3118. makePerspective: function ( fov, aspect, near, far ) {
  3119. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3120. var ymin = - ymax;
  3121. var xmin = ymin * aspect;
  3122. var xmax = ymax * aspect;
  3123. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3124. },
  3125. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3126. var te = this.elements;
  3127. var w = right - left;
  3128. var h = top - bottom;
  3129. var p = far - near;
  3130. var x = ( right + left ) / w;
  3131. var y = ( top + bottom ) / h;
  3132. var z = ( far + near ) / p;
  3133. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  3134. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  3135. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  3136. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  3137. return this;
  3138. },
  3139. fromArray: function ( array ) {
  3140. this.elements.set( array );
  3141. return this;
  3142. },
  3143. toArray: function () {
  3144. var te = this.elements;
  3145. return [
  3146. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3147. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3148. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3149. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3150. ];
  3151. },
  3152. clone: function () {
  3153. var te = this.elements;
  3154. return new THREE.Matrix4(
  3155. te[0], te[4], te[8], te[12],
  3156. te[1], te[5], te[9], te[13],
  3157. te[2], te[6], te[10], te[14],
  3158. te[3], te[7], te[11], te[15]
  3159. );
  3160. }
  3161. };
  3162. /**
  3163. * @author bhouston / http://exocortex.com
  3164. */
  3165. THREE.Ray = function ( origin, direction ) {
  3166. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3167. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3168. };
  3169. THREE.Ray.prototype = {
  3170. constructor: THREE.Ray,
  3171. set: function ( origin, direction ) {
  3172. this.origin.copy( origin );
  3173. this.direction.copy( direction );
  3174. return this;
  3175. },
  3176. copy: function ( ray ) {
  3177. this.origin.copy( ray.origin );
  3178. this.direction.copy( ray.direction );
  3179. return this;
  3180. },
  3181. at: function ( t, optionalTarget ) {
  3182. var result = optionalTarget || new THREE.Vector3();
  3183. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3184. },
  3185. recast: function () {
  3186. var v1 = new THREE.Vector3();
  3187. return function ( t ) {
  3188. this.origin.copy( this.at( t, v1 ) );
  3189. return this;
  3190. };
  3191. }(),
  3192. closestPointToPoint: function ( point, optionalTarget ) {
  3193. var result = optionalTarget || new THREE.Vector3();
  3194. result.subVectors( point, this.origin );
  3195. var directionDistance = result.dot( this.direction );
  3196. if ( directionDistance < 0 ) {
  3197. return result.copy( this.origin );
  3198. }
  3199. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3200. },
  3201. distanceToPoint: function () {
  3202. var v1 = new THREE.Vector3();
  3203. return function ( point ) {
  3204. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3205. // point behind the ray
  3206. if ( directionDistance < 0 ) {
  3207. return this.origin.distanceTo( point );
  3208. }
  3209. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3210. return v1.distanceTo( point );
  3211. };
  3212. }(),
  3213. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3214. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3215. // It returns the min distance between the ray and the segment
  3216. // defined by v0 and v1
  3217. // It can also set two optional targets :
  3218. // - The closest point on the ray
  3219. // - The closest point on the segment
  3220. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3221. var segDir = v1.clone().sub( v0 ).normalize();
  3222. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3223. var diff = this.origin.clone().sub( segCenter );
  3224. var a01 = - this.direction.dot( segDir );
  3225. var b0 = diff.dot( this.direction );
  3226. var b1 = - diff.dot( segDir );
  3227. var c = diff.lengthSq();
  3228. var det = Math.abs( 1 - a01 * a01 );
  3229. var s0, s1, sqrDist, extDet;
  3230. if ( det >= 0 ) {
  3231. // The ray and segment are not parallel.
  3232. s0 = a01 * b1 - b0;
  3233. s1 = a01 * b0 - b1;
  3234. extDet = segExtent * det;
  3235. if ( s0 >= 0 ) {
  3236. if ( s1 >= - extDet ) {
  3237. if ( s1 <= extDet ) {
  3238. // region 0
  3239. // Minimum at interior points of ray and segment.
  3240. var invDet = 1 / det;
  3241. s0 *= invDet;
  3242. s1 *= invDet;
  3243. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3244. } else {
  3245. // region 1
  3246. s1 = segExtent;
  3247. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3248. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3249. }
  3250. } else {
  3251. // region 5
  3252. s1 = - segExtent;
  3253. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3254. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3255. }
  3256. } else {
  3257. if ( s1 <= - extDet) {
  3258. // region 4
  3259. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3260. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3261. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3262. } else if ( s1 <= extDet ) {
  3263. // region 3
  3264. s0 = 0;
  3265. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3266. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3267. } else {
  3268. // region 2
  3269. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3270. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3271. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3272. }
  3273. }
  3274. } else {
  3275. // Ray and segment are parallel.
  3276. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3277. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3278. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3279. }
  3280. if ( optionalPointOnRay ) {
  3281. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3282. }
  3283. if ( optionalPointOnSegment ) {
  3284. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3285. }
  3286. return sqrDist;
  3287. },
  3288. isIntersectionSphere: function ( sphere ) {
  3289. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3290. },
  3291. isIntersectionPlane: function ( plane ) {
  3292. // check if the ray lies on the plane first
  3293. var distToPoint = plane.distanceToPoint( this.origin );
  3294. if ( distToPoint === 0 ) {
  3295. return true;
  3296. }
  3297. var denominator = plane.normal.dot( this.direction );
  3298. if ( denominator * distToPoint < 0 ) {
  3299. return true
  3300. }
  3301. // ray origin is behind the plane (and is pointing behind it)
  3302. return false;
  3303. },
  3304. distanceToPlane: function ( plane ) {
  3305. var denominator = plane.normal.dot( this.direction );
  3306. if ( denominator == 0 ) {
  3307. // line is coplanar, return origin
  3308. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3309. return 0;
  3310. }
  3311. // Null is preferable to undefined since undefined means.... it is undefined
  3312. return null;
  3313. }
  3314. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3315. // Return if the ray never intersects the plane
  3316. return t >= 0 ? t : null;
  3317. },
  3318. intersectPlane: function ( plane, optionalTarget ) {
  3319. var t = this.distanceToPlane( plane );
  3320. if ( t === null ) {
  3321. return null;
  3322. }
  3323. return this.at( t, optionalTarget );
  3324. },
  3325. isIntersectionBox: function () {
  3326. var v = new THREE.Vector3();
  3327. return function ( box ) {
  3328. return this.intersectBox( box, v ) !== null;
  3329. }
  3330. }(),
  3331. intersectBox: function ( box , optionalTarget ) {
  3332. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3333. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3334. var invdirx = 1/this.direction.x,
  3335. invdiry = 1/this.direction.y,
  3336. invdirz = 1/this.direction.z;
  3337. var origin = this.origin;
  3338. if (invdirx >= 0) {
  3339. tmin = (box.min.x - origin.x) * invdirx;
  3340. tmax = (box.max.x - origin.x) * invdirx;
  3341. } else {
  3342. tmin = (box.max.x - origin.x) * invdirx;
  3343. tmax = (box.min.x - origin.x) * invdirx;
  3344. }
  3345. if (invdiry >= 0) {
  3346. tymin = (box.min.y - origin.y) * invdiry;
  3347. tymax = (box.max.y - origin.y) * invdiry;
  3348. } else {
  3349. tymin = (box.max.y - origin.y) * invdiry;
  3350. tymax = (box.min.y - origin.y) * invdiry;
  3351. }
  3352. if ((tmin > tymax) || (tymin > tmax)) return null;
  3353. // These lines also handle the case where tmin or tmax is NaN
  3354. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3355. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3356. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3357. if (invdirz >= 0) {
  3358. tzmin = (box.min.z - origin.z) * invdirz;
  3359. tzmax = (box.max.z - origin.z) * invdirz;
  3360. } else {
  3361. tzmin = (box.max.z - origin.z) * invdirz;
  3362. tzmax = (box.min.z - origin.z) * invdirz;
  3363. }
  3364. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3365. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3366. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3367. //return point closest to the ray (positive side)
  3368. if ( tmax < 0 ) return null;
  3369. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3370. },
  3371. intersectTriangle: function() {
  3372. // Compute the offset origin, edges, and normal.
  3373. var diff = new THREE.Vector3();
  3374. var edge1 = new THREE.Vector3();
  3375. var edge2 = new THREE.Vector3();
  3376. var normal = new THREE.Vector3();
  3377. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3378. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3379. edge1.subVectors( b, a );
  3380. edge2.subVectors( c, a );
  3381. normal.crossVectors( edge1, edge2 );
  3382. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3383. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3384. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3385. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3386. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3387. var DdN = this.direction.dot( normal );
  3388. var sign;
  3389. if ( DdN > 0 ) {
  3390. if ( backfaceCulling ) return null;
  3391. sign = 1;
  3392. } else if ( DdN < 0 ) {
  3393. sign = - 1;
  3394. DdN = - DdN;
  3395. } else {
  3396. return null;
  3397. }
  3398. diff.subVectors( this.origin, a );
  3399. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3400. // b1 < 0, no intersection
  3401. if ( DdQxE2 < 0 ) {
  3402. return null;
  3403. }
  3404. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3405. // b2 < 0, no intersection
  3406. if ( DdE1xQ < 0 ) {
  3407. return null;
  3408. }
  3409. // b1+b2 > 1, no intersection
  3410. if ( DdQxE2 + DdE1xQ > DdN ) {
  3411. return null;
  3412. }
  3413. // Line intersects triangle, check if ray does.
  3414. var QdN = - sign * diff.dot( normal );
  3415. // t < 0, no intersection
  3416. if ( QdN < 0 ) {
  3417. return null;
  3418. }
  3419. // Ray intersects triangle.
  3420. return this.at( QdN / DdN, optionalTarget );
  3421. }
  3422. }(),
  3423. applyMatrix4: function ( matrix4 ) {
  3424. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3425. this.origin.applyMatrix4( matrix4 );
  3426. this.direction.sub( this.origin );
  3427. this.direction.normalize();
  3428. return this;
  3429. },
  3430. equals: function ( ray ) {
  3431. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3432. },
  3433. clone: function () {
  3434. return new THREE.Ray().copy( this );
  3435. }
  3436. };
  3437. /**
  3438. * @author bhouston / http://exocortex.com
  3439. * @author mrdoob / http://mrdoob.com/
  3440. */
  3441. THREE.Sphere = function ( center, radius ) {
  3442. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3443. this.radius = ( radius !== undefined ) ? radius : 0;
  3444. };
  3445. THREE.Sphere.prototype = {
  3446. constructor: THREE.Sphere,
  3447. set: function ( center, radius ) {
  3448. this.center.copy( center );
  3449. this.radius = radius;
  3450. return this;
  3451. },
  3452. setFromPoints: function () {
  3453. var box = new THREE.Box3();
  3454. return function ( points, optionalCenter ) {
  3455. var center = this.center;
  3456. if ( optionalCenter !== undefined ) {
  3457. center.copy( optionalCenter );
  3458. } else {
  3459. box.setFromPoints( points ).center( center );
  3460. }
  3461. var maxRadiusSq = 0;
  3462. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3463. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3464. }
  3465. this.radius = Math.sqrt( maxRadiusSq );
  3466. return this;
  3467. };
  3468. }(),
  3469. copy: function ( sphere ) {
  3470. this.center.copy( sphere.center );
  3471. this.radius = sphere.radius;
  3472. return this;
  3473. },
  3474. empty: function () {
  3475. return ( this.radius <= 0 );
  3476. },
  3477. containsPoint: function ( point ) {
  3478. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3479. },
  3480. distanceToPoint: function ( point ) {
  3481. return ( point.distanceTo( this.center ) - this.radius );
  3482. },
  3483. intersectsSphere: function ( sphere ) {
  3484. var radiusSum = this.radius + sphere.radius;
  3485. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3486. },
  3487. clampPoint: function ( point, optionalTarget ) {
  3488. var deltaLengthSq = this.center.distanceToSquared( point );
  3489. var result = optionalTarget || new THREE.Vector3();
  3490. result.copy( point );
  3491. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3492. result.sub( this.center ).normalize();
  3493. result.multiplyScalar( this.radius ).add( this.center );
  3494. }
  3495. return result;
  3496. },
  3497. getBoundingBox: function ( optionalTarget ) {
  3498. var box = optionalTarget || new THREE.Box3();
  3499. box.set( this.center, this.center );
  3500. box.expandByScalar( this.radius );
  3501. return box;
  3502. },
  3503. applyMatrix4: function ( matrix ) {
  3504. this.center.applyMatrix4( matrix );
  3505. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3506. return this;
  3507. },
  3508. translate: function ( offset ) {
  3509. this.center.add( offset );
  3510. return this;
  3511. },
  3512. equals: function ( sphere ) {
  3513. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3514. },
  3515. clone: function () {
  3516. return new THREE.Sphere().copy( this );
  3517. }
  3518. };
  3519. /**
  3520. * @author mrdoob / http://mrdoob.com/
  3521. * @author alteredq / http://alteredqualia.com/
  3522. * @author bhouston / http://exocortex.com
  3523. */
  3524. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3525. this.planes = [
  3526. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3527. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3528. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3529. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3530. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3531. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3532. ];
  3533. };
  3534. THREE.Frustum.prototype = {
  3535. constructor: THREE.Frustum,
  3536. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3537. var planes = this.planes;
  3538. planes[0].copy( p0 );
  3539. planes[1].copy( p1 );
  3540. planes[2].copy( p2 );
  3541. planes[3].copy( p3 );
  3542. planes[4].copy( p4 );
  3543. planes[5].copy( p5 );
  3544. return this;
  3545. },
  3546. copy: function ( frustum ) {
  3547. var planes = this.planes;
  3548. for( var i = 0; i < 6; i ++ ) {
  3549. planes[i].copy( frustum.planes[i] );
  3550. }
  3551. return this;
  3552. },
  3553. setFromMatrix: function ( m ) {
  3554. var planes = this.planes;
  3555. var me = m.elements;
  3556. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3557. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3558. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3559. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3560. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3561. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3562. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3563. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3564. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3565. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3566. return this;
  3567. },
  3568. intersectsObject: function () {
  3569. var sphere = new THREE.Sphere();
  3570. return function ( object ) {
  3571. var geometry = object.geometry;
  3572. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3573. sphere.copy( geometry.boundingSphere );
  3574. sphere.applyMatrix4( object.matrixWorld );
  3575. return this.intersectsSphere( sphere );
  3576. };
  3577. }(),
  3578. intersectsSphere: function ( sphere ) {
  3579. var planes = this.planes;
  3580. var center = sphere.center;
  3581. var negRadius = -sphere.radius;
  3582. for ( var i = 0; i < 6; i ++ ) {
  3583. var distance = planes[ i ].distanceToPoint( center );
  3584. if ( distance < negRadius ) {
  3585. return false;
  3586. }
  3587. }
  3588. return true;
  3589. },
  3590. intersectsBox : function() {
  3591. var p1 = new THREE.Vector3(),
  3592. p2 = new THREE.Vector3();
  3593. return function( box ) {
  3594. var planes = this.planes;
  3595. for ( var i = 0; i < 6 ; i ++ ) {
  3596. var plane = planes[i];
  3597. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3598. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3599. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3600. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3601. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3602. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3603. var d1 = plane.distanceToPoint( p1 );
  3604. var d2 = plane.distanceToPoint( p2 );
  3605. // if both outside plane, no intersection
  3606. if ( d1 < 0 && d2 < 0 ) {
  3607. return false;
  3608. }
  3609. }
  3610. return true;
  3611. };
  3612. }(),
  3613. containsPoint: function ( point ) {
  3614. var planes = this.planes;
  3615. for ( var i = 0; i < 6; i ++ ) {
  3616. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3617. return false;
  3618. }
  3619. }
  3620. return true;
  3621. },
  3622. clone: function () {
  3623. return new THREE.Frustum().copy( this );
  3624. }
  3625. };
  3626. /**
  3627. * @author bhouston / http://exocortex.com
  3628. */
  3629. THREE.Plane = function ( normal, constant ) {
  3630. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3631. this.constant = ( constant !== undefined ) ? constant : 0;
  3632. };
  3633. THREE.Plane.prototype = {
  3634. constructor: THREE.Plane,
  3635. set: function ( normal, constant ) {
  3636. this.normal.copy( normal );
  3637. this.constant = constant;
  3638. return this;
  3639. },
  3640. setComponents: function ( x, y, z, w ) {
  3641. this.normal.set( x, y, z );
  3642. this.constant = w;
  3643. return this;
  3644. },
  3645. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3646. this.normal.copy( normal );
  3647. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3648. return this;
  3649. },
  3650. setFromCoplanarPoints: function() {
  3651. var v1 = new THREE.Vector3();
  3652. var v2 = new THREE.Vector3();
  3653. return function ( a, b, c ) {
  3654. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3655. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3656. this.setFromNormalAndCoplanarPoint( normal, a );
  3657. return this;
  3658. };
  3659. }(),
  3660. copy: function ( plane ) {
  3661. this.normal.copy( plane.normal );
  3662. this.constant = plane.constant;
  3663. return this;
  3664. },
  3665. normalize: function () {
  3666. // Note: will lead to a divide by zero if the plane is invalid.
  3667. var inverseNormalLength = 1.0 / this.normal.length();
  3668. this.normal.multiplyScalar( inverseNormalLength );
  3669. this.constant *= inverseNormalLength;
  3670. return this;
  3671. },
  3672. negate: function () {
  3673. this.constant *= -1;
  3674. this.normal.negate();
  3675. return this;
  3676. },
  3677. distanceToPoint: function ( point ) {
  3678. return this.normal.dot( point ) + this.constant;
  3679. },
  3680. distanceToSphere: function ( sphere ) {
  3681. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3682. },
  3683. projectPoint: function ( point, optionalTarget ) {
  3684. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3685. },
  3686. orthoPoint: function ( point, optionalTarget ) {
  3687. var perpendicularMagnitude = this.distanceToPoint( point );
  3688. var result = optionalTarget || new THREE.Vector3();
  3689. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3690. },
  3691. isIntersectionLine: function ( line ) {
  3692. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3693. var startSign = this.distanceToPoint( line.start );
  3694. var endSign = this.distanceToPoint( line.end );
  3695. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3696. },
  3697. intersectLine: function() {
  3698. var v1 = new THREE.Vector3();
  3699. return function ( line, optionalTarget ) {
  3700. var result = optionalTarget || new THREE.Vector3();
  3701. var direction = line.delta( v1 );
  3702. var denominator = this.normal.dot( direction );
  3703. if ( denominator == 0 ) {
  3704. // line is coplanar, return origin
  3705. if( this.distanceToPoint( line.start ) == 0 ) {
  3706. return result.copy( line.start );
  3707. }
  3708. // Unsure if this is the correct method to handle this case.
  3709. return undefined;
  3710. }
  3711. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3712. if( t < 0 || t > 1 ) {
  3713. return undefined;
  3714. }
  3715. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3716. };
  3717. }(),
  3718. coplanarPoint: function ( optionalTarget ) {
  3719. var result = optionalTarget || new THREE.Vector3();
  3720. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3721. },
  3722. applyMatrix4: function() {
  3723. var v1 = new THREE.Vector3();
  3724. var v2 = new THREE.Vector3();
  3725. var m1 = new THREE.Matrix3();
  3726. return function ( matrix, optionalNormalMatrix ) {
  3727. // compute new normal based on theory here:
  3728. // http://www.songho.ca/opengl/gl_normaltransform.html
  3729. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3730. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3731. var newCoplanarPoint = this.coplanarPoint( v2 );
  3732. newCoplanarPoint.applyMatrix4( matrix );
  3733. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3734. return this;
  3735. };
  3736. }(),
  3737. translate: function ( offset ) {
  3738. this.constant = this.constant - offset.dot( this.normal );
  3739. return this;
  3740. },
  3741. equals: function ( plane ) {
  3742. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3743. },
  3744. clone: function () {
  3745. return new THREE.Plane().copy( this );
  3746. }
  3747. };
  3748. /**
  3749. * @author alteredq / http://alteredqualia.com/
  3750. * @author mrdoob / http://mrdoob.com/
  3751. */
  3752. THREE.Math = {
  3753. generateUUID: function () {
  3754. // http://www.broofa.com/Tools/Math.uuid.htm
  3755. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3756. var uuid = new Array(36);
  3757. var rnd = 0, r;
  3758. return function () {
  3759. for ( var i = 0; i < 36; i ++ ) {
  3760. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3761. uuid[ i ] = '-';
  3762. } else if ( i == 14 ) {
  3763. uuid[ i ] = '4';
  3764. } else {
  3765. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3766. r = rnd & 0xf;
  3767. rnd = rnd >> 4;
  3768. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3769. }
  3770. }
  3771. return uuid.join('');
  3772. };
  3773. }(),
  3774. // Clamp value to range <a, b>
  3775. clamp: function ( x, a, b ) {
  3776. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3777. },
  3778. // Clamp value to range <a, inf)
  3779. clampBottom: function ( x, a ) {
  3780. return x < a ? a : x;
  3781. },
  3782. // Linear mapping from range <a1, a2> to range <b1, b2>
  3783. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3784. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3785. },
  3786. // http://en.wikipedia.org/wiki/Smoothstep
  3787. smoothstep: function ( x, min, max ) {
  3788. if ( x <= min ) return 0;
  3789. if ( x >= max ) return 1;
  3790. x = ( x - min )/( max - min );
  3791. return x*x*(3 - 2*x);
  3792. },
  3793. smootherstep: function ( x, min, max ) {
  3794. if ( x <= min ) return 0;
  3795. if ( x >= max ) return 1;
  3796. x = ( x - min )/( max - min );
  3797. return x*x*x*(x*(x*6 - 15) + 10);
  3798. },
  3799. // Random float from <0, 1> with 16 bits of randomness
  3800. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3801. random16: function () {
  3802. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3803. },
  3804. // Random integer from <low, high> interval
  3805. randInt: function ( low, high ) {
  3806. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3807. },
  3808. // Random float from <low, high> interval
  3809. randFloat: function ( low, high ) {
  3810. return low + Math.random() * ( high - low );
  3811. },
  3812. // Random float from <-range/2, range/2> interval
  3813. randFloatSpread: function ( range ) {
  3814. return range * ( 0.5 - Math.random() );
  3815. },
  3816. sign: function ( x ) {
  3817. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3818. },
  3819. degToRad: function() {
  3820. var degreeToRadiansFactor = Math.PI / 180;
  3821. return function ( degrees ) {
  3822. return degrees * degreeToRadiansFactor;
  3823. };
  3824. }(),
  3825. radToDeg: function() {
  3826. var radianToDegreesFactor = 180 / Math.PI;
  3827. return function ( radians ) {
  3828. return radians * radianToDegreesFactor;
  3829. };
  3830. }(),
  3831. isPowerOfTwo: function ( value ) {
  3832. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3833. }
  3834. };
  3835. /**
  3836. * Spline from Tween.js, slightly optimized (and trashed)
  3837. * http://sole.github.com/tween.js/examples/05_spline.html
  3838. *
  3839. * @author mrdoob / http://mrdoob.com/
  3840. * @author alteredq / http://alteredqualia.com/
  3841. */
  3842. THREE.Spline = function ( points ) {
  3843. this.points = points;
  3844. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3845. point, intPoint, weight, w2, w3,
  3846. pa, pb, pc, pd;
  3847. this.initFromArray = function( a ) {
  3848. this.points = [];
  3849. for ( var i = 0; i < a.length; i++ ) {
  3850. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3851. }
  3852. };
  3853. this.getPoint = function ( k ) {
  3854. point = ( this.points.length - 1 ) * k;
  3855. intPoint = Math.floor( point );
  3856. weight = point - intPoint;
  3857. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3858. c[ 1 ] = intPoint;
  3859. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3860. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3861. pa = this.points[ c[ 0 ] ];
  3862. pb = this.points[ c[ 1 ] ];
  3863. pc = this.points[ c[ 2 ] ];
  3864. pd = this.points[ c[ 3 ] ];
  3865. w2 = weight * weight;
  3866. w3 = weight * w2;
  3867. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3868. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3869. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3870. return v3;
  3871. };
  3872. this.getControlPointsArray = function () {
  3873. var i, p, l = this.points.length,
  3874. coords = [];
  3875. for ( i = 0; i < l; i ++ ) {
  3876. p = this.points[ i ];
  3877. coords[ i ] = [ p.x, p.y, p.z ];
  3878. }
  3879. return coords;
  3880. };
  3881. // approximate length by summing linear segments
  3882. this.getLength = function ( nSubDivisions ) {
  3883. var i, index, nSamples, position,
  3884. point = 0, intPoint = 0, oldIntPoint = 0,
  3885. oldPosition = new THREE.Vector3(),
  3886. tmpVec = new THREE.Vector3(),
  3887. chunkLengths = [],
  3888. totalLength = 0;
  3889. // first point has 0 length
  3890. chunkLengths[ 0 ] = 0;
  3891. if ( !nSubDivisions ) nSubDivisions = 100;
  3892. nSamples = this.points.length * nSubDivisions;
  3893. oldPosition.copy( this.points[ 0 ] );
  3894. for ( i = 1; i < nSamples; i ++ ) {
  3895. index = i / nSamples;
  3896. position = this.getPoint( index );
  3897. tmpVec.copy( position );
  3898. totalLength += tmpVec.distanceTo( oldPosition );
  3899. oldPosition.copy( position );
  3900. point = ( this.points.length - 1 ) * index;
  3901. intPoint = Math.floor( point );
  3902. if ( intPoint != oldIntPoint ) {
  3903. chunkLengths[ intPoint ] = totalLength;
  3904. oldIntPoint = intPoint;
  3905. }
  3906. }
  3907. // last point ends with total length
  3908. chunkLengths[ chunkLengths.length ] = totalLength;
  3909. return { chunks: chunkLengths, total: totalLength };
  3910. };
  3911. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3912. var i, j,
  3913. index, indexCurrent, indexNext,
  3914. linearDistance, realDistance,
  3915. sampling, position,
  3916. newpoints = [],
  3917. tmpVec = new THREE.Vector3(),
  3918. sl = this.getLength();
  3919. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3920. for ( i = 1; i < this.points.length; i++ ) {
  3921. //tmpVec.copy( this.points[ i - 1 ] );
  3922. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3923. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3924. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3925. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3926. indexNext = i / ( this.points.length - 1 );
  3927. for ( j = 1; j < sampling - 1; j++ ) {
  3928. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3929. position = this.getPoint( index );
  3930. newpoints.push( tmpVec.copy( position ).clone() );
  3931. }
  3932. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3933. }
  3934. this.points = newpoints;
  3935. };
  3936. // Catmull-Rom
  3937. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3938. var v0 = ( p2 - p0 ) * 0.5,
  3939. v1 = ( p3 - p1 ) * 0.5;
  3940. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3941. };
  3942. };
  3943. /**
  3944. * @author bhouston / http://exocortex.com
  3945. * @author mrdoob / http://mrdoob.com/
  3946. */
  3947. THREE.Triangle = function ( a, b, c ) {
  3948. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3949. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3950. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3951. };
  3952. THREE.Triangle.normal = function() {
  3953. var v0 = new THREE.Vector3();
  3954. return function ( a, b, c, optionalTarget ) {
  3955. var result = optionalTarget || new THREE.Vector3();
  3956. result.subVectors( c, b );
  3957. v0.subVectors( a, b );
  3958. result.cross( v0 );
  3959. var resultLengthSq = result.lengthSq();
  3960. if( resultLengthSq > 0 ) {
  3961. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3962. }
  3963. return result.set( 0, 0, 0 );
  3964. };
  3965. }();
  3966. // static/instance method to calculate barycoordinates
  3967. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3968. THREE.Triangle.barycoordFromPoint = function() {
  3969. var v0 = new THREE.Vector3();
  3970. var v1 = new THREE.Vector3();
  3971. var v2 = new THREE.Vector3();
  3972. return function ( point, a, b, c, optionalTarget ) {
  3973. v0.subVectors( c, a );
  3974. v1.subVectors( b, a );
  3975. v2.subVectors( point, a );
  3976. var dot00 = v0.dot( v0 );
  3977. var dot01 = v0.dot( v1 );
  3978. var dot02 = v0.dot( v2 );
  3979. var dot11 = v1.dot( v1 );
  3980. var dot12 = v1.dot( v2 );
  3981. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3982. var result = optionalTarget || new THREE.Vector3();
  3983. // colinear or singular triangle
  3984. if( denom == 0 ) {
  3985. // arbitrary location outside of triangle?
  3986. // not sure if this is the best idea, maybe should be returning undefined
  3987. return result.set( -2, -1, -1 );
  3988. }
  3989. var invDenom = 1 / denom;
  3990. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3991. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3992. // barycoordinates must always sum to 1
  3993. return result.set( 1 - u - v, v, u );
  3994. };
  3995. }();
  3996. THREE.Triangle.containsPoint = function() {
  3997. var v1 = new THREE.Vector3();
  3998. return function ( point, a, b, c ) {
  3999. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4000. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4001. };
  4002. }();
  4003. THREE.Triangle.prototype = {
  4004. constructor: THREE.Triangle,
  4005. set: function ( a, b, c ) {
  4006. this.a.copy( a );
  4007. this.b.copy( b );
  4008. this.c.copy( c );
  4009. return this;
  4010. },
  4011. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4012. this.a.copy( points[i0] );
  4013. this.b.copy( points[i1] );
  4014. this.c.copy( points[i2] );
  4015. return this;
  4016. },
  4017. copy: function ( triangle ) {
  4018. this.a.copy( triangle.a );
  4019. this.b.copy( triangle.b );
  4020. this.c.copy( triangle.c );
  4021. return this;
  4022. },
  4023. area: function() {
  4024. var v0 = new THREE.Vector3();
  4025. var v1 = new THREE.Vector3();
  4026. return function () {
  4027. v0.subVectors( this.c, this.b );
  4028. v1.subVectors( this.a, this.b );
  4029. return v0.cross( v1 ).length() * 0.5;
  4030. };
  4031. }(),
  4032. midpoint: function ( optionalTarget ) {
  4033. var result = optionalTarget || new THREE.Vector3();
  4034. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4035. },
  4036. normal: function ( optionalTarget ) {
  4037. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4038. },
  4039. plane: function ( optionalTarget ) {
  4040. var result = optionalTarget || new THREE.Plane();
  4041. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4042. },
  4043. barycoordFromPoint: function ( point, optionalTarget ) {
  4044. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4045. },
  4046. containsPoint: function ( point ) {
  4047. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4048. },
  4049. equals: function ( triangle ) {
  4050. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4051. },
  4052. clone: function () {
  4053. return new THREE.Triangle().copy( this );
  4054. }
  4055. };
  4056. /**
  4057. * @author mrdoob / http://mrdoob.com/
  4058. */
  4059. THREE.Vertex = function ( v ) {
  4060. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  4061. return v;
  4062. };
  4063. /**
  4064. * @author mrdoob / http://mrdoob.com/
  4065. */
  4066. THREE.UV = function ( u, v ) {
  4067. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  4068. return new THREE.Vector2( u, v );
  4069. };
  4070. /**
  4071. * @author alteredq / http://alteredqualia.com/
  4072. */
  4073. THREE.Clock = function ( autoStart ) {
  4074. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4075. this.startTime = 0;
  4076. this.oldTime = 0;
  4077. this.elapsedTime = 0;
  4078. this.running = false;
  4079. };
  4080. THREE.Clock.prototype = {
  4081. constructor: THREE.Clock,
  4082. start: function () {
  4083. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4084. ? self.performance.now()
  4085. : Date.now();
  4086. this.oldTime = this.startTime;
  4087. this.running = true;
  4088. },
  4089. stop: function () {
  4090. this.getElapsedTime();
  4091. this.running = false;
  4092. },
  4093. getElapsedTime: function () {
  4094. this.getDelta();
  4095. return this.elapsedTime;
  4096. },
  4097. getDelta: function () {
  4098. var diff = 0;
  4099. if ( this.autoStart && ! this.running ) {
  4100. this.start();
  4101. }
  4102. if ( this.running ) {
  4103. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4104. ? self.performance.now()
  4105. : Date.now();
  4106. diff = 0.001 * ( newTime - this.oldTime );
  4107. this.oldTime = newTime;
  4108. this.elapsedTime += diff;
  4109. }
  4110. return diff;
  4111. }
  4112. };
  4113. /**
  4114. * https://github.com/mrdoob/eventdispatcher.js/
  4115. */
  4116. THREE.EventDispatcher = function () {}
  4117. THREE.EventDispatcher.prototype = {
  4118. constructor: THREE.EventDispatcher,
  4119. apply: function ( object ) {
  4120. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4121. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4122. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4123. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4124. },
  4125. addEventListener: function ( type, listener ) {
  4126. if ( this._listeners === undefined ) this._listeners = {};
  4127. var listeners = this._listeners;
  4128. if ( listeners[ type ] === undefined ) {
  4129. listeners[ type ] = [];
  4130. }
  4131. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4132. listeners[ type ].push( listener );
  4133. }
  4134. },
  4135. hasEventListener: function ( type, listener ) {
  4136. if ( this._listeners === undefined ) return false;
  4137. var listeners = this._listeners;
  4138. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4139. return true;
  4140. }
  4141. return false;
  4142. },
  4143. removeEventListener: function ( type, listener ) {
  4144. if ( this._listeners === undefined ) return;
  4145. var listeners = this._listeners;
  4146. var listenerArray = listeners[ type ];
  4147. if ( listenerArray !== undefined ) {
  4148. var index = listenerArray.indexOf( listener );
  4149. if ( index !== - 1 ) {
  4150. listenerArray.splice( index, 1 );
  4151. }
  4152. }
  4153. },
  4154. dispatchEvent: function ( event ) {
  4155. if ( this._listeners === undefined ) return;
  4156. var listeners = this._listeners;
  4157. var listenerArray = listeners[ event.type ];
  4158. if ( listenerArray !== undefined ) {
  4159. event.target = this;
  4160. var array = [];
  4161. var length = listenerArray.length;
  4162. for ( var i = 0; i < length; i ++ ) {
  4163. array[ i ] = listenerArray[ i ];
  4164. }
  4165. for ( var i = 0; i < length; i ++ ) {
  4166. array[ i ].call( this, event );
  4167. }
  4168. }
  4169. }
  4170. };
  4171. /**
  4172. * @author mrdoob / http://mrdoob.com/
  4173. * @author bhouston / http://exocortex.com/
  4174. * @author stephomi / http://stephaneginier.com/
  4175. */
  4176. ( function ( THREE ) {
  4177. THREE.Raycaster = function ( origin, direction, near, far ) {
  4178. this.ray = new THREE.Ray( origin, direction );
  4179. // direction is assumed to be normalized (for accurate distance calculations)
  4180. this.near = near || 0;
  4181. this.far = far || Infinity;
  4182. };
  4183. var sphere = new THREE.Sphere();
  4184. var localRay = new THREE.Ray();
  4185. var facePlane = new THREE.Plane();
  4186. var intersectPoint = new THREE.Vector3();
  4187. var matrixPosition = new THREE.Vector3();
  4188. var inverseMatrix = new THREE.Matrix4();
  4189. var descSort = function ( a, b ) {
  4190. return a.distance - b.distance;
  4191. };
  4192. var vA = new THREE.Vector3();
  4193. var vB = new THREE.Vector3();
  4194. var vC = new THREE.Vector3();
  4195. var intersectObject = function ( object, raycaster, intersects ) {
  4196. if ( object instanceof THREE.Sprite ) {
  4197. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4198. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4199. if ( distance > object.scale.x ) {
  4200. return intersects;
  4201. }
  4202. intersects.push( {
  4203. distance: distance,
  4204. point: object.position,
  4205. face: null,
  4206. object: object
  4207. } );
  4208. } else if ( object instanceof THREE.LOD ) {
  4209. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4210. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4211. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4212. } else if ( object instanceof THREE.Mesh ) {
  4213. var geometry = object.geometry;
  4214. // Checking boundingSphere distance to ray
  4215. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4216. sphere.copy( geometry.boundingSphere );
  4217. sphere.applyMatrix4( object.matrixWorld );
  4218. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4219. return intersects;
  4220. }
  4221. // Check boundingBox before continuing
  4222. inverseMatrix.getInverse( object.matrixWorld );
  4223. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4224. if ( geometry.boundingBox !== null ) {
  4225. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4226. return intersects;
  4227. }
  4228. }
  4229. if ( geometry instanceof THREE.BufferGeometry ) {
  4230. var material = object.material;
  4231. if ( material === undefined ) return intersects;
  4232. var attributes = geometry.attributes;
  4233. var a, b, c;
  4234. var precision = raycaster.precision;
  4235. if ( attributes.index !== undefined ) {
  4236. var offsets = geometry.offsets;
  4237. var indices = attributes.index.array;
  4238. var positions = attributes.position.array;
  4239. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  4240. var start = offsets[ oi ].start;
  4241. var count = offsets[ oi ].count;
  4242. var index = offsets[ oi ].index;
  4243. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4244. a = index + indices[ i ];
  4245. b = index + indices[ i + 1 ];
  4246. c = index + indices[ i + 2 ];
  4247. vA.set(
  4248. positions[ a * 3 ],
  4249. positions[ a * 3 + 1 ],
  4250. positions[ a * 3 + 2 ]
  4251. );
  4252. vB.set(
  4253. positions[ b * 3 ],
  4254. positions[ b * 3 + 1 ],
  4255. positions[ b * 3 + 2 ]
  4256. );
  4257. vC.set(
  4258. positions[ c * 3 ],
  4259. positions[ c * 3 + 1 ],
  4260. positions[ c * 3 + 2 ]
  4261. );
  4262. if ( material.side === THREE.BackSide ) {
  4263. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4264. } else {
  4265. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4266. }
  4267. if ( intersectionPoint === null ) continue;
  4268. intersectionPoint.applyMatrix4( object.matrixWorld );
  4269. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4270. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4271. intersects.push( {
  4272. distance: distance,
  4273. point: intersectionPoint,
  4274. indices: [a, b, c],
  4275. face: null,
  4276. faceIndex: null,
  4277. object: object
  4278. } );
  4279. }
  4280. }
  4281. } else {
  4282. var offsets = geometry.offsets;
  4283. var positions = attributes.position.array;
  4284. for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {
  4285. a = i;
  4286. b = i + 1;
  4287. c = i + 2;
  4288. vA.set(
  4289. positions[ a * 3 ],
  4290. positions[ a * 3 + 1 ],
  4291. positions[ a * 3 + 2 ]
  4292. );
  4293. vB.set(
  4294. positions[ b * 3 ],
  4295. positions[ b * 3 + 1 ],
  4296. positions[ b * 3 + 2 ]
  4297. );
  4298. vC.set(
  4299. positions[ c * 3 ],
  4300. positions[ c * 3 + 1 ],
  4301. positions[ c * 3 + 2 ]
  4302. );
  4303. if ( material.side === THREE.BackSide ) {
  4304. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4305. } else {
  4306. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, 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. indices: [a, b, c],
  4316. face: null,
  4317. faceIndex: null,
  4318. object: object
  4319. } );
  4320. }
  4321. }
  4322. } else if ( geometry instanceof THREE.Geometry ) {
  4323. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4324. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4325. var a, b, c, d;
  4326. var precision = raycaster.precision;
  4327. var vertices = geometry.vertices;
  4328. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4329. var face = geometry.faces[ f ];
  4330. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4331. if ( material === undefined ) continue;
  4332. a = vertices[ face.a ];
  4333. b = vertices[ face.b ];
  4334. c = vertices[ face.c ];
  4335. if ( material.morphTargets === true ) {
  4336. var morphTargets = geometry.morphTargets;
  4337. var morphInfluences = object.morphTargetInfluences;
  4338. vA.set( 0, 0, 0 );
  4339. vB.set( 0, 0, 0 );
  4340. vC.set( 0, 0, 0 );
  4341. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4342. var influence = morphInfluences[ t ];
  4343. if ( influence === 0 ) continue;
  4344. var targets = morphTargets[ t ].vertices;
  4345. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4346. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4347. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4348. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4349. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4350. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4351. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4352. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4353. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4354. }
  4355. vA.add( a );
  4356. vB.add( b );
  4357. vC.add( c );
  4358. a = vA;
  4359. b = vB;
  4360. c = vC;
  4361. }
  4362. if ( material.side === THREE.BackSide ) {
  4363. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4364. } else {
  4365. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4366. }
  4367. if ( intersectionPoint === null ) continue;
  4368. intersectionPoint.applyMatrix4( object.matrixWorld );
  4369. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4370. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4371. intersects.push( {
  4372. distance: distance,
  4373. point: intersectionPoint,
  4374. face: face,
  4375. faceIndex: f,
  4376. object: object
  4377. } );
  4378. }
  4379. }
  4380. } else if ( object instanceof THREE.Line ) {
  4381. var precision = raycaster.linePrecision;
  4382. var precisionSq = precision * precision;
  4383. var geometry = object.geometry;
  4384. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4385. // Checking boundingSphere distance to ray
  4386. sphere.copy( geometry.boundingSphere );
  4387. sphere.applyMatrix4( object.matrixWorld );
  4388. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4389. return intersects;
  4390. }
  4391. inverseMatrix.getInverse( object.matrixWorld );
  4392. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4393. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4394. } else */ if ( geometry instanceof THREE.Geometry ) {
  4395. var vertices = geometry.vertices;
  4396. var nbVertices = vertices.length;
  4397. var interSegment = new THREE.Vector3();
  4398. var interRay = new THREE.Vector3();
  4399. var step = object.type === THREE.LineStrip ? 1 : 2;
  4400. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4401. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4402. if ( distSq > precisionSq ) continue;
  4403. var distance = localRay.origin.distanceTo( interRay );
  4404. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4405. intersects.push( {
  4406. distance: distance,
  4407. // What do we want? intersection point on the ray or on the segment??
  4408. // point: raycaster.ray.at( distance ),
  4409. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4410. face: null,
  4411. faceIndex: null,
  4412. object: object
  4413. } );
  4414. }
  4415. }
  4416. }
  4417. };
  4418. var intersectDescendants = function ( object, raycaster, intersects ) {
  4419. var descendants = object.getDescendants();
  4420. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4421. intersectObject( descendants[ i ], raycaster, intersects );
  4422. }
  4423. };
  4424. //
  4425. THREE.Raycaster.prototype.precision = 0.0001;
  4426. THREE.Raycaster.prototype.linePrecision = 1;
  4427. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4428. this.ray.set( origin, direction );
  4429. // direction is assumed to be normalized (for accurate distance calculations)
  4430. };
  4431. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4432. var intersects = [];
  4433. if ( recursive === true ) {
  4434. intersectDescendants( object, this, intersects );
  4435. }
  4436. intersectObject( object, this, intersects );
  4437. intersects.sort( descSort );
  4438. return intersects;
  4439. };
  4440. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4441. var intersects = [];
  4442. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4443. intersectObject( objects[ i ], this, intersects );
  4444. if ( recursive === true ) {
  4445. intersectDescendants( objects[ i ], this, intersects );
  4446. }
  4447. }
  4448. intersects.sort( descSort );
  4449. return intersects;
  4450. };
  4451. }( THREE ) );
  4452. /**
  4453. * @author mrdoob / http://mrdoob.com/
  4454. * @author mikael emtinger / http://gomo.se/
  4455. * @author alteredq / http://alteredqualia.com/
  4456. * @author WestLangley / http://github.com/WestLangley
  4457. */
  4458. THREE.Object3D = function () {
  4459. this.id = THREE.Object3DIdCount ++;
  4460. this.uuid = THREE.Math.generateUUID();
  4461. this.name = '';
  4462. this.parent = undefined;
  4463. this.children = [];
  4464. this.up = new THREE.Vector3( 0, 1, 0 );
  4465. this.position = new THREE.Vector3();
  4466. this._rotation = new THREE.Euler();
  4467. this._quaternion = new THREE.Quaternion();
  4468. this.scale = new THREE.Vector3( 1, 1, 1 );
  4469. // keep rotation and quaternion in sync
  4470. this._rotation._quaternion = this.quaternion;
  4471. this._quaternion._euler = this.rotation;
  4472. this.renderDepth = null;
  4473. this.rotationAutoUpdate = true;
  4474. this.matrix = new THREE.Matrix4();
  4475. this.matrixWorld = new THREE.Matrix4();
  4476. this.matrixAutoUpdate = true;
  4477. this.matrixWorldNeedsUpdate = false;
  4478. this.visible = true;
  4479. this.castShadow = false;
  4480. this.receiveShadow = false;
  4481. this.frustumCulled = true;
  4482. this.userData = {};
  4483. };
  4484. THREE.Object3D.prototype = {
  4485. constructor: THREE.Object3D,
  4486. get rotation () {
  4487. return this._rotation;
  4488. },
  4489. set rotation ( value ) {
  4490. this._rotation = value;
  4491. this._rotation._quaternion = this._quaternion;
  4492. this._quaternion._euler = this._rotation;
  4493. this._rotation._updateQuaternion();
  4494. },
  4495. get quaternion () {
  4496. return this._quaternion;
  4497. },
  4498. set quaternion ( value ) {
  4499. this._quaternion = value;
  4500. this._quaternion._euler = this._rotation;
  4501. this._rotation._quaternion = this._quaternion;
  4502. this._quaternion._updateEuler();
  4503. },
  4504. get eulerOrder () {
  4505. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4506. return this.rotation.order;
  4507. },
  4508. set eulerOrder ( value ) {
  4509. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4510. this.rotation.order = value;
  4511. },
  4512. get useQuaternion () {
  4513. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4514. },
  4515. set useQuaternion ( value ) {
  4516. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4517. },
  4518. applyMatrix: function ( matrix ) {
  4519. this.matrix.multiplyMatrices( matrix, this.matrix );
  4520. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4521. },
  4522. setRotationFromAxisAngle: function ( axis, angle ) {
  4523. // assumes axis is normalized
  4524. this.quaternion.setFromAxisAngle( axis, angle );
  4525. },
  4526. setRotationFromEuler: function ( euler ) {
  4527. this.quaternion.setFromEuler( euler, true );
  4528. },
  4529. setRotationFromMatrix: function ( m ) {
  4530. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4531. this.quaternion.setFromRotationMatrix( m );
  4532. },
  4533. setRotationFromQuaternion: function ( q ) {
  4534. // assumes q is normalized
  4535. this.quaternion.copy( q );
  4536. },
  4537. rotateOnAxis: function() {
  4538. // rotate object on axis in object space
  4539. // axis is assumed to be normalized
  4540. var q1 = new THREE.Quaternion();
  4541. return function ( axis, angle ) {
  4542. q1.setFromAxisAngle( axis, angle );
  4543. this.quaternion.multiply( q1 );
  4544. return this;
  4545. }
  4546. }(),
  4547. rotateX: function () {
  4548. var v1 = new THREE.Vector3( 1, 0, 0 );
  4549. return function ( angle ) {
  4550. return this.rotateOnAxis( v1, angle );
  4551. };
  4552. }(),
  4553. rotateY: function () {
  4554. var v1 = new THREE.Vector3( 0, 1, 0 );
  4555. return function ( angle ) {
  4556. return this.rotateOnAxis( v1, angle );
  4557. };
  4558. }(),
  4559. rotateZ: function () {
  4560. var v1 = new THREE.Vector3( 0, 0, 1 );
  4561. return function ( angle ) {
  4562. return this.rotateOnAxis( v1, angle );
  4563. };
  4564. }(),
  4565. translateOnAxis: function () {
  4566. // translate object by distance along axis in object space
  4567. // axis is assumed to be normalized
  4568. var v1 = new THREE.Vector3();
  4569. return function ( axis, distance ) {
  4570. v1.copy( axis );
  4571. v1.applyQuaternion( this.quaternion );
  4572. this.position.add( v1.multiplyScalar( distance ) );
  4573. return this;
  4574. }
  4575. }(),
  4576. translate: function ( distance, axis ) {
  4577. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4578. return this.translateOnAxis( axis, distance );
  4579. },
  4580. translateX: function () {
  4581. var v1 = new THREE.Vector3( 1, 0, 0 );
  4582. return function ( distance ) {
  4583. return this.translateOnAxis( v1, distance );
  4584. };
  4585. }(),
  4586. translateY: function () {
  4587. var v1 = new THREE.Vector3( 0, 1, 0 );
  4588. return function ( distance ) {
  4589. return this.translateOnAxis( v1, distance );
  4590. };
  4591. }(),
  4592. translateZ: function () {
  4593. var v1 = new THREE.Vector3( 0, 0, 1 );
  4594. return function ( distance ) {
  4595. return this.translateOnAxis( v1, distance );
  4596. };
  4597. }(),
  4598. localToWorld: function ( vector ) {
  4599. return vector.applyMatrix4( this.matrixWorld );
  4600. },
  4601. worldToLocal: function () {
  4602. var m1 = new THREE.Matrix4();
  4603. return function ( vector ) {
  4604. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4605. };
  4606. }(),
  4607. lookAt: function () {
  4608. // This routine does not support objects with rotated and/or translated parent(s)
  4609. var m1 = new THREE.Matrix4();
  4610. return function ( vector ) {
  4611. m1.lookAt( vector, this.position, this.up );
  4612. this.quaternion.setFromRotationMatrix( m1 );
  4613. };
  4614. }(),
  4615. add: function ( object ) {
  4616. if ( object === this ) {
  4617. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4618. return;
  4619. }
  4620. if ( object instanceof THREE.Object3D ) {
  4621. if ( object.parent !== undefined ) {
  4622. object.parent.remove( object );
  4623. }
  4624. object.parent = this;
  4625. object.dispatchEvent( { type: 'added' } );
  4626. this.children.push( object );
  4627. // add to scene
  4628. var scene = this;
  4629. while ( scene.parent !== undefined ) {
  4630. scene = scene.parent;
  4631. }
  4632. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4633. scene.__addObject( object );
  4634. }
  4635. }
  4636. },
  4637. remove: function ( object ) {
  4638. var index = this.children.indexOf( object );
  4639. if ( index !== - 1 ) {
  4640. object.parent = undefined;
  4641. object.dispatchEvent( { type: 'removed' } );
  4642. this.children.splice( index, 1 );
  4643. // remove from scene
  4644. var scene = this;
  4645. while ( scene.parent !== undefined ) {
  4646. scene = scene.parent;
  4647. }
  4648. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4649. scene.__removeObject( object );
  4650. }
  4651. }
  4652. },
  4653. traverse: function ( callback ) {
  4654. callback( this );
  4655. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4656. this.children[ i ].traverse( callback );
  4657. }
  4658. },
  4659. getObjectById: function ( id, recursive ) {
  4660. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4661. var child = this.children[ i ];
  4662. if ( child.id === id ) {
  4663. return child;
  4664. }
  4665. if ( recursive === true ) {
  4666. child = child.getObjectById( id, recursive );
  4667. if ( child !== undefined ) {
  4668. return child;
  4669. }
  4670. }
  4671. }
  4672. return undefined;
  4673. },
  4674. getObjectByName: function ( name, recursive ) {
  4675. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4676. var child = this.children[ i ];
  4677. if ( child.name === name ) {
  4678. return child;
  4679. }
  4680. if ( recursive === true ) {
  4681. child = child.getObjectByName( name, recursive );
  4682. if ( child !== undefined ) {
  4683. return child;
  4684. }
  4685. }
  4686. }
  4687. return undefined;
  4688. },
  4689. getChildByName: function ( name, recursive ) {
  4690. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4691. return this.getObjectByName( name, recursive );
  4692. },
  4693. getDescendants: function ( array ) {
  4694. if ( array === undefined ) array = [];
  4695. Array.prototype.push.apply( array, this.children );
  4696. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4697. this.children[ i ].getDescendants( array );
  4698. }
  4699. return array;
  4700. },
  4701. updateMatrix: function () {
  4702. this.matrix.compose( this.position, this.quaternion, this.scale );
  4703. this.matrixWorldNeedsUpdate = true;
  4704. },
  4705. updateMatrixWorld: function ( force ) {
  4706. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4707. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4708. if ( this.parent === undefined ) {
  4709. this.matrixWorld.copy( this.matrix );
  4710. } else {
  4711. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4712. }
  4713. this.matrixWorldNeedsUpdate = false;
  4714. force = true;
  4715. }
  4716. // update children
  4717. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4718. this.children[ i ].updateMatrixWorld( force );
  4719. }
  4720. },
  4721. clone: function ( object, recursive ) {
  4722. if ( object === undefined ) object = new THREE.Object3D();
  4723. if ( recursive === undefined ) recursive = true;
  4724. object.name = this.name;
  4725. object.up.copy( this.up );
  4726. object.position.copy( this.position );
  4727. object.quaternion.copy( this.quaternion );
  4728. object.scale.copy( this.scale );
  4729. object.renderDepth = this.renderDepth;
  4730. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4731. object.matrix.copy( this.matrix );
  4732. object.matrixWorld.copy( this.matrixWorld );
  4733. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4734. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4735. object.visible = this.visible;
  4736. object.castShadow = this.castShadow;
  4737. object.receiveShadow = this.receiveShadow;
  4738. object.frustumCulled = this.frustumCulled;
  4739. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4740. if ( recursive === true ) {
  4741. for ( var i = 0; i < this.children.length; i ++ ) {
  4742. var child = this.children[ i ];
  4743. object.add( child.clone() );
  4744. }
  4745. }
  4746. return object;
  4747. }
  4748. };
  4749. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4750. THREE.Object3DIdCount = 0;
  4751. /**
  4752. * @author mrdoob / http://mrdoob.com/
  4753. * @author supereggbert / http://www.paulbrunt.co.uk/
  4754. * @author julianwa / https://github.com/julianwa
  4755. */
  4756. THREE.Projector = function () {
  4757. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4758. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4759. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4760. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4761. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4762. _renderData = { objects: [], lights: [], elements: [] },
  4763. _vA = new THREE.Vector3(),
  4764. _vB = new THREE.Vector3(),
  4765. _vC = new THREE.Vector3(),
  4766. _vector3 = new THREE.Vector3(),
  4767. _vector4 = new THREE.Vector4(),
  4768. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4769. _boundingBox = new THREE.Box3(),
  4770. _points3 = new Array( 3 ),
  4771. _points4 = new Array( 4 ),
  4772. _viewMatrix = new THREE.Matrix4(),
  4773. _viewProjectionMatrix = new THREE.Matrix4(),
  4774. _modelMatrix,
  4775. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4776. _normalMatrix = new THREE.Matrix3(),
  4777. _frustum = new THREE.Frustum(),
  4778. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4779. _clippedVertex2PositionScreen = new THREE.Vector4();
  4780. this.projectVector = function ( vector, camera ) {
  4781. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4782. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4783. return vector.applyProjection( _viewProjectionMatrix );
  4784. };
  4785. this.unprojectVector = function () {
  4786. var projectionMatrixInverse = new THREE.Matrix4();
  4787. return function ( vector, camera ) {
  4788. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4789. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4790. return vector.applyProjection( _viewProjectionMatrix );
  4791. };
  4792. }();
  4793. this.pickingRay = function ( vector, camera ) {
  4794. // set two vectors with opposing z values
  4795. vector.z = -1.0;
  4796. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4797. this.unprojectVector( vector, camera );
  4798. this.unprojectVector( end, camera );
  4799. // find direction from vector to end
  4800. end.sub( vector ).normalize();
  4801. return new THREE.Raycaster( vector, end );
  4802. };
  4803. var projectObject = function ( object ) {
  4804. if ( object.visible === false ) return;
  4805. if ( object instanceof THREE.Light ) {
  4806. _renderData.lights.push( object );
  4807. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4808. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4809. _object = getNextObjectInPool();
  4810. _object.id = object.id;
  4811. _object.object = object;
  4812. if ( object.renderDepth !== null ) {
  4813. _object.z = object.renderDepth;
  4814. } else {
  4815. _vector3.setFromMatrixPosition( object.matrixWorld );
  4816. _vector3.applyProjection( _viewProjectionMatrix );
  4817. _object.z = _vector3.z;
  4818. }
  4819. _renderData.objects.push( _object );
  4820. }
  4821. }
  4822. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4823. projectObject( object.children[ i ] );
  4824. }
  4825. };
  4826. var projectGraph = function ( root, sortObjects ) {
  4827. _objectCount = 0;
  4828. _renderData.objects.length = 0;
  4829. _renderData.lights.length = 0;
  4830. projectObject( root );
  4831. if ( sortObjects === true ) {
  4832. _renderData.objects.sort( painterSort );
  4833. }
  4834. };
  4835. var RenderList = function () {
  4836. var normals = [];
  4837. var uvs = [];
  4838. var object = null;
  4839. var material = null;
  4840. var normalMatrix = new THREE.Matrix3();
  4841. var setObject = function ( value ) {
  4842. object = value;
  4843. material = object.material;
  4844. normalMatrix.getNormalMatrix( object.matrixWorld );
  4845. normals.length = 0;
  4846. uvs.length = 0;
  4847. };
  4848. var projectVertex = function ( vertex ) {
  4849. var position = vertex.position;
  4850. var positionWorld = vertex.positionWorld;
  4851. var positionScreen = vertex.positionScreen;
  4852. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4853. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4854. var invW = 1 / positionScreen.w;
  4855. positionScreen.x *= invW;
  4856. positionScreen.y *= invW;
  4857. positionScreen.z *= invW;
  4858. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4859. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4860. positionScreen.z >= -1 && positionScreen.z <= 1;
  4861. };
  4862. var pushVertex = function ( x, y, z ) {
  4863. _vertex = getNextVertexInPool();
  4864. _vertex.position.set( x, y, z );
  4865. projectVertex( _vertex );
  4866. };
  4867. var pushNormal = function ( x, y, z ) {
  4868. normals.push( x, y, z );
  4869. };
  4870. var pushUv = function ( x, y ) {
  4871. uvs.push( x, y );
  4872. };
  4873. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4874. if ( v1.visible === true || v2.visible === true || v3.visible === true ) return true;
  4875. _points3[ 0 ] = v1.positionScreen;
  4876. _points3[ 1 ] = v2.positionScreen;
  4877. _points3[ 2 ] = v3.positionScreen;
  4878. return _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) );
  4879. };
  4880. var checkBackfaceCulling = function ( v1, v2, v3 ) {
  4881. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4882. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4883. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4884. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4885. };
  4886. var pushLine = function ( a, b ) {
  4887. var v1 = _vertexPool[ a ];
  4888. var v2 = _vertexPool[ b ];
  4889. _line = getNextLineInPool();
  4890. _line.id = object.id;
  4891. _line.v1.copy( v1 );
  4892. _line.v2.copy( v2 );
  4893. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4894. _line.material = object.material;
  4895. _renderData.elements.push( _line );
  4896. };
  4897. var pushTriangle = function ( a, b, c ) {
  4898. var v1 = _vertexPool[ a ];
  4899. var v2 = _vertexPool[ b ];
  4900. var v3 = _vertexPool[ c ];
  4901. if ( checkTriangleVisibility( v1, v2, v3 ) === false ) return;
  4902. if ( material.side === THREE.DoubleSide || checkBackfaceCulling( v1, v2, v3 ) === true ) {
  4903. _face = getNextFaceInPool();
  4904. _face.id = object.id;
  4905. _face.v1.copy( v1 );
  4906. _face.v2.copy( v2 );
  4907. _face.v3.copy( v3 );
  4908. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4909. for ( var i = 0; i < 3; i ++ ) {
  4910. var offset = arguments[ i ] * 3;
  4911. var normal = _face.vertexNormalsModel[ i ];
  4912. normal.set( normals[ offset ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4913. normal.applyMatrix3( normalMatrix ).normalize();
  4914. var offset2 = arguments[ i ] * 2;
  4915. var uv = _face.uvs[ i ];
  4916. uv.set( uvs[ offset2 ], uvs[ offset2 + 1 ] );
  4917. }
  4918. _face.vertexNormalsLength = 3;
  4919. _face.material = object.material;
  4920. _renderData.elements.push( _face );
  4921. }
  4922. };
  4923. return {
  4924. setObject: setObject,
  4925. projectVertex: projectVertex,
  4926. checkTriangleVisibility: checkTriangleVisibility,
  4927. checkBackfaceCulling: checkBackfaceCulling,
  4928. pushVertex: pushVertex,
  4929. pushNormal: pushNormal,
  4930. pushUv: pushUv,
  4931. pushLine: pushLine,
  4932. pushTriangle: pushTriangle
  4933. }
  4934. };
  4935. var renderList = new RenderList();
  4936. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4937. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs,
  4938. isFaceMaterial, objectMaterials;
  4939. _faceCount = 0;
  4940. _lineCount = 0;
  4941. _spriteCount = 0;
  4942. _renderData.elements.length = 0;
  4943. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4944. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4945. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4946. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4947. _frustum.setFromMatrix( _viewProjectionMatrix );
  4948. projectGraph( scene, sortObjects );
  4949. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4950. object = _renderData.objects[ o ].object;
  4951. geometry = object.geometry;
  4952. renderList.setObject( object );
  4953. _modelMatrix = object.matrixWorld;
  4954. _vertexCount = 0;
  4955. if ( object instanceof THREE.Mesh ) {
  4956. if ( geometry instanceof THREE.BufferGeometry ) {
  4957. var attributes = geometry.attributes;
  4958. var offsets = geometry.offsets;
  4959. if ( attributes.position === undefined ) continue;
  4960. var positions = attributes.position.array;
  4961. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4962. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4963. }
  4964. if ( attributes.normal !== undefined ) {
  4965. var normals = attributes.normal.array;
  4966. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4967. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4968. }
  4969. }
  4970. if ( attributes.uv !== undefined ) {
  4971. var uvs = attributes.uv.array;
  4972. for ( var i = 0, l = uvs.length; i < l; i += 2 ) {
  4973. renderList.pushUv( uvs[ i ], uvs[ i + 1 ] );
  4974. }
  4975. }
  4976. if ( attributes.index !== undefined ) {
  4977. var indices = attributes.index.array;
  4978. if ( offsets.length > 0 ) {
  4979. for ( var o = 0; o < offsets.length; o ++ ) {
  4980. var offset = offsets[ o ];
  4981. var index = offset.index;
  4982. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4983. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4984. }
  4985. }
  4986. } else {
  4987. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4988. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4989. }
  4990. }
  4991. } else {
  4992. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4993. renderList.pushTriangle( i, i + 1, i + 2 );
  4994. }
  4995. }
  4996. } else if ( geometry instanceof THREE.Geometry ) {
  4997. vertices = geometry.vertices;
  4998. faces = geometry.faces;
  4999. faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  5000. _normalMatrix.getNormalMatrix( _modelMatrix );
  5001. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  5002. objectMaterials = isFaceMaterial === true ? object.material : null;
  5003. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  5004. var vertex = vertices[ v ];
  5005. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  5006. }
  5007. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  5008. face = faces[ f ];
  5009. var material = isFaceMaterial === true
  5010. ? objectMaterials.materials[ face.materialIndex ]
  5011. : object.material;
  5012. if ( material === undefined ) continue;
  5013. var side = material.side;
  5014. var v1 = _vertexPool[ face.a ];
  5015. var v2 = _vertexPool[ face.b ];
  5016. var v3 = _vertexPool[ face.c ];
  5017. if ( material.morphTargets === true ) {
  5018. var morphTargets = geometry.morphTargets;
  5019. var morphInfluences = object.morphTargetInfluences;
  5020. var v1p = v1.position;
  5021. var v2p = v2.position;
  5022. var v3p = v3.position;
  5023. _vA.set( 0, 0, 0 );
  5024. _vB.set( 0, 0, 0 );
  5025. _vC.set( 0, 0, 0 );
  5026. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  5027. var influence = morphInfluences[ t ];
  5028. if ( influence === 0 ) continue;
  5029. var targets = morphTargets[ t ].vertices;
  5030. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  5031. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  5032. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  5033. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  5034. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  5035. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  5036. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  5037. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  5038. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  5039. }
  5040. v1.position.add( _vA );
  5041. v2.position.add( _vB );
  5042. v3.position.add( _vC );
  5043. renderList.projectVertex( v1 );
  5044. renderList.projectVertex( v2 );
  5045. renderList.projectVertex( v3 );
  5046. }
  5047. if ( renderList.checkTriangleVisibility( v1, v2, v3 ) === false ) continue;
  5048. var visible = renderList.checkBackfaceCulling( v1, v2, v3 );
  5049. if ( side !== THREE.DoubleSide ) {
  5050. if ( side === THREE.FrontSide && visible === false ) continue;
  5051. if ( side === THREE.BackSide && visible === true ) continue;
  5052. }
  5053. _face = getNextFaceInPool();
  5054. _face.id = object.id;
  5055. _face.v1.copy( v1 );
  5056. _face.v2.copy( v2 );
  5057. _face.v3.copy( v3 );
  5058. _face.normalModel.copy( face.normal );
  5059. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  5060. _face.normalModel.negate();
  5061. }
  5062. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  5063. faceVertexNormals = face.vertexNormals;
  5064. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  5065. var normalModel = _face.vertexNormalsModel[ n ];
  5066. normalModel.copy( faceVertexNormals[ n ] );
  5067. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  5068. normalModel.negate();
  5069. }
  5070. normalModel.applyMatrix3( _normalMatrix ).normalize();
  5071. }
  5072. _face.vertexNormalsLength = faceVertexNormals.length;
  5073. var vertexUvs = faceVertexUvs[ f ];
  5074. if ( vertexUvs !== undefined ) {
  5075. for ( var u = 0; u < 3; u ++ ) {
  5076. _face.uvs[ u ].copy( vertexUvs[ u ] );
  5077. }
  5078. }
  5079. _face.color = face.color;
  5080. _face.material = material;
  5081. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  5082. _renderData.elements.push( _face );
  5083. }
  5084. }
  5085. } else if ( object instanceof THREE.Line ) {
  5086. if ( geometry instanceof THREE.BufferGeometry ) {
  5087. var attributes = geometry.attributes;
  5088. if ( attributes.position !== undefined ) {
  5089. var positions = attributes.position.array;
  5090. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  5091. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5092. }
  5093. if ( attributes.index !== undefined ) {
  5094. var indices = attributes.index.array;
  5095. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  5096. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  5097. }
  5098. } else {
  5099. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  5100. renderList.pushLine( i, i + 1 );
  5101. }
  5102. }
  5103. }
  5104. } else if ( geometry instanceof THREE.Geometry ) {
  5105. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  5106. vertices = object.geometry.vertices;
  5107. if ( vertices.length === 0 ) continue;
  5108. v1 = getNextVertexInPool();
  5109. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  5110. // Handle LineStrip and LinePieces
  5111. var step = object.type === THREE.LinePieces ? 2 : 1;
  5112. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  5113. v1 = getNextVertexInPool();
  5114. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  5115. if ( ( v + 1 ) % step > 0 ) continue;
  5116. v2 = _vertexPool[ _vertexCount - 2 ];
  5117. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  5118. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  5119. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  5120. // Perform the perspective divide
  5121. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  5122. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  5123. _line = getNextLineInPool();
  5124. _line.id = object.id;
  5125. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  5126. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  5127. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  5128. _line.material = object.material;
  5129. if ( object.material.vertexColors === THREE.VertexColors ) {
  5130. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  5131. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  5132. }
  5133. _renderData.elements.push( _line );
  5134. }
  5135. }
  5136. }
  5137. } else if ( object instanceof THREE.Sprite ) {
  5138. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  5139. _vector4.applyMatrix4( _viewProjectionMatrix );
  5140. var invW = 1 / _vector4.w;
  5141. _vector4.z *= invW;
  5142. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  5143. _sprite = getNextSpriteInPool();
  5144. _sprite.id = object.id;
  5145. _sprite.x = _vector4.x * invW;
  5146. _sprite.y = _vector4.y * invW;
  5147. _sprite.z = _vector4.z;
  5148. _sprite.object = object;
  5149. _sprite.rotation = object.rotation;
  5150. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  5151. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  5152. _sprite.material = object.material;
  5153. _renderData.elements.push( _sprite );
  5154. }
  5155. }
  5156. }
  5157. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  5158. return _renderData;
  5159. };
  5160. // Pools
  5161. function getNextObjectInPool() {
  5162. if ( _objectCount === _objectPoolLength ) {
  5163. var object = new THREE.RenderableObject();
  5164. _objectPool.push( object );
  5165. _objectPoolLength ++;
  5166. _objectCount ++;
  5167. return object;
  5168. }
  5169. return _objectPool[ _objectCount ++ ];
  5170. }
  5171. function getNextVertexInPool() {
  5172. if ( _vertexCount === _vertexPoolLength ) {
  5173. var vertex = new THREE.RenderableVertex();
  5174. _vertexPool.push( vertex );
  5175. _vertexPoolLength ++;
  5176. _vertexCount ++;
  5177. return vertex;
  5178. }
  5179. return _vertexPool[ _vertexCount ++ ];
  5180. }
  5181. function getNextFaceInPool() {
  5182. if ( _faceCount === _facePoolLength ) {
  5183. var face = new THREE.RenderableFace();
  5184. _facePool.push( face );
  5185. _facePoolLength ++;
  5186. _faceCount ++;
  5187. return face;
  5188. }
  5189. return _facePool[ _faceCount ++ ];
  5190. }
  5191. function getNextLineInPool() {
  5192. if ( _lineCount === _linePoolLength ) {
  5193. var line = new THREE.RenderableLine();
  5194. _linePool.push( line );
  5195. _linePoolLength ++;
  5196. _lineCount ++
  5197. return line;
  5198. }
  5199. return _linePool[ _lineCount ++ ];
  5200. }
  5201. function getNextSpriteInPool() {
  5202. if ( _spriteCount === _spritePoolLength ) {
  5203. var sprite = new THREE.RenderableSprite();
  5204. _spritePool.push( sprite );
  5205. _spritePoolLength ++;
  5206. _spriteCount ++
  5207. return sprite;
  5208. }
  5209. return _spritePool[ _spriteCount ++ ];
  5210. }
  5211. //
  5212. function painterSort( a, b ) {
  5213. if ( a.z !== b.z ) {
  5214. return b.z - a.z;
  5215. } else if ( a.id !== b.id ) {
  5216. return a.id - b.id;
  5217. } else {
  5218. return 0;
  5219. }
  5220. }
  5221. function clipLine( s1, s2 ) {
  5222. var alpha1 = 0, alpha2 = 1,
  5223. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5224. // Z = -1 and Z = +1, respectively.
  5225. bc1near = s1.z + s1.w,
  5226. bc2near = s2.z + s2.w,
  5227. bc1far = - s1.z + s1.w,
  5228. bc2far = - s2.z + s2.w;
  5229. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5230. // Both vertices lie entirely within all clip planes.
  5231. return true;
  5232. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5233. // Both vertices lie entirely outside one of the clip planes.
  5234. return false;
  5235. } else {
  5236. // The line segment spans at least one clip plane.
  5237. if ( bc1near < 0 ) {
  5238. // v1 lies outside the near plane, v2 inside
  5239. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5240. } else if ( bc2near < 0 ) {
  5241. // v2 lies outside the near plane, v1 inside
  5242. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5243. }
  5244. if ( bc1far < 0 ) {
  5245. // v1 lies outside the far plane, v2 inside
  5246. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5247. } else if ( bc2far < 0 ) {
  5248. // v2 lies outside the far plane, v2 inside
  5249. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5250. }
  5251. if ( alpha2 < alpha1 ) {
  5252. // The line segment spans two boundaries, but is outside both of them.
  5253. // (This can't happen when we're only clipping against just near/far but good
  5254. // to leave the check here for future usage if other clip planes are added.)
  5255. return false;
  5256. } else {
  5257. // Update the s1 and s2 vertices to match the clipped line segment.
  5258. s1.lerp( s2, alpha1 );
  5259. s2.lerp( s1, 1 - alpha2 );
  5260. return true;
  5261. }
  5262. }
  5263. }
  5264. };
  5265. /**
  5266. * @author mrdoob / http://mrdoob.com/
  5267. * @author alteredq / http://alteredqualia.com/
  5268. */
  5269. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5270. this.a = a;
  5271. this.b = b;
  5272. this.c = c;
  5273. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5274. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5275. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5276. this.vertexColors = color instanceof Array ? color : [];
  5277. this.vertexTangents = [];
  5278. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5279. };
  5280. THREE.Face3.prototype = {
  5281. constructor: THREE.Face3,
  5282. clone: function () {
  5283. var face = new THREE.Face3( this.a, this.b, this.c );
  5284. face.normal.copy( this.normal );
  5285. face.color.copy( this.color );
  5286. face.materialIndex = this.materialIndex;
  5287. var i, il;
  5288. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5289. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5290. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5291. return face;
  5292. }
  5293. };
  5294. /**
  5295. * @author mrdoob / http://mrdoob.com/
  5296. */
  5297. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5298. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5299. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5300. };
  5301. /**
  5302. * @author mrdoob / http://mrdoob.com/
  5303. */
  5304. THREE.BufferAttribute = function () {};
  5305. THREE.BufferAttribute.prototype = {
  5306. constructor: THREE.BufferAttribute,
  5307. get length () {
  5308. return this.array.length;
  5309. },
  5310. set: function ( value ) {
  5311. this.array.set( value );
  5312. },
  5313. setX: function ( index, x ) {
  5314. this.array[ index * this.itemSize ] = x;
  5315. },
  5316. setY: function ( index, y ) {
  5317. this.array[ index * this.itemSize + 1 ] = y;
  5318. },
  5319. setZ: function ( index, z ) {
  5320. this.array[ index * this.itemSize + 2 ] = z;
  5321. },
  5322. setXY: function ( index, x, y ) {
  5323. index *= this.itemSize;
  5324. this.array[ index ] = x;
  5325. this.array[ index + 1 ] = y;
  5326. },
  5327. setXYZ: function ( index, x, y, z ) {
  5328. index *= this.itemSize;
  5329. this.array[ index ] = x;
  5330. this.array[ index + 1 ] = y;
  5331. this.array[ index + 2 ] = z;
  5332. },
  5333. setXYZW: function ( index, x, y, z, w ) {
  5334. index *= this.itemSize;
  5335. this.array[ index ] = x;
  5336. this.array[ index + 1 ] = y;
  5337. this.array[ index + 2 ] = z;
  5338. this.array[ index + 3 ] = w;
  5339. }
  5340. };
  5341. //
  5342. THREE.Int8Attribute = function ( size, itemSize ) {
  5343. this.array = new Int8Array( size * itemSize );
  5344. this.itemSize = itemSize;
  5345. };
  5346. THREE.Int8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5347. THREE.Uint8Attribute = function ( size, itemSize ) {
  5348. this.array = new Uint8Array( size * itemSize );
  5349. this.itemSize = itemSize;
  5350. };
  5351. THREE.Uint8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5352. THREE.Uint8ClampedAttribute = function ( size, itemSize ) {
  5353. this.array = new Uint8ClampedArray( size * itemSize );
  5354. this.itemSize = itemSize;
  5355. };
  5356. THREE.Uint8ClampedAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5357. THREE.Int16Attribute = function ( size, itemSize ) {
  5358. this.array = new Int16Array( size * itemSize );
  5359. this.itemSize = itemSize;
  5360. };
  5361. THREE.Int16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5362. THREE.Uint16Attribute = function ( size, itemSize ) {
  5363. this.array = new Uint16Array( size * itemSize );
  5364. this.itemSize = itemSize;
  5365. };
  5366. THREE.Uint16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5367. THREE.Int32Attribute = function ( size, itemSize ) {
  5368. this.array = new Int32Array( size * itemSize );
  5369. this.itemSize = itemSize;
  5370. };
  5371. THREE.Int32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5372. THREE.Uint32Attribute = function ( size, itemSize ) {
  5373. this.array = new Uint32Array( size * itemSize );
  5374. this.itemSize = itemSize;
  5375. };
  5376. THREE.Uint32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5377. THREE.Float32Attribute = function ( size, itemSize ) {
  5378. this.array = new Float32Array( size * itemSize );
  5379. this.itemSize = itemSize;
  5380. };
  5381. THREE.Float32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5382. THREE.Float64Attribute = function ( size, itemSize ) {
  5383. this.array = new Float64Array( size * itemSize );
  5384. this.itemSize = itemSize;
  5385. };
  5386. THREE.Float64Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5387. /**
  5388. * @author alteredq / http://alteredqualia.com/
  5389. */
  5390. THREE.BufferGeometry = function () {
  5391. this.id = THREE.GeometryIdCount ++;
  5392. this.uuid = THREE.Math.generateUUID();
  5393. this.name = '';
  5394. this.attributes = {};
  5395. this.drawcalls = [];
  5396. this.offsets = this.drawcalls; // backwards compatibility
  5397. this.boundingBox = null;
  5398. this.boundingSphere = null;
  5399. };
  5400. THREE.BufferGeometry.prototype = {
  5401. constructor: THREE.BufferGeometry,
  5402. addAttribute: function ( name, attribute ) {
  5403. if ( attribute instanceof THREE.BufferAttribute === false ) {
  5404. console.warn( 'DEPRECATED: BufferGeometry\'s addAttribute() now expects ( name, attribute ).' );
  5405. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  5406. return;
  5407. }
  5408. this.attributes[ name ] = attribute;
  5409. },
  5410. getAttribute: function ( name ) {
  5411. return this.attributes[ name ];
  5412. },
  5413. addDrawCall: function ( start, count, indexOffset ) {
  5414. this.drawcalls.push( {
  5415. start: start,
  5416. count: count,
  5417. index: indexOffset !== undefined ? indexOffset : 0
  5418. } );
  5419. },
  5420. applyMatrix: function ( matrix ) {
  5421. var position = this.attributes.position;
  5422. if ( position !== undefined ) {
  5423. matrix.applyToVector3Array( position.array );
  5424. position.needsUpdate = true;
  5425. }
  5426. var normal = this.attributes.normal;
  5427. if ( normal !== undefined ) {
  5428. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5429. normalMatrix.applyToVector3Array( normal.array );
  5430. normal.needsUpdate = true;
  5431. }
  5432. },
  5433. computeBoundingBox: function () {
  5434. if ( this.boundingBox === null ) {
  5435. this.boundingBox = new THREE.Box3();
  5436. }
  5437. var positions = this.attributes[ "position" ].array;
  5438. if ( positions ) {
  5439. var bb = this.boundingBox;
  5440. if( positions.length >= 3 ) {
  5441. bb.min.x = bb.max.x = positions[ 0 ];
  5442. bb.min.y = bb.max.y = positions[ 1 ];
  5443. bb.min.z = bb.max.z = positions[ 2 ];
  5444. }
  5445. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5446. var x = positions[ i ];
  5447. var y = positions[ i + 1 ];
  5448. var z = positions[ i + 2 ];
  5449. // bounding box
  5450. if ( x < bb.min.x ) {
  5451. bb.min.x = x;
  5452. } else if ( x > bb.max.x ) {
  5453. bb.max.x = x;
  5454. }
  5455. if ( y < bb.min.y ) {
  5456. bb.min.y = y;
  5457. } else if ( y > bb.max.y ) {
  5458. bb.max.y = y;
  5459. }
  5460. if ( z < bb.min.z ) {
  5461. bb.min.z = z;
  5462. } else if ( z > bb.max.z ) {
  5463. bb.max.z = z;
  5464. }
  5465. }
  5466. }
  5467. if ( positions === undefined || positions.length === 0 ) {
  5468. this.boundingBox.min.set( 0, 0, 0 );
  5469. this.boundingBox.max.set( 0, 0, 0 );
  5470. }
  5471. },
  5472. computeBoundingSphere: function () {
  5473. var box = new THREE.Box3();
  5474. var vector = new THREE.Vector3();
  5475. return function () {
  5476. if ( this.boundingSphere === null ) {
  5477. this.boundingSphere = new THREE.Sphere();
  5478. }
  5479. var positions = this.attributes[ "position" ].array;
  5480. if ( positions ) {
  5481. box.makeEmpty();
  5482. var center = this.boundingSphere.center;
  5483. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5484. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5485. box.addPoint( vector );
  5486. }
  5487. box.center( center );
  5488. var maxRadiusSq = 0;
  5489. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5490. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5491. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5492. }
  5493. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5494. }
  5495. }
  5496. }(),
  5497. computeFaceNormals: function () {
  5498. // backwards compatibility
  5499. },
  5500. computeVertexNormals: function () {
  5501. if ( this.attributes[ "position" ] ) {
  5502. var i, il;
  5503. var j, jl;
  5504. var nVertexElements = this.attributes[ "position" ].array.length;
  5505. if ( this.attributes[ "normal" ] === undefined ) {
  5506. this.attributes[ "normal" ] = {
  5507. itemSize: 3,
  5508. array: new Float32Array( nVertexElements )
  5509. };
  5510. } else {
  5511. // reset existing normals to zero
  5512. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5513. this.attributes[ "normal" ].array[ i ] = 0;
  5514. }
  5515. }
  5516. var positions = this.attributes[ "position" ].array;
  5517. var normals = this.attributes[ "normal" ].array;
  5518. var vA, vB, vC, x, y, z,
  5519. pA = new THREE.Vector3(),
  5520. pB = new THREE.Vector3(),
  5521. pC = new THREE.Vector3(),
  5522. cb = new THREE.Vector3(),
  5523. ab = new THREE.Vector3();
  5524. // indexed elements
  5525. if ( this.attributes[ "index" ] ) {
  5526. var indices = this.attributes[ "index" ].array;
  5527. var offsets = this.offsets;
  5528. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5529. var start = offsets[ j ].start;
  5530. var count = offsets[ j ].count;
  5531. var index = offsets[ j ].index;
  5532. for ( i = start, il = start + count; i < il; i += 3 ) {
  5533. vA = index + indices[ i ];
  5534. vB = index + indices[ i + 1 ];
  5535. vC = index + indices[ i + 2 ];
  5536. x = positions[ vA * 3 ];
  5537. y = positions[ vA * 3 + 1 ];
  5538. z = positions[ vA * 3 + 2 ];
  5539. pA.set( x, y, z );
  5540. x = positions[ vB * 3 ];
  5541. y = positions[ vB * 3 + 1 ];
  5542. z = positions[ vB * 3 + 2 ];
  5543. pB.set( x, y, z );
  5544. x = positions[ vC * 3 ];
  5545. y = positions[ vC * 3 + 1 ];
  5546. z = positions[ vC * 3 + 2 ];
  5547. pC.set( x, y, z );
  5548. cb.subVectors( pC, pB );
  5549. ab.subVectors( pA, pB );
  5550. cb.cross( ab );
  5551. normals[ vA * 3 ] += cb.x;
  5552. normals[ vA * 3 + 1 ] += cb.y;
  5553. normals[ vA * 3 + 2 ] += cb.z;
  5554. normals[ vB * 3 ] += cb.x;
  5555. normals[ vB * 3 + 1 ] += cb.y;
  5556. normals[ vB * 3 + 2 ] += cb.z;
  5557. normals[ vC * 3 ] += cb.x;
  5558. normals[ vC * 3 + 1 ] += cb.y;
  5559. normals[ vC * 3 + 2 ] += cb.z;
  5560. }
  5561. }
  5562. // non-indexed elements (unconnected triangle soup)
  5563. } else {
  5564. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5565. x = positions[ i ];
  5566. y = positions[ i + 1 ];
  5567. z = positions[ i + 2 ];
  5568. pA.set( x, y, z );
  5569. x = positions[ i + 3 ];
  5570. y = positions[ i + 4 ];
  5571. z = positions[ i + 5 ];
  5572. pB.set( x, y, z );
  5573. x = positions[ i + 6 ];
  5574. y = positions[ i + 7 ];
  5575. z = positions[ i + 8 ];
  5576. pC.set( x, y, z );
  5577. cb.subVectors( pC, pB );
  5578. ab.subVectors( pA, pB );
  5579. cb.cross( ab );
  5580. normals[ i ] = cb.x;
  5581. normals[ i + 1 ] = cb.y;
  5582. normals[ i + 2 ] = cb.z;
  5583. normals[ i + 3 ] = cb.x;
  5584. normals[ i + 4 ] = cb.y;
  5585. normals[ i + 5 ] = cb.z;
  5586. normals[ i + 6 ] = cb.x;
  5587. normals[ i + 7 ] = cb.y;
  5588. normals[ i + 8 ] = cb.z;
  5589. }
  5590. }
  5591. this.normalizeNormals();
  5592. this.normalsNeedUpdate = true;
  5593. }
  5594. },
  5595. normalizeNormals: function () {
  5596. var normals = this.attributes[ "normal" ].array;
  5597. var x, y, z, n;
  5598. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5599. x = normals[ i ];
  5600. y = normals[ i + 1 ];
  5601. z = normals[ i + 2 ];
  5602. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5603. normals[ i ] *= n;
  5604. normals[ i + 1 ] *= n;
  5605. normals[ i + 2 ] *= n;
  5606. }
  5607. },
  5608. computeTangents: function () {
  5609. // based on http://www.terathon.com/code/tangent.html
  5610. // (per vertex tangents)
  5611. if ( this.attributes[ "index" ] === undefined ||
  5612. this.attributes[ "position" ] === undefined ||
  5613. this.attributes[ "normal" ] === undefined ||
  5614. this.attributes[ "uv" ] === undefined ) {
  5615. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5616. return;
  5617. }
  5618. var indices = this.attributes[ "index" ].array;
  5619. var positions = this.attributes[ "position" ].array;
  5620. var normals = this.attributes[ "normal" ].array;
  5621. var uvs = this.attributes[ "uv" ].array;
  5622. var nVertices = positions.length / 3;
  5623. if ( this.attributes[ "tangent" ] === undefined ) {
  5624. var nTangentElements = 4 * nVertices;
  5625. this.attributes[ "tangent" ] = {
  5626. itemSize: 4,
  5627. array: new Float32Array( nTangentElements )
  5628. };
  5629. }
  5630. var tangents = this.attributes[ "tangent" ].array;
  5631. var tan1 = [], tan2 = [];
  5632. for ( var k = 0; k < nVertices; k ++ ) {
  5633. tan1[ k ] = new THREE.Vector3();
  5634. tan2[ k ] = new THREE.Vector3();
  5635. }
  5636. var xA, yA, zA,
  5637. xB, yB, zB,
  5638. xC, yC, zC,
  5639. uA, vA,
  5640. uB, vB,
  5641. uC, vC,
  5642. x1, x2, y1, y2, z1, z2,
  5643. s1, s2, t1, t2, r;
  5644. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5645. function handleTriangle( a, b, c ) {
  5646. xA = positions[ a * 3 ];
  5647. yA = positions[ a * 3 + 1 ];
  5648. zA = positions[ a * 3 + 2 ];
  5649. xB = positions[ b * 3 ];
  5650. yB = positions[ b * 3 + 1 ];
  5651. zB = positions[ b * 3 + 2 ];
  5652. xC = positions[ c * 3 ];
  5653. yC = positions[ c * 3 + 1 ];
  5654. zC = positions[ c * 3 + 2 ];
  5655. uA = uvs[ a * 2 ];
  5656. vA = uvs[ a * 2 + 1 ];
  5657. uB = uvs[ b * 2 ];
  5658. vB = uvs[ b * 2 + 1 ];
  5659. uC = uvs[ c * 2 ];
  5660. vC = uvs[ c * 2 + 1 ];
  5661. x1 = xB - xA;
  5662. x2 = xC - xA;
  5663. y1 = yB - yA;
  5664. y2 = yC - yA;
  5665. z1 = zB - zA;
  5666. z2 = zC - zA;
  5667. s1 = uB - uA;
  5668. s2 = uC - uA;
  5669. t1 = vB - vA;
  5670. t2 = vC - vA;
  5671. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5672. sdir.set(
  5673. ( t2 * x1 - t1 * x2 ) * r,
  5674. ( t2 * y1 - t1 * y2 ) * r,
  5675. ( t2 * z1 - t1 * z2 ) * r
  5676. );
  5677. tdir.set(
  5678. ( s1 * x2 - s2 * x1 ) * r,
  5679. ( s1 * y2 - s2 * y1 ) * r,
  5680. ( s1 * z2 - s2 * z1 ) * r
  5681. );
  5682. tan1[ a ].add( sdir );
  5683. tan1[ b ].add( sdir );
  5684. tan1[ c ].add( sdir );
  5685. tan2[ a ].add( tdir );
  5686. tan2[ b ].add( tdir );
  5687. tan2[ c ].add( tdir );
  5688. }
  5689. var i, il;
  5690. var j, jl;
  5691. var iA, iB, iC;
  5692. var offsets = this.offsets;
  5693. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5694. var start = offsets[ j ].start;
  5695. var count = offsets[ j ].count;
  5696. var index = offsets[ j ].index;
  5697. for ( i = start, il = start + count; i < il; i += 3 ) {
  5698. iA = index + indices[ i ];
  5699. iB = index + indices[ i + 1 ];
  5700. iC = index + indices[ i + 2 ];
  5701. handleTriangle( iA, iB, iC );
  5702. }
  5703. }
  5704. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5705. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5706. var w, t, test;
  5707. function handleVertex( v ) {
  5708. n.x = normals[ v * 3 ];
  5709. n.y = normals[ v * 3 + 1 ];
  5710. n.z = normals[ v * 3 + 2 ];
  5711. n2.copy( n );
  5712. t = tan1[ v ];
  5713. // Gram-Schmidt orthogonalize
  5714. tmp.copy( t );
  5715. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5716. // Calculate handedness
  5717. tmp2.crossVectors( n2, t );
  5718. test = tmp2.dot( tan2[ v ] );
  5719. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5720. tangents[ v * 4 ] = tmp.x;
  5721. tangents[ v * 4 + 1 ] = tmp.y;
  5722. tangents[ v * 4 + 2 ] = tmp.z;
  5723. tangents[ v * 4 + 3 ] = w;
  5724. }
  5725. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5726. var start = offsets[ j ].start;
  5727. var count = offsets[ j ].count;
  5728. var index = offsets[ j ].index;
  5729. for ( i = start, il = start + count; i < il; i += 3 ) {
  5730. iA = index + indices[ i ];
  5731. iB = index + indices[ i + 1 ];
  5732. iC = index + indices[ i + 2 ];
  5733. handleVertex( iA );
  5734. handleVertex( iB );
  5735. handleVertex( iC );
  5736. }
  5737. }
  5738. },
  5739. /*
  5740. computeOffsets
  5741. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5742. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5743. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5744. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5745. */
  5746. computeOffsets: function(indexBufferSize) {
  5747. var size = indexBufferSize;
  5748. if(indexBufferSize === undefined)
  5749. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5750. var s = Date.now();
  5751. var indices = this.attributes['index'].array;
  5752. var vertices = this.attributes['position'].array;
  5753. var verticesCount = (vertices.length/3);
  5754. var facesCount = (indices.length/3);
  5755. /*
  5756. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5757. console.log("Faces to process: "+(indices.length/3));
  5758. console.log("Reordering "+verticesCount+" vertices.");
  5759. */
  5760. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5761. var indexPtr = 0;
  5762. var vertexPtr = 0;
  5763. var offsets = [ { start:0, count:0, index:0 } ];
  5764. var offset = offsets[0];
  5765. var duplicatedVertices = 0;
  5766. var newVerticeMaps = 0;
  5767. var faceVertices = new Int32Array(6);
  5768. var vertexMap = new Int32Array( vertices.length );
  5769. var revVertexMap = new Int32Array( vertices.length );
  5770. for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; }
  5771. /*
  5772. Traverse every face and reorder vertices in the proper offsets of 65k.
  5773. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5774. */
  5775. for(var findex = 0; findex < facesCount; findex++) {
  5776. newVerticeMaps = 0;
  5777. for(var vo = 0; vo < 3; vo++) {
  5778. var vid = indices[ findex*3 + vo ];
  5779. if(vertexMap[vid] == -1) {
  5780. //Unmapped vertice
  5781. faceVertices[vo*2] = vid;
  5782. faceVertices[vo*2+1] = -1;
  5783. newVerticeMaps++;
  5784. } else if(vertexMap[vid] < offset.index) {
  5785. //Reused vertices from previous block (duplicate)
  5786. faceVertices[vo*2] = vid;
  5787. faceVertices[vo*2+1] = -1;
  5788. duplicatedVertices++;
  5789. } else {
  5790. //Reused vertice in the current block
  5791. faceVertices[vo*2] = vid;
  5792. faceVertices[vo*2+1] = vertexMap[vid];
  5793. }
  5794. }
  5795. var faceMax = vertexPtr + newVerticeMaps;
  5796. if(faceMax > (offset.index + size)) {
  5797. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5798. offsets.push(new_offset);
  5799. offset = new_offset;
  5800. //Re-evaluate reused vertices in light of new offset.
  5801. for(var v = 0; v < 6; v+=2) {
  5802. var new_vid = faceVertices[v+1];
  5803. if(new_vid > -1 && new_vid < offset.index)
  5804. faceVertices[v+1] = -1;
  5805. }
  5806. }
  5807. //Reindex the face.
  5808. for(var v = 0; v < 6; v+=2) {
  5809. var vid = faceVertices[v];
  5810. var new_vid = faceVertices[v+1];
  5811. if(new_vid === -1)
  5812. new_vid = vertexPtr++;
  5813. vertexMap[vid] = new_vid;
  5814. revVertexMap[new_vid] = vid;
  5815. sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit
  5816. offset.count++;
  5817. }
  5818. }
  5819. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5820. this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr);
  5821. this.offsets = offsets;
  5822. /*
  5823. var orderTime = Date.now();
  5824. console.log("Reorder time: "+(orderTime-s)+"ms");
  5825. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5826. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5827. console.log("Draw offsets: "+offsets.length);
  5828. */
  5829. return offsets;
  5830. },
  5831. /*
  5832. reoderBuffers:
  5833. Reorder attributes based on a new indexBuffer and indexMap.
  5834. indexBuffer - Uint16Array of the new ordered indices.
  5835. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5836. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5837. */
  5838. reorderBuffers: function(indexBuffer, indexMap, vertexCount) {
  5839. /* Create a copy of all attributes for reordering. */
  5840. var sortedAttributes = {};
  5841. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5842. for( var attr in this.attributes ) {
  5843. if(attr == 'index')
  5844. continue;
  5845. var sourceArray = this.attributes[attr].array;
  5846. for ( var i = 0, il = types.length; i < il; i++ ) {
  5847. var type = types[i];
  5848. if (sourceArray instanceof type) {
  5849. sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
  5850. break;
  5851. }
  5852. }
  5853. }
  5854. /* Move attribute positions based on the new index map */
  5855. for(var new_vid = 0; new_vid < vertexCount; new_vid++) {
  5856. var vid = indexMap[new_vid];
  5857. for ( var attr in this.attributes ) {
  5858. if(attr == 'index')
  5859. continue;
  5860. var attrArray = this.attributes[attr].array;
  5861. var attrSize = this.attributes[attr].itemSize;
  5862. var sortedAttr = sortedAttributes[attr];
  5863. for(var k = 0; k < attrSize; k++)
  5864. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5865. }
  5866. }
  5867. /* Carry the new sorted buffers locally */
  5868. this.attributes['index'].array = indexBuffer;
  5869. for ( var attr in this.attributes ) {
  5870. if(attr == 'index')
  5871. continue;
  5872. this.attributes[attr].array = sortedAttributes[attr];
  5873. this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount;
  5874. }
  5875. },
  5876. clone: function () {
  5877. var geometry = new THREE.BufferGeometry();
  5878. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5879. for ( var attr in this.attributes ) {
  5880. var sourceAttr = this.attributes[ attr ];
  5881. var sourceArray = sourceAttr.array;
  5882. var attribute = {
  5883. itemSize: sourceAttr.itemSize,
  5884. array: null
  5885. };
  5886. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5887. var type = types[ i ];
  5888. if ( sourceArray instanceof type ) {
  5889. attribute.array = new type( sourceArray );
  5890. break;
  5891. }
  5892. }
  5893. geometry.attributes[ attr ] = attribute;
  5894. }
  5895. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5896. var offset = this.offsets[ i ];
  5897. geometry.offsets.push( {
  5898. start: offset.start,
  5899. index: offset.index,
  5900. count: offset.count
  5901. } );
  5902. }
  5903. return geometry;
  5904. },
  5905. dispose: function () {
  5906. this.dispatchEvent( { type: 'dispose' } );
  5907. }
  5908. };
  5909. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5910. /**
  5911. * @author mrdoob / http://mrdoob.com/
  5912. */
  5913. THREE.BufferGeometryManipulator = function ( bufferGeometry ) {
  5914. this.vertices = [];
  5915. this.normals = [];
  5916. this.uvs = [];
  5917. var attributes = bufferGeometry.attributes;
  5918. var length = attributes.position.array.length;
  5919. for ( var i = 0, l = length / 3; i < l; i ++ ) {
  5920. this.vertices.push( new THREE.TypedVector3( attributes.position.array, i * 3 ) );
  5921. this.normals.push( new THREE.TypedVector3( attributes.normal.array, i * 3 ) );
  5922. this.uvs.push( new THREE.TypedVector2( attributes.uv.array, i * 2 ) );
  5923. }
  5924. };
  5925. /**
  5926. * @author mrdoob / http://mrdoob.com/
  5927. * @author kile / http://kile.stravaganza.org/
  5928. * @author alteredq / http://alteredqualia.com/
  5929. * @author mikael emtinger / http://gomo.se/
  5930. * @author zz85 / http://www.lab4games.net/zz85/blog
  5931. * @author bhouston / http://exocortex.com
  5932. */
  5933. THREE.Geometry = function () {
  5934. this.id = THREE.GeometryIdCount ++;
  5935. this.uuid = THREE.Math.generateUUID();
  5936. this.name = '';
  5937. this.vertices = [];
  5938. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  5939. this.faces = [];
  5940. this.faceVertexUvs = [[]];
  5941. this.morphTargets = [];
  5942. this.morphColors = [];
  5943. this.morphNormals = [];
  5944. this.skinWeights = [];
  5945. this.skinIndices = [];
  5946. this.lineDistances = [];
  5947. this.boundingBox = null;
  5948. this.boundingSphere = null;
  5949. this.hasTangents = false;
  5950. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5951. // update flags
  5952. this.verticesNeedUpdate = false;
  5953. this.elementsNeedUpdate = false;
  5954. this.uvsNeedUpdate = false;
  5955. this.normalsNeedUpdate = false;
  5956. this.tangentsNeedUpdate = false;
  5957. this.colorsNeedUpdate = false;
  5958. this.lineDistancesNeedUpdate = false;
  5959. this.buffersNeedUpdate = false;
  5960. };
  5961. THREE.Geometry.prototype = {
  5962. constructor: THREE.Geometry,
  5963. applyMatrix: function ( matrix ) {
  5964. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5965. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5966. var vertex = this.vertices[ i ];
  5967. vertex.applyMatrix4( matrix );
  5968. }
  5969. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5970. var face = this.faces[ i ];
  5971. face.normal.applyMatrix3( normalMatrix ).normalize();
  5972. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5973. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5974. }
  5975. }
  5976. if ( this.boundingBox instanceof THREE.Box3 ) {
  5977. this.computeBoundingBox();
  5978. }
  5979. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5980. this.computeBoundingSphere();
  5981. }
  5982. },
  5983. computeFaceNormals: function () {
  5984. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5985. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5986. var face = this.faces[ f ];
  5987. var vA = this.vertices[ face.a ];
  5988. var vB = this.vertices[ face.b ];
  5989. var vC = this.vertices[ face.c ];
  5990. cb.subVectors( vC, vB );
  5991. ab.subVectors( vA, vB );
  5992. cb.cross( ab );
  5993. cb.normalize();
  5994. face.normal.copy( cb );
  5995. }
  5996. },
  5997. computeVertexNormals: function ( areaWeighted ) {
  5998. var v, vl, f, fl, face, vertices;
  5999. vertices = new Array( this.vertices.length );
  6000. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6001. vertices[ v ] = new THREE.Vector3();
  6002. }
  6003. if ( areaWeighted ) {
  6004. // vertex normals weighted by triangle areas
  6005. // http://www.iquilezles.org/www/articles/normals/normals.htm
  6006. var vA, vB, vC, vD;
  6007. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  6008. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  6009. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6010. face = this.faces[ f ];
  6011. vA = this.vertices[ face.a ];
  6012. vB = this.vertices[ face.b ];
  6013. vC = this.vertices[ face.c ];
  6014. cb.subVectors( vC, vB );
  6015. ab.subVectors( vA, vB );
  6016. cb.cross( ab );
  6017. vertices[ face.a ].add( cb );
  6018. vertices[ face.b ].add( cb );
  6019. vertices[ face.c ].add( cb );
  6020. }
  6021. } else {
  6022. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6023. face = this.faces[ f ];
  6024. vertices[ face.a ].add( face.normal );
  6025. vertices[ face.b ].add( face.normal );
  6026. vertices[ face.c ].add( face.normal );
  6027. }
  6028. }
  6029. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6030. vertices[ v ].normalize();
  6031. }
  6032. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6033. face = this.faces[ f ];
  6034. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  6035. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  6036. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  6037. }
  6038. },
  6039. computeMorphNormals: function () {
  6040. var i, il, f, fl, face;
  6041. // save original normals
  6042. // - create temp variables on first access
  6043. // otherwise just copy (for faster repeated calls)
  6044. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6045. face = this.faces[ f ];
  6046. if ( ! face.__originalFaceNormal ) {
  6047. face.__originalFaceNormal = face.normal.clone();
  6048. } else {
  6049. face.__originalFaceNormal.copy( face.normal );
  6050. }
  6051. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  6052. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  6053. if ( ! face.__originalVertexNormals[ i ] ) {
  6054. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  6055. } else {
  6056. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  6057. }
  6058. }
  6059. }
  6060. // use temp geometry to compute face and vertex normals for each morph
  6061. var tmpGeo = new THREE.Geometry();
  6062. tmpGeo.faces = this.faces;
  6063. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  6064. // create on first access
  6065. if ( ! this.morphNormals[ i ] ) {
  6066. this.morphNormals[ i ] = {};
  6067. this.morphNormals[ i ].faceNormals = [];
  6068. this.morphNormals[ i ].vertexNormals = [];
  6069. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  6070. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  6071. var faceNormal, vertexNormals;
  6072. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6073. face = this.faces[ f ];
  6074. faceNormal = new THREE.Vector3();
  6075. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  6076. dstNormalsFace.push( faceNormal );
  6077. dstNormalsVertex.push( vertexNormals );
  6078. }
  6079. }
  6080. var morphNormals = this.morphNormals[ i ];
  6081. // set vertices to morph target
  6082. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  6083. // compute morph normals
  6084. tmpGeo.computeFaceNormals();
  6085. tmpGeo.computeVertexNormals();
  6086. // store morph normals
  6087. var faceNormal, vertexNormals;
  6088. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6089. face = this.faces[ f ];
  6090. faceNormal = morphNormals.faceNormals[ f ];
  6091. vertexNormals = morphNormals.vertexNormals[ f ];
  6092. faceNormal.copy( face.normal );
  6093. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  6094. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  6095. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  6096. }
  6097. }
  6098. // restore original normals
  6099. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6100. face = this.faces[ f ];
  6101. face.normal = face.__originalFaceNormal;
  6102. face.vertexNormals = face.__originalVertexNormals;
  6103. }
  6104. },
  6105. computeTangents: function () {
  6106. // based on http://www.terathon.com/code/tangent.html
  6107. // tangents go to vertices
  6108. var f, fl, v, vl, i, il, vertexIndex,
  6109. face, uv, vA, vB, vC, uvA, uvB, uvC,
  6110. x1, x2, y1, y2, z1, z2,
  6111. s1, s2, t1, t2, r, t, test,
  6112. tan1 = [], tan2 = [],
  6113. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  6114. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  6115. n = new THREE.Vector3(), w;
  6116. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6117. tan1[ v ] = new THREE.Vector3();
  6118. tan2[ v ] = new THREE.Vector3();
  6119. }
  6120. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  6121. vA = context.vertices[ a ];
  6122. vB = context.vertices[ b ];
  6123. vC = context.vertices[ c ];
  6124. uvA = uv[ ua ];
  6125. uvB = uv[ ub ];
  6126. uvC = uv[ uc ];
  6127. x1 = vB.x - vA.x;
  6128. x2 = vC.x - vA.x;
  6129. y1 = vB.y - vA.y;
  6130. y2 = vC.y - vA.y;
  6131. z1 = vB.z - vA.z;
  6132. z2 = vC.z - vA.z;
  6133. s1 = uvB.x - uvA.x;
  6134. s2 = uvC.x - uvA.x;
  6135. t1 = uvB.y - uvA.y;
  6136. t2 = uvC.y - uvA.y;
  6137. r = 1.0 / ( s1 * t2 - s2 * t1 );
  6138. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  6139. ( t2 * y1 - t1 * y2 ) * r,
  6140. ( t2 * z1 - t1 * z2 ) * r );
  6141. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  6142. ( s1 * y2 - s2 * y1 ) * r,
  6143. ( s1 * z2 - s2 * z1 ) * r );
  6144. tan1[ a ].add( sdir );
  6145. tan1[ b ].add( sdir );
  6146. tan1[ c ].add( sdir );
  6147. tan2[ a ].add( tdir );
  6148. tan2[ b ].add( tdir );
  6149. tan2[ c ].add( tdir );
  6150. }
  6151. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6152. face = this.faces[ f ];
  6153. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  6154. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  6155. }
  6156. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  6157. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6158. face = this.faces[ f ];
  6159. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  6160. n.copy( face.vertexNormals[ i ] );
  6161. vertexIndex = face[ faceIndex[ i ] ];
  6162. t = tan1[ vertexIndex ];
  6163. // Gram-Schmidt orthogonalize
  6164. tmp.copy( t );
  6165. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6166. // Calculate handedness
  6167. tmp2.crossVectors( face.vertexNormals[ i ], t );
  6168. test = tmp2.dot( tan2[ vertexIndex ] );
  6169. w = (test < 0.0) ? -1.0 : 1.0;
  6170. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  6171. }
  6172. }
  6173. this.hasTangents = true;
  6174. },
  6175. computeLineDistances: function ( ) {
  6176. var d = 0;
  6177. var vertices = this.vertices;
  6178. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6179. if ( i > 0 ) {
  6180. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6181. }
  6182. this.lineDistances[ i ] = d;
  6183. }
  6184. },
  6185. computeBoundingBox: function () {
  6186. if ( this.boundingBox === null ) {
  6187. this.boundingBox = new THREE.Box3();
  6188. }
  6189. this.boundingBox.setFromPoints( this.vertices );
  6190. },
  6191. computeBoundingSphere: function () {
  6192. if ( this.boundingSphere === null ) {
  6193. this.boundingSphere = new THREE.Sphere();
  6194. }
  6195. this.boundingSphere.setFromPoints( this.vertices );
  6196. },
  6197. /*
  6198. * Checks for duplicate vertices with hashmap.
  6199. * Duplicated vertices are removed
  6200. * and faces' vertices are updated.
  6201. */
  6202. mergeVertices: function () {
  6203. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6204. var unique = [], changes = [];
  6205. var v, key;
  6206. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6207. var precision = Math.pow( 10, precisionPoints );
  6208. var i,il, face;
  6209. var indices, k, j, jl, u;
  6210. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6211. v = this.vertices[ i ];
  6212. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6213. if ( verticesMap[ key ] === undefined ) {
  6214. verticesMap[ key ] = i;
  6215. unique.push( this.vertices[ i ] );
  6216. changes[ i ] = unique.length - 1;
  6217. } else {
  6218. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6219. changes[ i ] = changes[ verticesMap[ key ] ];
  6220. }
  6221. };
  6222. // if faces are completely degenerate after merging vertices, we
  6223. // have to remove them from the geometry.
  6224. var faceIndicesToRemove = [];
  6225. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  6226. face = this.faces[ i ];
  6227. face.a = changes[ face.a ];
  6228. face.b = changes[ face.b ];
  6229. face.c = changes[ face.c ];
  6230. indices = [ face.a, face.b, face.c ];
  6231. var dupIndex = -1;
  6232. // if any duplicate vertices are found in a Face3
  6233. // we have to remove the face as nothing can be saved
  6234. for ( var n = 0; n < 3; n ++ ) {
  6235. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6236. dupIndex = n;
  6237. faceIndicesToRemove.push( i );
  6238. break;
  6239. }
  6240. }
  6241. }
  6242. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6243. var idx = faceIndicesToRemove[ i ];
  6244. this.faces.splice( idx, 1 );
  6245. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6246. this.faceVertexUvs[ j ].splice( idx, 1 );
  6247. }
  6248. }
  6249. // Use unique set of vertices
  6250. var diff = this.vertices.length - unique.length;
  6251. this.vertices = unique;
  6252. return diff;
  6253. },
  6254. // Geometry splitting
  6255. makeGroups: ( function () {
  6256. var geometryGroupCounter = 0;
  6257. return function ( usesFaceMaterial, maxVerticesInGroup ) {
  6258. var f, fl, face, materialIndex,
  6259. groupHash, hash_map = {};
  6260. var numMorphTargets = this.morphTargets.length;
  6261. var numMorphNormals = this.morphNormals.length;
  6262. this.geometryGroups = {};
  6263. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6264. face = this.faces[ f ];
  6265. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  6266. if ( ! ( materialIndex in hash_map ) ) {
  6267. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  6268. }
  6269. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6270. if ( ! ( groupHash in this.geometryGroups ) ) {
  6271. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6272. }
  6273. if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  6274. hash_map[ materialIndex ].counter += 1;
  6275. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6276. if ( ! ( groupHash in this.geometryGroups ) ) {
  6277. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6278. }
  6279. }
  6280. this.geometryGroups[ groupHash ].faces3.push( f );
  6281. this.geometryGroups[ groupHash ].vertices += 3;
  6282. }
  6283. this.geometryGroupsList = [];
  6284. for ( var g in this.geometryGroups ) {
  6285. this.geometryGroups[ g ].id = geometryGroupCounter ++;
  6286. this.geometryGroupsList.push( this.geometryGroups[ g ] );
  6287. }
  6288. };
  6289. } )(),
  6290. clone: function () {
  6291. var geometry = new THREE.Geometry();
  6292. var vertices = this.vertices;
  6293. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6294. geometry.vertices.push( vertices[ i ].clone() );
  6295. }
  6296. var faces = this.faces;
  6297. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6298. geometry.faces.push( faces[ i ].clone() );
  6299. }
  6300. var uvs = this.faceVertexUvs[ 0 ];
  6301. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  6302. var uv = uvs[ i ], uvCopy = [];
  6303. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6304. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6305. }
  6306. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  6307. }
  6308. return geometry;
  6309. },
  6310. dispose: function () {
  6311. this.dispatchEvent( { type: 'dispose' } );
  6312. }
  6313. };
  6314. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6315. THREE.GeometryIdCount = 0;
  6316. /**
  6317. * @author mrdoob / http://mrdoob.com/
  6318. * @author mikael emtinger / http://gomo.se/
  6319. * @author WestLangley / http://github.com/WestLangley
  6320. */
  6321. THREE.Camera = function () {
  6322. THREE.Object3D.call( this );
  6323. this.matrixWorldInverse = new THREE.Matrix4();
  6324. this.projectionMatrix = new THREE.Matrix4();
  6325. };
  6326. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6327. THREE.Camera.prototype.lookAt = function () {
  6328. // This routine does not support cameras with rotated and/or translated parent(s)
  6329. var m1 = new THREE.Matrix4();
  6330. return function ( vector ) {
  6331. m1.lookAt( this.position, vector, this.up );
  6332. this.quaternion.setFromRotationMatrix( m1 );
  6333. };
  6334. }();
  6335. THREE.Camera.prototype.clone = function (camera) {
  6336. if ( camera === undefined ) camera = new THREE.Camera();
  6337. THREE.Object3D.prototype.clone.call( this, camera );
  6338. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6339. camera.projectionMatrix.copy( this.projectionMatrix );
  6340. return camera;
  6341. };
  6342. /**
  6343. * @author alteredq / http://alteredqualia.com/
  6344. */
  6345. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6346. THREE.Camera.call( this );
  6347. this.left = left;
  6348. this.right = right;
  6349. this.top = top;
  6350. this.bottom = bottom;
  6351. this.near = ( near !== undefined ) ? near : 0.1;
  6352. this.far = ( far !== undefined ) ? far : 2000;
  6353. this.updateProjectionMatrix();
  6354. };
  6355. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6356. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6357. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6358. };
  6359. THREE.OrthographicCamera.prototype.clone = function () {
  6360. var camera = new THREE.OrthographicCamera();
  6361. THREE.Camera.prototype.clone.call( this, camera );
  6362. camera.left = this.left;
  6363. camera.right = this.right;
  6364. camera.top = this.top;
  6365. camera.bottom = this.bottom;
  6366. camera.near = this.near;
  6367. camera.far = this.far;
  6368. return camera;
  6369. };
  6370. /**
  6371. * @author mrdoob / http://mrdoob.com/
  6372. * @author greggman / http://games.greggman.com/
  6373. * @author zz85 / http://www.lab4games.net/zz85/blog
  6374. */
  6375. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6376. THREE.Camera.call( this );
  6377. this.fov = fov !== undefined ? fov : 50;
  6378. this.aspect = aspect !== undefined ? aspect : 1;
  6379. this.near = near !== undefined ? near : 0.1;
  6380. this.far = far !== undefined ? far : 2000;
  6381. this.updateProjectionMatrix();
  6382. };
  6383. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6384. /**
  6385. * Uses Focal Length (in mm) to estimate and set FOV
  6386. * 35mm (fullframe) camera is used if frame size is not specified;
  6387. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6388. */
  6389. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6390. if ( frameHeight === undefined ) frameHeight = 24;
  6391. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6392. this.updateProjectionMatrix();
  6393. }
  6394. /**
  6395. * Sets an offset in a larger frustum. This is useful for multi-window or
  6396. * multi-monitor/multi-machine setups.
  6397. *
  6398. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6399. * the monitors are in grid like this
  6400. *
  6401. * +---+---+---+
  6402. * | A | B | C |
  6403. * +---+---+---+
  6404. * | D | E | F |
  6405. * +---+---+---+
  6406. *
  6407. * then for each monitor you would call it like this
  6408. *
  6409. * var w = 1920;
  6410. * var h = 1080;
  6411. * var fullWidth = w * 3;
  6412. * var fullHeight = h * 2;
  6413. *
  6414. * --A--
  6415. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6416. * --B--
  6417. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6418. * --C--
  6419. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6420. * --D--
  6421. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6422. * --E--
  6423. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6424. * --F--
  6425. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6426. *
  6427. * Note there is no reason monitors have to be the same size or in a grid.
  6428. */
  6429. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6430. this.fullWidth = fullWidth;
  6431. this.fullHeight = fullHeight;
  6432. this.x = x;
  6433. this.y = y;
  6434. this.width = width;
  6435. this.height = height;
  6436. this.updateProjectionMatrix();
  6437. };
  6438. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6439. if ( this.fullWidth ) {
  6440. var aspect = this.fullWidth / this.fullHeight;
  6441. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6442. var bottom = -top;
  6443. var left = aspect * bottom;
  6444. var right = aspect * top;
  6445. var width = Math.abs( right - left );
  6446. var height = Math.abs( top - bottom );
  6447. this.projectionMatrix.makeFrustum(
  6448. left + this.x * width / this.fullWidth,
  6449. left + ( this.x + this.width ) * width / this.fullWidth,
  6450. top - ( this.y + this.height ) * height / this.fullHeight,
  6451. top - this.y * height / this.fullHeight,
  6452. this.near,
  6453. this.far
  6454. );
  6455. } else {
  6456. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6457. }
  6458. };
  6459. THREE.PerspectiveCamera.prototype.clone = function () {
  6460. var camera = new THREE.PerspectiveCamera();
  6461. THREE.Camera.prototype.clone.call( this, camera );
  6462. camera.fov = this.fov;
  6463. camera.aspect = this.aspect;
  6464. camera.near = this.near;
  6465. camera.far = this.far;
  6466. return camera;
  6467. };
  6468. /**
  6469. * @author mrdoob / http://mrdoob.com/
  6470. * @author alteredq / http://alteredqualia.com/
  6471. */
  6472. THREE.Light = function ( color ) {
  6473. THREE.Object3D.call( this );
  6474. this.color = new THREE.Color( color );
  6475. };
  6476. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6477. THREE.Light.prototype.clone = function ( light ) {
  6478. if ( light === undefined ) light = new THREE.Light();
  6479. THREE.Object3D.prototype.clone.call( this, light );
  6480. light.color.copy( this.color );
  6481. return light;
  6482. };
  6483. /**
  6484. * @author mrdoob / http://mrdoob.com/
  6485. */
  6486. THREE.AmbientLight = function ( color ) {
  6487. THREE.Light.call( this, color );
  6488. };
  6489. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6490. THREE.AmbientLight.prototype.clone = function () {
  6491. var light = new THREE.AmbientLight();
  6492. THREE.Light.prototype.clone.call( this, light );
  6493. return light;
  6494. };
  6495. /**
  6496. * @author MPanknin / http://www.redplant.de/
  6497. * @author alteredq / http://alteredqualia.com/
  6498. */
  6499. THREE.AreaLight = function ( color, intensity ) {
  6500. THREE.Light.call( this, color );
  6501. this.normal = new THREE.Vector3( 0, -1, 0 );
  6502. this.right = new THREE.Vector3( 1, 0, 0 );
  6503. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6504. this.width = 1.0;
  6505. this.height = 1.0;
  6506. this.constantAttenuation = 1.5;
  6507. this.linearAttenuation = 0.5;
  6508. this.quadraticAttenuation = 0.1;
  6509. };
  6510. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6511. /**
  6512. * @author mrdoob / http://mrdoob.com/
  6513. * @author alteredq / http://alteredqualia.com/
  6514. */
  6515. THREE.DirectionalLight = function ( color, intensity ) {
  6516. THREE.Light.call( this, color );
  6517. this.position.set( 0, 1, 0 );
  6518. this.target = new THREE.Object3D();
  6519. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6520. this.castShadow = false;
  6521. this.onlyShadow = false;
  6522. //
  6523. this.shadowCameraNear = 50;
  6524. this.shadowCameraFar = 5000;
  6525. this.shadowCameraLeft = -500;
  6526. this.shadowCameraRight = 500;
  6527. this.shadowCameraTop = 500;
  6528. this.shadowCameraBottom = -500;
  6529. this.shadowCameraVisible = false;
  6530. this.shadowBias = 0;
  6531. this.shadowDarkness = 0.5;
  6532. this.shadowMapWidth = 512;
  6533. this.shadowMapHeight = 512;
  6534. //
  6535. this.shadowCascade = false;
  6536. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6537. this.shadowCascadeCount = 2;
  6538. this.shadowCascadeBias = [ 0, 0, 0 ];
  6539. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6540. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6541. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6542. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6543. this.shadowCascadeArray = [];
  6544. //
  6545. this.shadowMap = null;
  6546. this.shadowMapSize = null;
  6547. this.shadowCamera = null;
  6548. this.shadowMatrix = null;
  6549. };
  6550. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6551. THREE.DirectionalLight.prototype.clone = function () {
  6552. var light = new THREE.DirectionalLight();
  6553. THREE.Light.prototype.clone.call( this, light );
  6554. light.target = this.target.clone();
  6555. light.intensity = this.intensity;
  6556. light.castShadow = this.castShadow;
  6557. light.onlyShadow = this.onlyShadow;
  6558. //
  6559. light.shadowCameraNear = this.shadowCameraNear;
  6560. light.shadowCameraFar = this.shadowCameraFar;
  6561. light.shadowCameraLeft = this.shadowCameraLeft;
  6562. light.shadowCameraRight = this.shadowCameraRight;
  6563. light.shadowCameraTop = this.shadowCameraTop;
  6564. light.shadowCameraBottom = this.shadowCameraBottom;
  6565. light.shadowCameraVisible = this.shadowCameraVisible;
  6566. light.shadowBias = this.shadowBias;
  6567. light.shadowDarkness = this.shadowDarkness;
  6568. light.shadowMapWidth = this.shadowMapWidth;
  6569. light.shadowMapHeight = this.shadowMapHeight;
  6570. //
  6571. light.shadowCascade = this.shadowCascade;
  6572. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6573. light.shadowCascadeCount = this.shadowCascadeCount;
  6574. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6575. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6576. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6577. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6578. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6579. return light;
  6580. };
  6581. /**
  6582. * @author alteredq / http://alteredqualia.com/
  6583. */
  6584. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6585. THREE.Light.call( this, skyColor );
  6586. this.position.set( 0, 100, 0 );
  6587. this.groundColor = new THREE.Color( groundColor );
  6588. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6589. };
  6590. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6591. THREE.HemisphereLight.prototype.clone = function () {
  6592. var light = new THREE.HemisphereLight();
  6593. THREE.Light.prototype.clone.call( this, light );
  6594. light.groundColor.copy( this.groundColor );
  6595. light.intensity = this.intensity;
  6596. return light;
  6597. };
  6598. /**
  6599. * @author mrdoob / http://mrdoob.com/
  6600. */
  6601. THREE.PointLight = function ( color, intensity, distance ) {
  6602. THREE.Light.call( this, color );
  6603. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6604. this.distance = ( distance !== undefined ) ? distance : 0;
  6605. };
  6606. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6607. THREE.PointLight.prototype.clone = function () {
  6608. var light = new THREE.PointLight();
  6609. THREE.Light.prototype.clone.call( this, light );
  6610. light.intensity = this.intensity;
  6611. light.distance = this.distance;
  6612. return light;
  6613. };
  6614. /**
  6615. * @author alteredq / http://alteredqualia.com/
  6616. */
  6617. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6618. THREE.Light.call( this, color );
  6619. this.position.set( 0, 1, 0 );
  6620. this.target = new THREE.Object3D();
  6621. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6622. this.distance = ( distance !== undefined ) ? distance : 0;
  6623. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6624. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6625. this.castShadow = false;
  6626. this.onlyShadow = false;
  6627. //
  6628. this.shadowCameraNear = 50;
  6629. this.shadowCameraFar = 5000;
  6630. this.shadowCameraFov = 50;
  6631. this.shadowCameraVisible = false;
  6632. this.shadowBias = 0;
  6633. this.shadowDarkness = 0.5;
  6634. this.shadowMapWidth = 512;
  6635. this.shadowMapHeight = 512;
  6636. //
  6637. this.shadowMap = null;
  6638. this.shadowMapSize = null;
  6639. this.shadowCamera = null;
  6640. this.shadowMatrix = null;
  6641. };
  6642. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6643. THREE.SpotLight.prototype.clone = function () {
  6644. var light = new THREE.SpotLight();
  6645. THREE.Light.prototype.clone.call( this, light );
  6646. light.target = this.target.clone();
  6647. light.intensity = this.intensity;
  6648. light.distance = this.distance;
  6649. light.angle = this.angle;
  6650. light.exponent = this.exponent;
  6651. light.castShadow = this.castShadow;
  6652. light.onlyShadow = this.onlyShadow;
  6653. //
  6654. light.shadowCameraNear = this.shadowCameraNear;
  6655. light.shadowCameraFar = this.shadowCameraFar;
  6656. light.shadowCameraFov = this.shadowCameraFov;
  6657. light.shadowCameraVisible = this.shadowCameraVisible;
  6658. light.shadowBias = this.shadowBias;
  6659. light.shadowDarkness = this.shadowDarkness;
  6660. light.shadowMapWidth = this.shadowMapWidth;
  6661. light.shadowMapHeight = this.shadowMapHeight;
  6662. return light;
  6663. };
  6664. /**
  6665. * @author mrdoob / http://mrdoob.com/
  6666. */
  6667. THREE.Cache = function () {
  6668. this.files = {};
  6669. };
  6670. THREE.Cache.prototype = {
  6671. constructor: THREE.Cache,
  6672. add: function ( key, file ) {
  6673. // console.log( 'THREE.Cache', 'Adding key:', key );
  6674. this.files[ key ] = file;
  6675. },
  6676. get: function ( key ) {
  6677. // console.log( 'THREE.Cache', 'Checking key:', key );
  6678. return this.files[ key ];
  6679. },
  6680. remove: function ( key ) {
  6681. delete this.files[ key ];
  6682. },
  6683. clear: function () {
  6684. this.files = {}
  6685. }
  6686. };
  6687. /**
  6688. * @author alteredq / http://alteredqualia.com/
  6689. */
  6690. THREE.Loader = function ( showStatus ) {
  6691. this.showStatus = showStatus;
  6692. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6693. this.imageLoader = new THREE.ImageLoader();
  6694. this.onLoadStart = function () {};
  6695. this.onLoadProgress = function () {};
  6696. this.onLoadComplete = function () {};
  6697. };
  6698. THREE.Loader.prototype = {
  6699. constructor: THREE.Loader,
  6700. crossOrigin: undefined,
  6701. addStatusElement: function () {
  6702. var e = document.createElement( "div" );
  6703. e.style.position = "absolute";
  6704. e.style.right = "0px";
  6705. e.style.top = "0px";
  6706. e.style.fontSize = "0.8em";
  6707. e.style.textAlign = "left";
  6708. e.style.background = "rgba(0,0,0,0.25)";
  6709. e.style.color = "#fff";
  6710. e.style.width = "120px";
  6711. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6712. e.style.zIndex = 1000;
  6713. e.innerHTML = "Loading ...";
  6714. return e;
  6715. },
  6716. updateProgress: function ( progress ) {
  6717. var message = "Loaded ";
  6718. if ( progress.total ) {
  6719. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6720. } else {
  6721. message += ( progress.loaded / 1024 ).toFixed(2) + " KB";
  6722. }
  6723. this.statusDomElement.innerHTML = message;
  6724. },
  6725. extractUrlBase: function ( url ) {
  6726. var parts = url.split( '/' );
  6727. if ( parts.length === 1 ) return './';
  6728. parts.pop();
  6729. return parts.join( '/' ) + '/';
  6730. },
  6731. initMaterials: function ( materials, texturePath ) {
  6732. var array = [];
  6733. for ( var i = 0; i < materials.length; ++ i ) {
  6734. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6735. }
  6736. return array;
  6737. },
  6738. needsTangents: function ( materials ) {
  6739. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6740. var m = materials[ i ];
  6741. if ( m instanceof THREE.ShaderMaterial ) return true;
  6742. }
  6743. return false;
  6744. },
  6745. createMaterial: function ( m, texturePath ) {
  6746. var scope = this;
  6747. function nearest_pow2( n ) {
  6748. var l = Math.log( n ) / Math.LN2;
  6749. return Math.pow( 2, Math.round( l ) );
  6750. }
  6751. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6752. var isCompressed = /\.dds$/i.test( sourceFile );
  6753. var fullPath = texturePath + sourceFile;
  6754. if ( isCompressed ) {
  6755. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6756. where[ name ] = texture;
  6757. } else {
  6758. var texture = document.createElement( 'canvas' );
  6759. where[ name ] = new THREE.Texture( texture );
  6760. }
  6761. where[ name ].sourceFile = sourceFile;
  6762. if( repeat ) {
  6763. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6764. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6765. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6766. }
  6767. if ( offset ) {
  6768. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6769. }
  6770. if ( wrap ) {
  6771. var wrapMap = {
  6772. "repeat": THREE.RepeatWrapping,
  6773. "mirror": THREE.MirroredRepeatWrapping
  6774. }
  6775. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6776. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6777. }
  6778. if ( anisotropy ) {
  6779. where[ name ].anisotropy = anisotropy;
  6780. }
  6781. if ( ! isCompressed ) {
  6782. var texture = where[ name ];
  6783. scope.imageLoader.crossOrigin = scope.crossOrigin;
  6784. scope.imageLoader.load( fullPath, function ( image ) {
  6785. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  6786. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  6787. var width = nearest_pow2( image.width );
  6788. var height = nearest_pow2( image.height );
  6789. texture.image.width = width;
  6790. texture.image.height = height;
  6791. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  6792. } else {
  6793. texture.image = image;
  6794. }
  6795. texture.needsUpdate = true;
  6796. } );
  6797. }
  6798. }
  6799. function rgb2hex( rgb ) {
  6800. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6801. }
  6802. // defaults
  6803. var mtype = "MeshLambertMaterial";
  6804. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6805. // parameters from model file
  6806. if ( m.shading ) {
  6807. var shading = m.shading.toLowerCase();
  6808. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6809. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6810. }
  6811. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6812. mpars.blending = THREE[ m.blending ];
  6813. }
  6814. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6815. mpars.transparent = m.transparent;
  6816. }
  6817. if ( m.depthTest !== undefined ) {
  6818. mpars.depthTest = m.depthTest;
  6819. }
  6820. if ( m.depthWrite !== undefined ) {
  6821. mpars.depthWrite = m.depthWrite;
  6822. }
  6823. if ( m.visible !== undefined ) {
  6824. mpars.visible = m.visible;
  6825. }
  6826. if ( m.flipSided !== undefined ) {
  6827. mpars.side = THREE.BackSide;
  6828. }
  6829. if ( m.doubleSided !== undefined ) {
  6830. mpars.side = THREE.DoubleSide;
  6831. }
  6832. if ( m.wireframe !== undefined ) {
  6833. mpars.wireframe = m.wireframe;
  6834. }
  6835. if ( m.vertexColors !== undefined ) {
  6836. if ( m.vertexColors === "face" ) {
  6837. mpars.vertexColors = THREE.FaceColors;
  6838. } else if ( m.vertexColors ) {
  6839. mpars.vertexColors = THREE.VertexColors;
  6840. }
  6841. }
  6842. // colors
  6843. if ( m.colorDiffuse ) {
  6844. mpars.color = rgb2hex( m.colorDiffuse );
  6845. } else if ( m.DbgColor ) {
  6846. mpars.color = m.DbgColor;
  6847. }
  6848. if ( m.colorSpecular ) {
  6849. mpars.specular = rgb2hex( m.colorSpecular );
  6850. }
  6851. if ( m.colorAmbient ) {
  6852. mpars.ambient = rgb2hex( m.colorAmbient );
  6853. }
  6854. // modifiers
  6855. if ( m.transparency ) {
  6856. mpars.opacity = m.transparency;
  6857. }
  6858. if ( m.specularCoef ) {
  6859. mpars.shininess = m.specularCoef;
  6860. }
  6861. // textures
  6862. if ( m.mapDiffuse && texturePath ) {
  6863. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6864. }
  6865. if ( m.mapLight && texturePath ) {
  6866. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6867. }
  6868. if ( m.mapBump && texturePath ) {
  6869. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6870. }
  6871. if ( m.mapNormal && texturePath ) {
  6872. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6873. }
  6874. if ( m.mapSpecular && texturePath ) {
  6875. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6876. }
  6877. //
  6878. if ( m.mapBumpScale ) {
  6879. mpars.bumpScale = m.mapBumpScale;
  6880. }
  6881. // special case for normal mapped material
  6882. if ( m.mapNormal ) {
  6883. var shader = THREE.ShaderLib[ "normalmap" ];
  6884. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6885. uniforms[ "tNormal" ].value = mpars.normalMap;
  6886. if ( m.mapNormalFactor ) {
  6887. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6888. }
  6889. if ( mpars.map ) {
  6890. uniforms[ "tDiffuse" ].value = mpars.map;
  6891. uniforms[ "enableDiffuse" ].value = true;
  6892. }
  6893. if ( mpars.specularMap ) {
  6894. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6895. uniforms[ "enableSpecular" ].value = true;
  6896. }
  6897. if ( mpars.lightMap ) {
  6898. uniforms[ "tAO" ].value = mpars.lightMap;
  6899. uniforms[ "enableAO" ].value = true;
  6900. }
  6901. // for the moment don't handle displacement texture
  6902. uniforms[ "diffuse" ].value.setHex( mpars.color );
  6903. uniforms[ "specular" ].value.setHex( mpars.specular );
  6904. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  6905. uniforms[ "shininess" ].value = mpars.shininess;
  6906. if ( mpars.opacity !== undefined ) {
  6907. uniforms[ "opacity" ].value = mpars.opacity;
  6908. }
  6909. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6910. var material = new THREE.ShaderMaterial( parameters );
  6911. if ( mpars.transparent ) {
  6912. material.transparent = true;
  6913. }
  6914. } else {
  6915. var material = new THREE[ mtype ]( mpars );
  6916. }
  6917. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6918. return material;
  6919. }
  6920. };
  6921. /**
  6922. * @author mrdoob / http://mrdoob.com/
  6923. */
  6924. THREE.XHRLoader = function ( manager ) {
  6925. this.cache = new THREE.Cache();
  6926. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6927. };
  6928. THREE.XHRLoader.prototype = {
  6929. constructor: THREE.XHRLoader,
  6930. load: function ( url, onLoad, onProgress, onError ) {
  6931. var scope = this;
  6932. var cached = scope.cache.get( url );
  6933. if ( cached !== undefined ) {
  6934. onLoad( cached );
  6935. return;
  6936. }
  6937. var request = new XMLHttpRequest();
  6938. if ( onLoad !== undefined ) {
  6939. request.addEventListener( 'load', function ( event ) {
  6940. scope.cache.add( url, event.target.responseText );
  6941. onLoad( event.target.responseText );
  6942. scope.manager.itemEnd( url );
  6943. }, false );
  6944. }
  6945. if ( onProgress !== undefined ) {
  6946. request.addEventListener( 'progress', function ( event ) {
  6947. onProgress( event );
  6948. }, false );
  6949. }
  6950. if ( onError !== undefined ) {
  6951. request.addEventListener( 'error', function ( event ) {
  6952. onError( event );
  6953. }, false );
  6954. }
  6955. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6956. request.open( 'GET', url, true );
  6957. request.send( null );
  6958. scope.manager.itemStart( url );
  6959. },
  6960. setCrossOrigin: function ( value ) {
  6961. this.crossOrigin = value;
  6962. }
  6963. };
  6964. /**
  6965. * @author mrdoob / http://mrdoob.com/
  6966. */
  6967. THREE.ImageLoader = function ( manager ) {
  6968. this.cache = new THREE.Cache();
  6969. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6970. };
  6971. THREE.ImageLoader.prototype = {
  6972. constructor: THREE.ImageLoader,
  6973. load: function ( url, onLoad, onProgress, onError ) {
  6974. var scope = this;
  6975. var cached = scope.cache.get( url );
  6976. if ( cached !== undefined ) {
  6977. onLoad( cached );
  6978. return;
  6979. }
  6980. var image = document.createElement( 'img' );
  6981. if ( onLoad !== undefined ) {
  6982. image.addEventListener( 'load', function ( event ) {
  6983. scope.cache.add( url, this );
  6984. onLoad( this );
  6985. scope.manager.itemEnd( url );
  6986. }, false );
  6987. }
  6988. if ( onProgress !== undefined ) {
  6989. image.addEventListener( 'progress', function ( event ) {
  6990. onProgress( event );
  6991. }, false );
  6992. }
  6993. if ( onError !== undefined ) {
  6994. image.addEventListener( 'error', function ( event ) {
  6995. onError( event );
  6996. }, false );
  6997. }
  6998. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6999. image.src = url;
  7000. scope.manager.itemStart( url );
  7001. return image;
  7002. },
  7003. setCrossOrigin: function ( value ) {
  7004. this.crossOrigin = value;
  7005. }
  7006. }
  7007. /**
  7008. * @author mrdoob / http://mrdoob.com/
  7009. * @author alteredq / http://alteredqualia.com/
  7010. */
  7011. THREE.JSONLoader = function ( showStatus ) {
  7012. THREE.Loader.call( this, showStatus );
  7013. this.withCredentials = false;
  7014. };
  7015. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7016. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7017. var scope = this;
  7018. // todo: unify load API to for easier SceneLoader use
  7019. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  7020. this.onLoadStart();
  7021. this.loadAjaxJSON( this, url, callback, texturePath );
  7022. };
  7023. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7024. var xhr = new XMLHttpRequest();
  7025. var length = 0;
  7026. xhr.onreadystatechange = function () {
  7027. if ( xhr.readyState === xhr.DONE ) {
  7028. if ( xhr.status === 200 || xhr.status === 0 ) {
  7029. if ( xhr.responseText ) {
  7030. var json = JSON.parse( xhr.responseText );
  7031. if ( json.metadata !== undefined && json.metadata.type === 'scene' ) {
  7032. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  7033. return;
  7034. }
  7035. var result = context.parse( json, texturePath );
  7036. callback( result.geometry, result.materials );
  7037. } else {
  7038. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  7039. }
  7040. // in context of more complex asset initialization
  7041. // do not block on single failed file
  7042. // maybe should go even one more level up
  7043. context.onLoadComplete();
  7044. } else {
  7045. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  7046. }
  7047. } else if ( xhr.readyState === xhr.LOADING ) {
  7048. if ( callbackProgress ) {
  7049. if ( length === 0 ) {
  7050. length = xhr.getResponseHeader( 'Content-Length' );
  7051. }
  7052. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7053. }
  7054. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7055. if ( callbackProgress !== undefined ) {
  7056. length = xhr.getResponseHeader( "Content-Length" );
  7057. }
  7058. }
  7059. };
  7060. xhr.open( "GET", url, true );
  7061. xhr.withCredentials = this.withCredentials;
  7062. xhr.send( null );
  7063. };
  7064. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7065. var scope = this,
  7066. geometry = new THREE.Geometry(),
  7067. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7068. parseModel( scale );
  7069. parseSkin();
  7070. parseMorphing( scale );
  7071. geometry.computeFaceNormals();
  7072. geometry.computeBoundingSphere();
  7073. function parseModel( scale ) {
  7074. function isBitSet( value, position ) {
  7075. return value & ( 1 << position );
  7076. }
  7077. var i, j, fi,
  7078. offset, zLength,
  7079. colorIndex, normalIndex, uvIndex, materialIndex,
  7080. type,
  7081. isQuad,
  7082. hasMaterial,
  7083. hasFaceVertexUv,
  7084. hasFaceNormal, hasFaceVertexNormal,
  7085. hasFaceColor, hasFaceVertexColor,
  7086. vertex, face, faceA, faceB, color, hex, normal,
  7087. uvLayer, uv, u, v,
  7088. faces = json.faces,
  7089. vertices = json.vertices,
  7090. normals = json.normals,
  7091. colors = json.colors,
  7092. nUvLayers = 0;
  7093. if ( json.uvs !== undefined ) {
  7094. // disregard empty arrays
  7095. for ( i = 0; i < json.uvs.length; i++ ) {
  7096. if ( json.uvs[ i ].length ) nUvLayers ++;
  7097. }
  7098. for ( i = 0; i < nUvLayers; i++ ) {
  7099. geometry.faceVertexUvs[ i ] = [];
  7100. }
  7101. }
  7102. offset = 0;
  7103. zLength = vertices.length;
  7104. while ( offset < zLength ) {
  7105. vertex = new THREE.Vector3();
  7106. vertex.x = vertices[ offset ++ ] * scale;
  7107. vertex.y = vertices[ offset ++ ] * scale;
  7108. vertex.z = vertices[ offset ++ ] * scale;
  7109. geometry.vertices.push( vertex );
  7110. }
  7111. offset = 0;
  7112. zLength = faces.length;
  7113. while ( offset < zLength ) {
  7114. type = faces[ offset ++ ];
  7115. isQuad = isBitSet( type, 0 );
  7116. hasMaterial = isBitSet( type, 1 );
  7117. hasFaceVertexUv = isBitSet( type, 3 );
  7118. hasFaceNormal = isBitSet( type, 4 );
  7119. hasFaceVertexNormal = isBitSet( type, 5 );
  7120. hasFaceColor = isBitSet( type, 6 );
  7121. hasFaceVertexColor = isBitSet( type, 7 );
  7122. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7123. if ( isQuad ) {
  7124. faceA = new THREE.Face3();
  7125. faceA.a = faces[ offset ];
  7126. faceA.b = faces[ offset + 1 ];
  7127. faceA.c = faces[ offset + 3 ];
  7128. faceB = new THREE.Face3();
  7129. faceB.a = faces[ offset + 1 ];
  7130. faceB.b = faces[ offset + 2 ];
  7131. faceB.c = faces[ offset + 3 ];
  7132. offset += 4;
  7133. if ( hasMaterial ) {
  7134. materialIndex = faces[ offset ++ ];
  7135. faceA.materialIndex = materialIndex;
  7136. faceB.materialIndex = materialIndex;
  7137. }
  7138. // to get face <=> uv index correspondence
  7139. fi = geometry.faces.length;
  7140. if ( hasFaceVertexUv ) {
  7141. for ( i = 0; i < nUvLayers; i++ ) {
  7142. uvLayer = json.uvs[ i ];
  7143. geometry.faceVertexUvs[ i ][ fi ] = [];
  7144. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7145. for ( j = 0; j < 4; j ++ ) {
  7146. uvIndex = faces[ offset ++ ];
  7147. u = uvLayer[ uvIndex * 2 ];
  7148. v = uvLayer[ uvIndex * 2 + 1 ];
  7149. uv = new THREE.Vector2( u, v );
  7150. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7151. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7152. }
  7153. }
  7154. }
  7155. if ( hasFaceNormal ) {
  7156. normalIndex = faces[ offset ++ ] * 3;
  7157. faceA.normal.set(
  7158. normals[ normalIndex ++ ],
  7159. normals[ normalIndex ++ ],
  7160. normals[ normalIndex ]
  7161. );
  7162. faceB.normal.copy( faceA.normal );
  7163. }
  7164. if ( hasFaceVertexNormal ) {
  7165. for ( i = 0; i < 4; i++ ) {
  7166. normalIndex = faces[ offset ++ ] * 3;
  7167. normal = new THREE.Vector3(
  7168. normals[ normalIndex ++ ],
  7169. normals[ normalIndex ++ ],
  7170. normals[ normalIndex ]
  7171. );
  7172. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7173. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7174. }
  7175. }
  7176. if ( hasFaceColor ) {
  7177. colorIndex = faces[ offset ++ ];
  7178. hex = colors[ colorIndex ];
  7179. faceA.color.setHex( hex );
  7180. faceB.color.setHex( hex );
  7181. }
  7182. if ( hasFaceVertexColor ) {
  7183. for ( i = 0; i < 4; i++ ) {
  7184. colorIndex = faces[ offset ++ ];
  7185. hex = colors[ colorIndex ];
  7186. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7187. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7188. }
  7189. }
  7190. geometry.faces.push( faceA );
  7191. geometry.faces.push( faceB );
  7192. } else {
  7193. face = new THREE.Face3();
  7194. face.a = faces[ offset ++ ];
  7195. face.b = faces[ offset ++ ];
  7196. face.c = faces[ offset ++ ];
  7197. if ( hasMaterial ) {
  7198. materialIndex = faces[ offset ++ ];
  7199. face.materialIndex = materialIndex;
  7200. }
  7201. // to get face <=> uv index correspondence
  7202. fi = geometry.faces.length;
  7203. if ( hasFaceVertexUv ) {
  7204. for ( i = 0; i < nUvLayers; i++ ) {
  7205. uvLayer = json.uvs[ i ];
  7206. geometry.faceVertexUvs[ i ][ fi ] = [];
  7207. for ( j = 0; j < 3; j ++ ) {
  7208. uvIndex = faces[ offset ++ ];
  7209. u = uvLayer[ uvIndex * 2 ];
  7210. v = uvLayer[ uvIndex * 2 + 1 ];
  7211. uv = new THREE.Vector2( u, v );
  7212. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7213. }
  7214. }
  7215. }
  7216. if ( hasFaceNormal ) {
  7217. normalIndex = faces[ offset ++ ] * 3;
  7218. face.normal.set(
  7219. normals[ normalIndex ++ ],
  7220. normals[ normalIndex ++ ],
  7221. normals[ normalIndex ]
  7222. );
  7223. }
  7224. if ( hasFaceVertexNormal ) {
  7225. for ( i = 0; i < 3; i++ ) {
  7226. normalIndex = faces[ offset ++ ] * 3;
  7227. normal = new THREE.Vector3(
  7228. normals[ normalIndex ++ ],
  7229. normals[ normalIndex ++ ],
  7230. normals[ normalIndex ]
  7231. );
  7232. face.vertexNormals.push( normal );
  7233. }
  7234. }
  7235. if ( hasFaceColor ) {
  7236. colorIndex = faces[ offset ++ ];
  7237. face.color.setHex( colors[ colorIndex ] );
  7238. }
  7239. if ( hasFaceVertexColor ) {
  7240. for ( i = 0; i < 3; i++ ) {
  7241. colorIndex = faces[ offset ++ ];
  7242. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7243. }
  7244. }
  7245. geometry.faces.push( face );
  7246. }
  7247. }
  7248. };
  7249. function parseSkin() {
  7250. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7251. if ( json.skinWeights ) {
  7252. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7253. var x = json.skinWeights[ i ];
  7254. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7255. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7256. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7257. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7258. }
  7259. }
  7260. if ( json.skinIndices ) {
  7261. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7262. var a = json.skinIndices[ i ];
  7263. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7264. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7265. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7266. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7267. }
  7268. }
  7269. geometry.bones = json.bones;
  7270. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7271. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7272. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7273. }
  7274. // could change this to json.animations[0] or remove completely
  7275. geometry.animation = json.animation;
  7276. geometry.animations = json.animations;
  7277. };
  7278. function parseMorphing( scale ) {
  7279. if ( json.morphTargets !== undefined ) {
  7280. var i, l, v, vl, dstVertices, srcVertices;
  7281. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7282. geometry.morphTargets[ i ] = {};
  7283. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7284. geometry.morphTargets[ i ].vertices = [];
  7285. dstVertices = geometry.morphTargets[ i ].vertices;
  7286. srcVertices = json.morphTargets [ i ].vertices;
  7287. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7288. var vertex = new THREE.Vector3();
  7289. vertex.x = srcVertices[ v ] * scale;
  7290. vertex.y = srcVertices[ v + 1 ] * scale;
  7291. vertex.z = srcVertices[ v + 2 ] * scale;
  7292. dstVertices.push( vertex );
  7293. }
  7294. }
  7295. }
  7296. if ( json.morphColors !== undefined ) {
  7297. var i, l, c, cl, dstColors, srcColors, color;
  7298. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  7299. geometry.morphColors[ i ] = {};
  7300. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7301. geometry.morphColors[ i ].colors = [];
  7302. dstColors = geometry.morphColors[ i ].colors;
  7303. srcColors = json.morphColors [ i ].colors;
  7304. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7305. color = new THREE.Color( 0xffaa00 );
  7306. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7307. dstColors.push( color );
  7308. }
  7309. }
  7310. }
  7311. };
  7312. if ( json.materials === undefined || json.materials.length === 0 ) {
  7313. return { geometry: geometry };
  7314. } else {
  7315. var materials = this.initMaterials( json.materials, texturePath );
  7316. if ( this.needsTangents( materials ) ) {
  7317. geometry.computeTangents();
  7318. }
  7319. return { geometry: geometry, materials: materials };
  7320. }
  7321. };
  7322. /**
  7323. * @author mrdoob / http://mrdoob.com/
  7324. */
  7325. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7326. var scope = this;
  7327. var loaded = 0, total = 0;
  7328. this.onLoad = onLoad;
  7329. this.onProgress = onProgress;
  7330. this.onError = onError;
  7331. this.itemStart = function ( url ) {
  7332. total ++;
  7333. };
  7334. this.itemEnd = function ( url ) {
  7335. loaded ++;
  7336. if ( scope.onProgress !== undefined ) {
  7337. scope.onProgress( url, loaded, total );
  7338. }
  7339. if ( loaded === total && scope.onLoad !== undefined ) {
  7340. scope.onLoad();
  7341. }
  7342. };
  7343. };
  7344. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7345. /**
  7346. * @author mrdoob / http://mrdoob.com/
  7347. */
  7348. THREE.BufferGeometryLoader = function ( manager ) {
  7349. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7350. };
  7351. THREE.BufferGeometryLoader.prototype = {
  7352. constructor: THREE.BufferGeometryLoader,
  7353. load: function ( url, onLoad, onProgress, onError ) {
  7354. var scope = this;
  7355. var loader = new THREE.XHRLoader();
  7356. loader.setCrossOrigin( this.crossOrigin );
  7357. loader.load( url, function ( text ) {
  7358. onLoad( scope.parse( JSON.parse( text ) ) );
  7359. } );
  7360. },
  7361. setCrossOrigin: function ( value ) {
  7362. this.crossOrigin = value;
  7363. },
  7364. parse: function ( json ) {
  7365. var geometry = new THREE.BufferGeometry();
  7366. var attributes = json.attributes;
  7367. var offsets = json.offsets;
  7368. var boundingSphere = json.boundingSphere;
  7369. for ( var key in attributes ) {
  7370. var attribute = attributes[ key ];
  7371. geometry.attributes[ key ] = {
  7372. itemSize: attribute.itemSize,
  7373. array: new self[ attribute.type ]( attribute.array )
  7374. }
  7375. }
  7376. if ( offsets !== undefined ) {
  7377. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7378. }
  7379. if ( boundingSphere !== undefined ) {
  7380. geometry.boundingSphere = new THREE.Sphere(
  7381. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7382. boundingSphere.radius
  7383. );
  7384. }
  7385. return geometry;
  7386. }
  7387. };
  7388. /**
  7389. * @author mrdoob / http://mrdoob.com/
  7390. */
  7391. THREE.MaterialLoader = function ( manager ) {
  7392. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7393. };
  7394. THREE.MaterialLoader.prototype = {
  7395. constructor: THREE.MaterialLoader,
  7396. load: function ( url, onLoad, onProgress, onError ) {
  7397. var scope = this;
  7398. var loader = new THREE.XHRLoader();
  7399. loader.setCrossOrigin( this.crossOrigin );
  7400. loader.load( url, function ( text ) {
  7401. onLoad( scope.parse( JSON.parse( text ) ) );
  7402. } );
  7403. },
  7404. setCrossOrigin: function ( value ) {
  7405. this.crossOrigin = value;
  7406. },
  7407. parse: function ( json ) {
  7408. var material = new THREE[ json.type ];
  7409. if ( json.color !== undefined ) material.color.setHex( json.color );
  7410. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7411. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7412. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7413. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7414. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7415. if ( json.blending !== undefined ) material.blending = json.blending;
  7416. if ( json.side !== undefined ) material.side = json.side;
  7417. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7418. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7419. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7420. if ( json.materials !== undefined ) {
  7421. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7422. material.materials.push( this.parse( json.materials[ i ] ) );
  7423. }
  7424. }
  7425. return material;
  7426. }
  7427. };
  7428. /**
  7429. * @author mrdoob / http://mrdoob.com/
  7430. */
  7431. THREE.ObjectLoader = function ( manager ) {
  7432. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7433. };
  7434. THREE.ObjectLoader.prototype = {
  7435. constructor: THREE.ObjectLoader,
  7436. load: function ( url, onLoad, onProgress, onError ) {
  7437. var scope = this;
  7438. var loader = new THREE.XHRLoader( scope.manager );
  7439. loader.setCrossOrigin( this.crossOrigin );
  7440. loader.load( url, function ( text ) {
  7441. onLoad( scope.parse( JSON.parse( text ) ) );
  7442. } );
  7443. },
  7444. setCrossOrigin: function ( value ) {
  7445. this.crossOrigin = value;
  7446. },
  7447. parse: function ( json ) {
  7448. var geometries = this.parseGeometries( json.geometries );
  7449. var materials = this.parseMaterials( json.materials );
  7450. var object = this.parseObject( json.object, geometries, materials );
  7451. return object;
  7452. },
  7453. parseGeometries: function ( json ) {
  7454. var geometries = {};
  7455. if ( json !== undefined ) {
  7456. var geometryLoader = new THREE.JSONLoader();
  7457. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7458. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7459. var geometry;
  7460. var data = json[ i ];
  7461. switch ( data.type ) {
  7462. case 'PlaneGeometry':
  7463. geometry = new THREE.PlaneGeometry(
  7464. data.width,
  7465. data.height,
  7466. data.widthSegments,
  7467. data.heightSegments
  7468. );
  7469. break;
  7470. case 'BoxGeometry':
  7471. case 'CubeGeometry': // DEPRECATED
  7472. geometry = new THREE.BoxGeometry(
  7473. data.width,
  7474. data.height,
  7475. data.depth,
  7476. data.widthSegments,
  7477. data.heightSegments,
  7478. data.depthSegments
  7479. );
  7480. break;
  7481. case 'CircleGeometry':
  7482. geometry = new THREE.CircleGeometry(
  7483. data.radius,
  7484. data.segments
  7485. );
  7486. break;
  7487. case 'CylinderGeometry':
  7488. geometry = new THREE.CylinderGeometry(
  7489. data.radiusTop,
  7490. data.radiusBottom,
  7491. data.height,
  7492. data.radialSegments,
  7493. data.heightSegments,
  7494. data.openEnded
  7495. );
  7496. break;
  7497. case 'SphereGeometry':
  7498. geometry = new THREE.SphereGeometry(
  7499. data.radius,
  7500. data.widthSegments,
  7501. data.heightSegments,
  7502. data.phiStart,
  7503. data.phiLength,
  7504. data.thetaStart,
  7505. data.thetaLength
  7506. );
  7507. break;
  7508. case 'IcosahedronGeometry':
  7509. geometry = new THREE.IcosahedronGeometry(
  7510. data.radius,
  7511. data.detail
  7512. );
  7513. break;
  7514. case 'TorusGeometry':
  7515. geometry = new THREE.TorusGeometry(
  7516. data.radius,
  7517. data.tube,
  7518. data.radialSegments,
  7519. data.tubularSegments,
  7520. data.arc
  7521. );
  7522. break;
  7523. case 'TorusKnotGeometry':
  7524. geometry = new THREE.TorusKnotGeometry(
  7525. data.radius,
  7526. data.tube,
  7527. data.radialSegments,
  7528. data.tubularSegments,
  7529. data.p,
  7530. data.q,
  7531. data.heightScale
  7532. );
  7533. break;
  7534. case 'BufferGeometry':
  7535. geometry = bufferGeometryLoader.parse( data.data );
  7536. break;
  7537. case 'Geometry':
  7538. geometry = geometryLoader.parse( data.data ).geometry;
  7539. break;
  7540. }
  7541. geometry.uuid = data.uuid;
  7542. if ( data.name !== undefined ) geometry.name = data.name;
  7543. geometries[ data.uuid ] = geometry;
  7544. }
  7545. }
  7546. return geometries;
  7547. },
  7548. parseMaterials: function ( json ) {
  7549. var materials = {};
  7550. if ( json !== undefined ) {
  7551. var loader = new THREE.MaterialLoader();
  7552. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7553. var data = json[ i ];
  7554. var material = loader.parse( data );
  7555. material.uuid = data.uuid;
  7556. if ( data.name !== undefined ) material.name = data.name;
  7557. materials[ data.uuid ] = material;
  7558. }
  7559. }
  7560. return materials;
  7561. },
  7562. parseObject: function () {
  7563. var matrix = new THREE.Matrix4();
  7564. return function ( data, geometries, materials ) {
  7565. var object;
  7566. switch ( data.type ) {
  7567. case 'Scene':
  7568. object = new THREE.Scene();
  7569. break;
  7570. case 'PerspectiveCamera':
  7571. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7572. break;
  7573. case 'OrthographicCamera':
  7574. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7575. break;
  7576. case 'AmbientLight':
  7577. object = new THREE.AmbientLight( data.color );
  7578. break;
  7579. case 'DirectionalLight':
  7580. object = new THREE.DirectionalLight( data.color, data.intensity );
  7581. break;
  7582. case 'PointLight':
  7583. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7584. break;
  7585. case 'SpotLight':
  7586. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7587. break;
  7588. case 'HemisphereLight':
  7589. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7590. break;
  7591. case 'Mesh':
  7592. var geometry = geometries[ data.geometry ];
  7593. var material = materials[ data.material ];
  7594. if ( geometry === undefined ) {
  7595. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7596. }
  7597. if ( material === undefined ) {
  7598. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7599. }
  7600. object = new THREE.Mesh( geometry, material );
  7601. break;
  7602. case 'Sprite':
  7603. var material = materials[ data.material ];
  7604. if ( material === undefined ) {
  7605. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7606. }
  7607. object = new THREE.Sprite( material );
  7608. break;
  7609. default:
  7610. object = new THREE.Object3D();
  7611. }
  7612. object.uuid = data.uuid;
  7613. if ( data.name !== undefined ) object.name = data.name;
  7614. if ( data.matrix !== undefined ) {
  7615. matrix.fromArray( data.matrix );
  7616. matrix.decompose( object.position, object.quaternion, object.scale );
  7617. } else {
  7618. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7619. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7620. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7621. }
  7622. if ( data.visible !== undefined ) object.visible = data.visible;
  7623. if ( data.userData !== undefined ) object.userData = data.userData;
  7624. if ( data.children !== undefined ) {
  7625. for ( var child in data.children ) {
  7626. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7627. }
  7628. }
  7629. return object;
  7630. }
  7631. }()
  7632. };
  7633. /**
  7634. * @author alteredq / http://alteredqualia.com/
  7635. */
  7636. THREE.SceneLoader = function () {
  7637. this.onLoadStart = function () {};
  7638. this.onLoadProgress = function() {};
  7639. this.onLoadComplete = function () {};
  7640. this.callbackSync = function () {};
  7641. this.callbackProgress = function () {};
  7642. this.geometryHandlers = {};
  7643. this.hierarchyHandlers = {};
  7644. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  7645. };
  7646. THREE.SceneLoader.prototype = {
  7647. constructor: THREE.SceneLoader,
  7648. load: function ( url, onLoad, onProgress, onError ) {
  7649. var scope = this;
  7650. var loader = new THREE.XHRLoader( scope.manager );
  7651. loader.setCrossOrigin( this.crossOrigin );
  7652. loader.load( url, function ( text ) {
  7653. scope.parse( JSON.parse( text ), onLoad, url );
  7654. } );
  7655. },
  7656. setCrossOrigin: function ( value ) {
  7657. this.crossOrigin = value;
  7658. },
  7659. addGeometryHandler: function ( typeID, loaderClass ) {
  7660. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7661. },
  7662. addHierarchyHandler: function ( typeID, loaderClass ) {
  7663. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7664. },
  7665. parse: function ( json, callbackFinished, url ) {
  7666. var scope = this;
  7667. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7668. var geometry, material, camera, fog,
  7669. texture, images, color,
  7670. light, hex, intensity,
  7671. counter_models, counter_textures,
  7672. total_models, total_textures,
  7673. result;
  7674. var target_array = [];
  7675. var data = json;
  7676. // async geometry loaders
  7677. for ( var typeID in this.geometryHandlers ) {
  7678. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7679. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7680. }
  7681. // async hierachy loaders
  7682. for ( var typeID in this.hierarchyHandlers ) {
  7683. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7684. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7685. }
  7686. counter_models = 0;
  7687. counter_textures = 0;
  7688. result = {
  7689. scene: new THREE.Scene(),
  7690. geometries: {},
  7691. face_materials: {},
  7692. materials: {},
  7693. textures: {},
  7694. objects: {},
  7695. cameras: {},
  7696. lights: {},
  7697. fogs: {},
  7698. empties: {},
  7699. groups: {}
  7700. };
  7701. if ( data.transform ) {
  7702. var position = data.transform.position,
  7703. rotation = data.transform.rotation,
  7704. scale = data.transform.scale;
  7705. if ( position ) {
  7706. result.scene.position.fromArray( position );
  7707. }
  7708. if ( rotation ) {
  7709. result.scene.rotation.fromArray( rotation );
  7710. }
  7711. if ( scale ) {
  7712. result.scene.scale.fromArray( scale );
  7713. }
  7714. if ( position || rotation || scale ) {
  7715. result.scene.updateMatrix();
  7716. result.scene.updateMatrixWorld();
  7717. }
  7718. }
  7719. function get_url( source_url, url_type ) {
  7720. if ( url_type == "relativeToHTML" ) {
  7721. return source_url;
  7722. } else {
  7723. return urlBase + source_url;
  7724. }
  7725. };
  7726. // toplevel loader function, delegates to handle_children
  7727. function handle_objects() {
  7728. handle_children( result.scene, data.objects );
  7729. }
  7730. // handle all the children from the loaded json and attach them to given parent
  7731. function handle_children( parent, children ) {
  7732. var mat, dst, pos, rot, scl, quat;
  7733. for ( var objID in children ) {
  7734. // check by id if child has already been handled,
  7735. // if not, create new object
  7736. var object = result.objects[ objID ];
  7737. var objJSON = children[ objID ];
  7738. if ( object === undefined ) {
  7739. // meshes
  7740. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7741. if ( objJSON.loading === undefined ) {
  7742. var reservedTypes = {
  7743. "type": 1, "url": 1, "material": 1,
  7744. "position": 1, "rotation": 1, "scale" : 1,
  7745. "visible": 1, "children": 1, "userData": 1,
  7746. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7747. };
  7748. var loaderParameters = {};
  7749. for ( var parType in objJSON ) {
  7750. if ( ! ( parType in reservedTypes ) ) {
  7751. loaderParameters[ parType ] = objJSON[ parType ];
  7752. }
  7753. }
  7754. material = result.materials[ objJSON.material ];
  7755. objJSON.loading = true;
  7756. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7757. // ColladaLoader
  7758. if ( loader.options ) {
  7759. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7760. // UTF8Loader
  7761. // OBJLoader
  7762. } else {
  7763. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7764. }
  7765. }
  7766. } else if ( objJSON.geometry !== undefined ) {
  7767. geometry = result.geometries[ objJSON.geometry ];
  7768. // geometry already loaded
  7769. if ( geometry ) {
  7770. var needsTangents = false;
  7771. material = result.materials[ objJSON.material ];
  7772. needsTangents = material instanceof THREE.ShaderMaterial;
  7773. pos = objJSON.position;
  7774. rot = objJSON.rotation;
  7775. scl = objJSON.scale;
  7776. mat = objJSON.matrix;
  7777. quat = objJSON.quaternion;
  7778. // use materials from the model file
  7779. // if there is no material specified in the object
  7780. if ( ! objJSON.material ) {
  7781. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7782. }
  7783. // use materials from the model file
  7784. // if there is just empty face material
  7785. // (must create new material as each model has its own face material)
  7786. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7787. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7788. }
  7789. if ( material instanceof THREE.MeshFaceMaterial ) {
  7790. for ( var i = 0; i < material.materials.length; i ++ ) {
  7791. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7792. }
  7793. }
  7794. if ( needsTangents ) {
  7795. geometry.computeTangents();
  7796. }
  7797. if ( objJSON.skin ) {
  7798. object = new THREE.SkinnedMesh( geometry, material );
  7799. } else if ( objJSON.morph ) {
  7800. object = new THREE.MorphAnimMesh( geometry, material );
  7801. if ( objJSON.duration !== undefined ) {
  7802. object.duration = objJSON.duration;
  7803. }
  7804. if ( objJSON.time !== undefined ) {
  7805. object.time = objJSON.time;
  7806. }
  7807. if ( objJSON.mirroredLoop !== undefined ) {
  7808. object.mirroredLoop = objJSON.mirroredLoop;
  7809. }
  7810. if ( material.morphNormals ) {
  7811. geometry.computeMorphNormals();
  7812. }
  7813. } else {
  7814. object = new THREE.Mesh( geometry, material );
  7815. }
  7816. object.name = objID;
  7817. if ( mat ) {
  7818. object.matrixAutoUpdate = false;
  7819. object.matrix.set(
  7820. mat[0], mat[1], mat[2], mat[3],
  7821. mat[4], mat[5], mat[6], mat[7],
  7822. mat[8], mat[9], mat[10], mat[11],
  7823. mat[12], mat[13], mat[14], mat[15]
  7824. );
  7825. } else {
  7826. object.position.fromArray( pos );
  7827. if ( quat ) {
  7828. object.quaternion.fromArray( quat );
  7829. } else {
  7830. object.rotation.fromArray( rot );
  7831. }
  7832. object.scale.fromArray( scl );
  7833. }
  7834. object.visible = objJSON.visible;
  7835. object.castShadow = objJSON.castShadow;
  7836. object.receiveShadow = objJSON.receiveShadow;
  7837. parent.add( object );
  7838. result.objects[ objID ] = object;
  7839. }
  7840. // lights
  7841. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7842. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7843. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7844. var color = objJSON.color;
  7845. var intensity = objJSON.intensity;
  7846. var distance = objJSON.distance;
  7847. var position = objJSON.position;
  7848. var rotation = objJSON.rotation;
  7849. switch ( objJSON.type ) {
  7850. case 'AmbientLight':
  7851. light = new THREE.AmbientLight( color );
  7852. break;
  7853. case 'PointLight':
  7854. light = new THREE.PointLight( color, intensity, distance );
  7855. light.position.fromArray( position );
  7856. break;
  7857. case 'DirectionalLight':
  7858. light = new THREE.DirectionalLight( color, intensity );
  7859. light.position.fromArray( objJSON.direction );
  7860. break;
  7861. case 'SpotLight':
  7862. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7863. light.angle = objJSON.angle;
  7864. light.position.fromArray( position );
  7865. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7866. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7867. break;
  7868. case 'HemisphereLight':
  7869. light = new THREE.DirectionalLight( color, intensity, distance );
  7870. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7871. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7872. break;
  7873. case 'AreaLight':
  7874. light = new THREE.AreaLight(color, intensity);
  7875. light.position.fromArray( position );
  7876. light.width = objJSON.size;
  7877. light.height = objJSON.size_y;
  7878. break;
  7879. }
  7880. parent.add( light );
  7881. light.name = objID;
  7882. result.lights[ objID ] = light;
  7883. result.objects[ objID ] = light;
  7884. // cameras
  7885. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7886. pos = objJSON.position;
  7887. rot = objJSON.rotation;
  7888. quat = objJSON.quaternion;
  7889. if ( objJSON.type === "PerspectiveCamera" ) {
  7890. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7891. } else if ( objJSON.type === "OrthographicCamera" ) {
  7892. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7893. }
  7894. camera.name = objID;
  7895. camera.position.fromArray( pos );
  7896. if ( quat !== undefined ) {
  7897. camera.quaternion.fromArray( quat );
  7898. } else if ( rot !== undefined ) {
  7899. camera.rotation.fromArray( rot );
  7900. }
  7901. parent.add( camera );
  7902. result.cameras[ objID ] = camera;
  7903. result.objects[ objID ] = camera;
  7904. // pure Object3D
  7905. } else {
  7906. pos = objJSON.position;
  7907. rot = objJSON.rotation;
  7908. scl = objJSON.scale;
  7909. quat = objJSON.quaternion;
  7910. object = new THREE.Object3D();
  7911. object.name = objID;
  7912. object.position.fromArray( pos );
  7913. if ( quat ) {
  7914. object.quaternion.fromArray( quat );
  7915. } else {
  7916. object.rotation.fromArray( rot );
  7917. }
  7918. object.scale.fromArray( scl );
  7919. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7920. parent.add( object );
  7921. result.objects[ objID ] = object;
  7922. result.empties[ objID ] = object;
  7923. }
  7924. if ( object ) {
  7925. if ( objJSON.userData !== undefined ) {
  7926. for ( var key in objJSON.userData ) {
  7927. var value = objJSON.userData[ key ];
  7928. object.userData[ key ] = value;
  7929. }
  7930. }
  7931. if ( objJSON.groups !== undefined ) {
  7932. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7933. var groupID = objJSON.groups[ i ];
  7934. if ( result.groups[ groupID ] === undefined ) {
  7935. result.groups[ groupID ] = [];
  7936. }
  7937. result.groups[ groupID ].push( objID );
  7938. }
  7939. }
  7940. }
  7941. }
  7942. if ( object !== undefined && objJSON.children !== undefined ) {
  7943. handle_children( object, objJSON.children );
  7944. }
  7945. }
  7946. };
  7947. function handle_mesh( geo, mat, id ) {
  7948. result.geometries[ id ] = geo;
  7949. result.face_materials[ id ] = mat;
  7950. handle_objects();
  7951. };
  7952. function handle_hierarchy( node, id, parent, material, obj ) {
  7953. var p = obj.position;
  7954. var r = obj.rotation;
  7955. var q = obj.quaternion;
  7956. var s = obj.scale;
  7957. node.position.fromArray( p );
  7958. if ( q ) {
  7959. node.quaternion.fromArray( q );
  7960. } else {
  7961. node.rotation.fromArray( r );
  7962. }
  7963. node.scale.fromArray( s );
  7964. // override children materials
  7965. // if object material was specified in JSON explicitly
  7966. if ( material ) {
  7967. node.traverse( function ( child ) {
  7968. child.material = material;
  7969. } );
  7970. }
  7971. // override children visibility
  7972. // with root node visibility as specified in JSON
  7973. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7974. node.traverse( function ( child ) {
  7975. child.visible = visible;
  7976. } );
  7977. parent.add( node );
  7978. node.name = id;
  7979. result.objects[ id ] = node;
  7980. handle_objects();
  7981. };
  7982. function create_callback_geometry( id ) {
  7983. return function ( geo, mat ) {
  7984. geo.name = id;
  7985. handle_mesh( geo, mat, id );
  7986. counter_models -= 1;
  7987. scope.onLoadComplete();
  7988. async_callback_gate();
  7989. }
  7990. };
  7991. function create_callback_hierachy( id, parent, material, obj ) {
  7992. return function ( event ) {
  7993. var result;
  7994. // loaders which use EventDispatcher
  7995. if ( event.content ) {
  7996. result = event.content;
  7997. // ColladaLoader
  7998. } else if ( event.dae ) {
  7999. result = event.scene;
  8000. // UTF8Loader
  8001. } else {
  8002. result = event;
  8003. }
  8004. handle_hierarchy( result, id, parent, material, obj );
  8005. counter_models -= 1;
  8006. scope.onLoadComplete();
  8007. async_callback_gate();
  8008. }
  8009. };
  8010. function create_callback_embed( id ) {
  8011. return function ( geo, mat ) {
  8012. geo.name = id;
  8013. result.geometries[ id ] = geo;
  8014. result.face_materials[ id ] = mat;
  8015. }
  8016. };
  8017. function async_callback_gate() {
  8018. var progress = {
  8019. totalModels : total_models,
  8020. totalTextures : total_textures,
  8021. loadedModels : total_models - counter_models,
  8022. loadedTextures : total_textures - counter_textures
  8023. };
  8024. scope.callbackProgress( progress, result );
  8025. scope.onLoadProgress();
  8026. if ( counter_models === 0 && counter_textures === 0 ) {
  8027. finalize();
  8028. callbackFinished( result );
  8029. }
  8030. };
  8031. function finalize() {
  8032. // take care of targets which could be asynchronously loaded objects
  8033. for ( var i = 0; i < target_array.length; i ++ ) {
  8034. var ta = target_array[ i ];
  8035. var target = result.objects[ ta.targetName ];
  8036. if ( target ) {
  8037. ta.object.target = target;
  8038. } else {
  8039. // if there was error and target of specified name doesn't exist in the scene file
  8040. // create instead dummy target
  8041. // (target must be added to scene explicitly as parent is already added)
  8042. ta.object.target = new THREE.Object3D();
  8043. result.scene.add( ta.object.target );
  8044. }
  8045. ta.object.target.userData.targetInverse = ta.object;
  8046. }
  8047. };
  8048. var callbackTexture = function ( count ) {
  8049. counter_textures -= count;
  8050. async_callback_gate();
  8051. scope.onLoadComplete();
  8052. };
  8053. // must use this instead of just directly calling callbackTexture
  8054. // because of closure in the calling context loop
  8055. var generateTextureCallback = function ( count ) {
  8056. return function () {
  8057. callbackTexture( count );
  8058. };
  8059. };
  8060. function traverse_json_hierarchy( objJSON, callback ) {
  8061. callback( objJSON );
  8062. if ( objJSON.children !== undefined ) {
  8063. for ( var objChildID in objJSON.children ) {
  8064. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  8065. }
  8066. }
  8067. };
  8068. // first go synchronous elements
  8069. // fogs
  8070. var fogID, fogJSON;
  8071. for ( fogID in data.fogs ) {
  8072. fogJSON = data.fogs[ fogID ];
  8073. if ( fogJSON.type === "linear" ) {
  8074. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  8075. } else if ( fogJSON.type === "exp2" ) {
  8076. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  8077. }
  8078. color = fogJSON.color;
  8079. fog.color.setRGB( color[0], color[1], color[2] );
  8080. result.fogs[ fogID ] = fog;
  8081. }
  8082. // now come potentially asynchronous elements
  8083. // geometries
  8084. // count how many geometries will be loaded asynchronously
  8085. var geoID, geoJSON;
  8086. for ( geoID in data.geometries ) {
  8087. geoJSON = data.geometries[ geoID ];
  8088. if ( geoJSON.type in this.geometryHandlers ) {
  8089. counter_models += 1;
  8090. scope.onLoadStart();
  8091. }
  8092. }
  8093. // count how many hierarchies will be loaded asynchronously
  8094. for ( var objID in data.objects ) {
  8095. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  8096. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  8097. counter_models += 1;
  8098. scope.onLoadStart();
  8099. }
  8100. });
  8101. }
  8102. total_models = counter_models;
  8103. for ( geoID in data.geometries ) {
  8104. geoJSON = data.geometries[ geoID ];
  8105. if ( geoJSON.type === "cube" ) {
  8106. geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  8107. geometry.name = geoID;
  8108. result.geometries[ geoID ] = geometry;
  8109. } else if ( geoJSON.type === "plane" ) {
  8110. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  8111. geometry.name = geoID;
  8112. result.geometries[ geoID ] = geometry;
  8113. } else if ( geoJSON.type === "sphere" ) {
  8114. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  8115. geometry.name = geoID;
  8116. result.geometries[ geoID ] = geometry;
  8117. } else if ( geoJSON.type === "cylinder" ) {
  8118. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  8119. geometry.name = geoID;
  8120. result.geometries[ geoID ] = geometry;
  8121. } else if ( geoJSON.type === "torus" ) {
  8122. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  8123. geometry.name = geoID;
  8124. result.geometries[ geoID ] = geometry;
  8125. } else if ( geoJSON.type === "icosahedron" ) {
  8126. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  8127. geometry.name = geoID;
  8128. result.geometries[ geoID ] = geometry;
  8129. } else if ( geoJSON.type in this.geometryHandlers ) {
  8130. var loaderParameters = {};
  8131. for ( var parType in geoJSON ) {
  8132. if ( parType !== "type" && parType !== "url" ) {
  8133. loaderParameters[ parType ] = geoJSON[ parType ];
  8134. }
  8135. }
  8136. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  8137. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  8138. } else if ( geoJSON.type === "embedded" ) {
  8139. var modelJson = data.embeds[ geoJSON.id ],
  8140. texture_path = "";
  8141. // pass metadata along to jsonLoader so it knows the format version
  8142. modelJson.metadata = data.metadata;
  8143. if ( modelJson ) {
  8144. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  8145. var model = jsonLoader.parse( modelJson, texture_path );
  8146. create_callback_embed( geoID )( model.geometry, model.materials );
  8147. }
  8148. }
  8149. }
  8150. // textures
  8151. // count how many textures will be loaded asynchronously
  8152. var textureID, textureJSON;
  8153. for ( textureID in data.textures ) {
  8154. textureJSON = data.textures[ textureID ];
  8155. if ( textureJSON.url instanceof Array ) {
  8156. counter_textures += textureJSON.url.length;
  8157. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  8158. scope.onLoadStart();
  8159. }
  8160. } else {
  8161. counter_textures += 1;
  8162. scope.onLoadStart();
  8163. }
  8164. }
  8165. total_textures = counter_textures;
  8166. for ( textureID in data.textures ) {
  8167. textureJSON = data.textures[ textureID ];
  8168. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  8169. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  8170. }
  8171. if ( textureJSON.url instanceof Array ) {
  8172. var count = textureJSON.url.length;
  8173. var url_array = [];
  8174. for( var i = 0; i < count; i ++ ) {
  8175. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  8176. }
  8177. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  8178. if ( isCompressed ) {
  8179. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8180. } else {
  8181. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8182. }
  8183. } else {
  8184. var isCompressed = /\.dds$/i.test( textureJSON.url );
  8185. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  8186. var textureCallback = generateTextureCallback( 1 );
  8187. if ( isCompressed ) {
  8188. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  8189. } else {
  8190. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  8191. }
  8192. if ( THREE[ textureJSON.minFilter ] !== undefined )
  8193. texture.minFilter = THREE[ textureJSON.minFilter ];
  8194. if ( THREE[ textureJSON.magFilter ] !== undefined )
  8195. texture.magFilter = THREE[ textureJSON.magFilter ];
  8196. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  8197. if ( textureJSON.repeat ) {
  8198. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  8199. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  8200. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  8201. }
  8202. if ( textureJSON.offset ) {
  8203. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  8204. }
  8205. // handle wrap after repeat so that default repeat can be overriden
  8206. if ( textureJSON.wrap ) {
  8207. var wrapMap = {
  8208. "repeat": THREE.RepeatWrapping,
  8209. "mirror": THREE.MirroredRepeatWrapping
  8210. }
  8211. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  8212. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  8213. }
  8214. }
  8215. result.textures[ textureID ] = texture;
  8216. }
  8217. // materials
  8218. var matID, matJSON;
  8219. var parID;
  8220. for ( matID in data.materials ) {
  8221. matJSON = data.materials[ matID ];
  8222. for ( parID in matJSON.parameters ) {
  8223. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  8224. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  8225. } else if ( parID === "shading" ) {
  8226. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  8227. } else if ( parID === "side" ) {
  8228. if ( matJSON.parameters[ parID ] == "double" ) {
  8229. matJSON.parameters[ parID ] = THREE.DoubleSide;
  8230. } else if ( matJSON.parameters[ parID ] == "back" ) {
  8231. matJSON.parameters[ parID ] = THREE.BackSide;
  8232. } else {
  8233. matJSON.parameters[ parID ] = THREE.FrontSide;
  8234. }
  8235. } else if ( parID === "blending" ) {
  8236. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  8237. } else if ( parID === "combine" ) {
  8238. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  8239. } else if ( parID === "vertexColors" ) {
  8240. if ( matJSON.parameters[ parID ] == "face" ) {
  8241. matJSON.parameters[ parID ] = THREE.FaceColors;
  8242. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  8243. } else if ( matJSON.parameters[ parID ] ) {
  8244. matJSON.parameters[ parID ] = THREE.VertexColors;
  8245. }
  8246. } else if ( parID === "wrapRGB" ) {
  8247. var v3 = matJSON.parameters[ parID ];
  8248. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  8249. }
  8250. }
  8251. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  8252. matJSON.parameters.transparent = true;
  8253. }
  8254. if ( matJSON.parameters.normalMap ) {
  8255. var shader = THREE.ShaderLib[ "normalmap" ];
  8256. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  8257. var diffuse = matJSON.parameters.color;
  8258. var specular = matJSON.parameters.specular;
  8259. var ambient = matJSON.parameters.ambient;
  8260. var shininess = matJSON.parameters.shininess;
  8261. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  8262. if ( matJSON.parameters.normalScale ) {
  8263. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  8264. }
  8265. if ( matJSON.parameters.map ) {
  8266. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  8267. uniforms[ "enableDiffuse" ].value = true;
  8268. }
  8269. if ( matJSON.parameters.envMap ) {
  8270. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  8271. uniforms[ "enableReflection" ].value = true;
  8272. uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
  8273. }
  8274. if ( matJSON.parameters.lightMap ) {
  8275. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  8276. uniforms[ "enableAO" ].value = true;
  8277. }
  8278. if ( matJSON.parameters.specularMap ) {
  8279. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  8280. uniforms[ "enableSpecular" ].value = true;
  8281. }
  8282. if ( matJSON.parameters.displacementMap ) {
  8283. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  8284. uniforms[ "enableDisplacement" ].value = true;
  8285. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  8286. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  8287. }
  8288. uniforms[ "diffuse" ].value.setHex( diffuse );
  8289. uniforms[ "specular" ].value.setHex( specular );
  8290. uniforms[ "ambient" ].value.setHex( ambient );
  8291. uniforms[ "shininess" ].value = shininess;
  8292. if ( matJSON.parameters.opacity ) {
  8293. uniforms[ "opacity" ].value = matJSON.parameters.opacity;
  8294. }
  8295. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  8296. material = new THREE.ShaderMaterial( parameters );
  8297. } else {
  8298. material = new THREE[ matJSON.type ]( matJSON.parameters );
  8299. }
  8300. material.name = matID;
  8301. result.materials[ matID ] = material;
  8302. }
  8303. // second pass through all materials to initialize MeshFaceMaterials
  8304. // that could be referring to other materials out of order
  8305. for ( matID in data.materials ) {
  8306. matJSON = data.materials[ matID ];
  8307. if ( matJSON.parameters.materials ) {
  8308. var materialArray = [];
  8309. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  8310. var label = matJSON.parameters.materials[ i ];
  8311. materialArray.push( result.materials[ label ] );
  8312. }
  8313. result.materials[ matID ].materials = materialArray;
  8314. }
  8315. }
  8316. // objects ( synchronous init of procedural primitives )
  8317. handle_objects();
  8318. // defaults
  8319. if ( result.cameras && data.defaults.camera ) {
  8320. result.currentCamera = result.cameras[ data.defaults.camera ];
  8321. }
  8322. if ( result.fogs && data.defaults.fog ) {
  8323. result.scene.fog = result.fogs[ data.defaults.fog ];
  8324. }
  8325. // synchronous callback
  8326. scope.callbackSync( result );
  8327. // just in case there are no async elements
  8328. async_callback_gate();
  8329. }
  8330. }
  8331. /**
  8332. * @author mrdoob / http://mrdoob.com/
  8333. */
  8334. THREE.TextureLoader = function ( manager ) {
  8335. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8336. };
  8337. THREE.TextureLoader.prototype = {
  8338. constructor: THREE.TextureLoader,
  8339. load: function ( url, onLoad, onProgress, onError ) {
  8340. var scope = this;
  8341. var loader = new THREE.ImageLoader( scope.manager );
  8342. loader.setCrossOrigin( this.crossOrigin );
  8343. loader.load( url, function ( image ) {
  8344. var texture = new THREE.Texture( image );
  8345. texture.needsUpdate = true;
  8346. if ( onLoad !== undefined ) {
  8347. onLoad( texture );
  8348. }
  8349. } );
  8350. },
  8351. setCrossOrigin: function ( value ) {
  8352. this.crossOrigin = value;
  8353. }
  8354. };
  8355. /**
  8356. * @author mrdoob / http://mrdoob.com/
  8357. * @author alteredq / http://alteredqualia.com/
  8358. */
  8359. THREE.Material = function () {
  8360. this.id = THREE.MaterialIdCount ++;
  8361. this.uuid = THREE.Math.generateUUID();
  8362. this.name = '';
  8363. this.side = THREE.FrontSide;
  8364. this.opacity = 1;
  8365. this.transparent = false;
  8366. this.blending = THREE.NormalBlending;
  8367. this.blendSrc = THREE.SrcAlphaFactor;
  8368. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  8369. this.blendEquation = THREE.AddEquation;
  8370. this.depthTest = true;
  8371. this.depthWrite = true;
  8372. this.polygonOffset = false;
  8373. this.polygonOffsetFactor = 0;
  8374. this.polygonOffsetUnits = 0;
  8375. this.alphaTest = 0;
  8376. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8377. this.visible = true;
  8378. this.needsUpdate = true;
  8379. };
  8380. THREE.Material.prototype = {
  8381. constructor: THREE.Material,
  8382. setValues: function ( values ) {
  8383. if ( values === undefined ) return;
  8384. for ( var key in values ) {
  8385. var newValue = values[ key ];
  8386. if ( newValue === undefined ) {
  8387. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  8388. continue;
  8389. }
  8390. if ( key in this ) {
  8391. var currentValue = this[ key ];
  8392. if ( currentValue instanceof THREE.Color ) {
  8393. currentValue.set( newValue );
  8394. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  8395. currentValue.copy( newValue );
  8396. } else if ( key == 'overdraw') {
  8397. // ensure overdraw is backwards-compatable with legacy boolean type
  8398. this[ key ] = Number(newValue);
  8399. } else {
  8400. this[ key ] = newValue;
  8401. }
  8402. }
  8403. }
  8404. },
  8405. clone: function ( material ) {
  8406. if ( material === undefined ) material = new THREE.Material();
  8407. material.name = this.name;
  8408. material.side = this.side;
  8409. material.opacity = this.opacity;
  8410. material.transparent = this.transparent;
  8411. material.blending = this.blending;
  8412. material.blendSrc = this.blendSrc;
  8413. material.blendDst = this.blendDst;
  8414. material.blendEquation = this.blendEquation;
  8415. material.depthTest = this.depthTest;
  8416. material.depthWrite = this.depthWrite;
  8417. material.polygonOffset = this.polygonOffset;
  8418. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8419. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8420. material.alphaTest = this.alphaTest;
  8421. material.overdraw = this.overdraw;
  8422. material.visible = this.visible;
  8423. return material;
  8424. },
  8425. dispose: function () {
  8426. this.dispatchEvent( { type: 'dispose' } );
  8427. }
  8428. };
  8429. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8430. THREE.MaterialIdCount = 0;
  8431. /**
  8432. * @author mrdoob / http://mrdoob.com/
  8433. * @author alteredq / http://alteredqualia.com/
  8434. *
  8435. * parameters = {
  8436. * color: <hex>,
  8437. * opacity: <float>,
  8438. *
  8439. * blending: THREE.NormalBlending,
  8440. * depthTest: <bool>,
  8441. * depthWrite: <bool>,
  8442. *
  8443. * linewidth: <float>,
  8444. * linecap: "round",
  8445. * linejoin: "round",
  8446. *
  8447. * vertexColors: <bool>
  8448. *
  8449. * fog: <bool>
  8450. * }
  8451. */
  8452. THREE.LineBasicMaterial = function ( parameters ) {
  8453. THREE.Material.call( this );
  8454. this.color = new THREE.Color( 0xffffff );
  8455. this.linewidth = 1;
  8456. this.linecap = 'round';
  8457. this.linejoin = 'round';
  8458. this.vertexColors = false;
  8459. this.fog = true;
  8460. this.setValues( parameters );
  8461. };
  8462. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8463. THREE.LineBasicMaterial.prototype.clone = function () {
  8464. var material = new THREE.LineBasicMaterial();
  8465. THREE.Material.prototype.clone.call( this, material );
  8466. material.color.copy( this.color );
  8467. material.linewidth = this.linewidth;
  8468. material.linecap = this.linecap;
  8469. material.linejoin = this.linejoin;
  8470. material.vertexColors = this.vertexColors;
  8471. material.fog = this.fog;
  8472. return material;
  8473. };
  8474. /**
  8475. * @author alteredq / http://alteredqualia.com/
  8476. *
  8477. * parameters = {
  8478. * color: <hex>,
  8479. * opacity: <float>,
  8480. *
  8481. * blending: THREE.NormalBlending,
  8482. * depthTest: <bool>,
  8483. * depthWrite: <bool>,
  8484. *
  8485. * linewidth: <float>,
  8486. *
  8487. * scale: <float>,
  8488. * dashSize: <float>,
  8489. * gapSize: <float>,
  8490. *
  8491. * vertexColors: <bool>
  8492. *
  8493. * fog: <bool>
  8494. * }
  8495. */
  8496. THREE.LineDashedMaterial = function ( parameters ) {
  8497. THREE.Material.call( this );
  8498. this.color = new THREE.Color( 0xffffff );
  8499. this.linewidth = 1;
  8500. this.scale = 1;
  8501. this.dashSize = 3;
  8502. this.gapSize = 1;
  8503. this.vertexColors = false;
  8504. this.fog = true;
  8505. this.setValues( parameters );
  8506. };
  8507. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8508. THREE.LineDashedMaterial.prototype.clone = function () {
  8509. var material = new THREE.LineDashedMaterial();
  8510. THREE.Material.prototype.clone.call( this, material );
  8511. material.color.copy( this.color );
  8512. material.linewidth = this.linewidth;
  8513. material.scale = this.scale;
  8514. material.dashSize = this.dashSize;
  8515. material.gapSize = this.gapSize;
  8516. material.vertexColors = this.vertexColors;
  8517. material.fog = this.fog;
  8518. return material;
  8519. };
  8520. /**
  8521. * @author mrdoob / http://mrdoob.com/
  8522. * @author alteredq / http://alteredqualia.com/
  8523. *
  8524. * parameters = {
  8525. * color: <hex>,
  8526. * opacity: <float>,
  8527. * map: new THREE.Texture( <Image> ),
  8528. *
  8529. * lightMap: new THREE.Texture( <Image> ),
  8530. *
  8531. * specularMap: new THREE.Texture( <Image> ),
  8532. *
  8533. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8534. * combine: THREE.Multiply,
  8535. * reflectivity: <float>,
  8536. * refractionRatio: <float>,
  8537. *
  8538. * shading: THREE.SmoothShading,
  8539. * blending: THREE.NormalBlending,
  8540. * depthTest: <bool>,
  8541. * depthWrite: <bool>,
  8542. *
  8543. * wireframe: <boolean>,
  8544. * wireframeLinewidth: <float>,
  8545. *
  8546. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8547. *
  8548. * skinning: <bool>,
  8549. * morphTargets: <bool>,
  8550. *
  8551. * fog: <bool>
  8552. * }
  8553. */
  8554. THREE.MeshBasicMaterial = function ( parameters ) {
  8555. THREE.Material.call( this );
  8556. this.color = new THREE.Color( 0xffffff ); // emissive
  8557. this.map = null;
  8558. this.lightMap = null;
  8559. this.specularMap = null;
  8560. this.envMap = null;
  8561. this.combine = THREE.MultiplyOperation;
  8562. this.reflectivity = 1;
  8563. this.refractionRatio = 0.98;
  8564. this.fog = true;
  8565. this.shading = THREE.SmoothShading;
  8566. this.wireframe = false;
  8567. this.wireframeLinewidth = 1;
  8568. this.wireframeLinecap = 'round';
  8569. this.wireframeLinejoin = 'round';
  8570. this.vertexColors = THREE.NoColors;
  8571. this.skinning = false;
  8572. this.morphTargets = false;
  8573. this.setValues( parameters );
  8574. };
  8575. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8576. THREE.MeshBasicMaterial.prototype.clone = function () {
  8577. var material = new THREE.MeshBasicMaterial();
  8578. THREE.Material.prototype.clone.call( this, material );
  8579. material.color.copy( this.color );
  8580. material.map = this.map;
  8581. material.lightMap = this.lightMap;
  8582. material.specularMap = this.specularMap;
  8583. material.envMap = this.envMap;
  8584. material.combine = this.combine;
  8585. material.reflectivity = this.reflectivity;
  8586. material.refractionRatio = this.refractionRatio;
  8587. material.fog = this.fog;
  8588. material.shading = this.shading;
  8589. material.wireframe = this.wireframe;
  8590. material.wireframeLinewidth = this.wireframeLinewidth;
  8591. material.wireframeLinecap = this.wireframeLinecap;
  8592. material.wireframeLinejoin = this.wireframeLinejoin;
  8593. material.vertexColors = this.vertexColors;
  8594. material.skinning = this.skinning;
  8595. material.morphTargets = this.morphTargets;
  8596. return material;
  8597. };
  8598. /**
  8599. * @author mrdoob / http://mrdoob.com/
  8600. * @author alteredq / http://alteredqualia.com/
  8601. *
  8602. * parameters = {
  8603. * color: <hex>,
  8604. * ambient: <hex>,
  8605. * emissive: <hex>,
  8606. * opacity: <float>,
  8607. *
  8608. * map: new THREE.Texture( <Image> ),
  8609. *
  8610. * lightMap: new THREE.Texture( <Image> ),
  8611. *
  8612. * specularMap: new THREE.Texture( <Image> ),
  8613. *
  8614. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8615. * combine: THREE.Multiply,
  8616. * reflectivity: <float>,
  8617. * refractionRatio: <float>,
  8618. *
  8619. * shading: THREE.SmoothShading,
  8620. * blending: THREE.NormalBlending,
  8621. * depthTest: <bool>,
  8622. * depthWrite: <bool>,
  8623. *
  8624. * wireframe: <boolean>,
  8625. * wireframeLinewidth: <float>,
  8626. *
  8627. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8628. *
  8629. * skinning: <bool>,
  8630. * morphTargets: <bool>,
  8631. * morphNormals: <bool>,
  8632. *
  8633. * fog: <bool>
  8634. * }
  8635. */
  8636. THREE.MeshLambertMaterial = function ( parameters ) {
  8637. THREE.Material.call( this );
  8638. this.color = new THREE.Color( 0xffffff ); // diffuse
  8639. this.ambient = new THREE.Color( 0xffffff );
  8640. this.emissive = new THREE.Color( 0x000000 );
  8641. this.wrapAround = false;
  8642. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8643. this.map = null;
  8644. this.lightMap = null;
  8645. this.specularMap = null;
  8646. this.envMap = null;
  8647. this.combine = THREE.MultiplyOperation;
  8648. this.reflectivity = 1;
  8649. this.refractionRatio = 0.98;
  8650. this.fog = true;
  8651. this.shading = THREE.SmoothShading;
  8652. this.wireframe = false;
  8653. this.wireframeLinewidth = 1;
  8654. this.wireframeLinecap = 'round';
  8655. this.wireframeLinejoin = 'round';
  8656. this.vertexColors = THREE.NoColors;
  8657. this.skinning = false;
  8658. this.morphTargets = false;
  8659. this.morphNormals = false;
  8660. this.setValues( parameters );
  8661. };
  8662. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8663. THREE.MeshLambertMaterial.prototype.clone = function () {
  8664. var material = new THREE.MeshLambertMaterial();
  8665. THREE.Material.prototype.clone.call( this, material );
  8666. material.color.copy( this.color );
  8667. material.ambient.copy( this.ambient );
  8668. material.emissive.copy( this.emissive );
  8669. material.wrapAround = this.wrapAround;
  8670. material.wrapRGB.copy( this.wrapRGB );
  8671. material.map = this.map;
  8672. material.lightMap = this.lightMap;
  8673. material.specularMap = this.specularMap;
  8674. material.envMap = this.envMap;
  8675. material.combine = this.combine;
  8676. material.reflectivity = this.reflectivity;
  8677. material.refractionRatio = this.refractionRatio;
  8678. material.fog = this.fog;
  8679. material.shading = this.shading;
  8680. material.wireframe = this.wireframe;
  8681. material.wireframeLinewidth = this.wireframeLinewidth;
  8682. material.wireframeLinecap = this.wireframeLinecap;
  8683. material.wireframeLinejoin = this.wireframeLinejoin;
  8684. material.vertexColors = this.vertexColors;
  8685. material.skinning = this.skinning;
  8686. material.morphTargets = this.morphTargets;
  8687. material.morphNormals = this.morphNormals;
  8688. return material;
  8689. };
  8690. /**
  8691. * @author mrdoob / http://mrdoob.com/
  8692. * @author alteredq / http://alteredqualia.com/
  8693. *
  8694. * parameters = {
  8695. * color: <hex>,
  8696. * ambient: <hex>,
  8697. * emissive: <hex>,
  8698. * specular: <hex>,
  8699. * shininess: <float>,
  8700. * opacity: <float>,
  8701. *
  8702. * map: new THREE.Texture( <Image> ),
  8703. *
  8704. * lightMap: new THREE.Texture( <Image> ),
  8705. *
  8706. * bumpMap: new THREE.Texture( <Image> ),
  8707. * bumpScale: <float>,
  8708. *
  8709. * normalMap: new THREE.Texture( <Image> ),
  8710. * normalScale: <Vector2>,
  8711. *
  8712. * specularMap: new THREE.Texture( <Image> ),
  8713. *
  8714. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8715. * combine: THREE.Multiply,
  8716. * reflectivity: <float>,
  8717. * refractionRatio: <float>,
  8718. *
  8719. * shading: THREE.SmoothShading,
  8720. * blending: THREE.NormalBlending,
  8721. * depthTest: <bool>,
  8722. * depthWrite: <bool>,
  8723. *
  8724. * wireframe: <boolean>,
  8725. * wireframeLinewidth: <float>,
  8726. *
  8727. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8728. *
  8729. * skinning: <bool>,
  8730. * morphTargets: <bool>,
  8731. * morphNormals: <bool>,
  8732. *
  8733. * fog: <bool>
  8734. * }
  8735. */
  8736. THREE.MeshPhongMaterial = function ( parameters ) {
  8737. THREE.Material.call( this );
  8738. this.color = new THREE.Color( 0xffffff ); // diffuse
  8739. this.ambient = new THREE.Color( 0xffffff );
  8740. this.emissive = new THREE.Color( 0x000000 );
  8741. this.specular = new THREE.Color( 0x111111 );
  8742. this.shininess = 30;
  8743. this.metal = false;
  8744. this.wrapAround = false;
  8745. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8746. this.map = null;
  8747. this.lightMap = null;
  8748. this.bumpMap = null;
  8749. this.bumpScale = 1;
  8750. this.normalMap = null;
  8751. this.normalScale = new THREE.Vector2( 1, 1 );
  8752. this.specularMap = null;
  8753. this.envMap = null;
  8754. this.combine = THREE.MultiplyOperation;
  8755. this.reflectivity = 1;
  8756. this.refractionRatio = 0.98;
  8757. this.fog = true;
  8758. this.shading = THREE.SmoothShading;
  8759. this.wireframe = false;
  8760. this.wireframeLinewidth = 1;
  8761. this.wireframeLinecap = 'round';
  8762. this.wireframeLinejoin = 'round';
  8763. this.vertexColors = THREE.NoColors;
  8764. this.skinning = false;
  8765. this.morphTargets = false;
  8766. this.morphNormals = false;
  8767. this.setValues( parameters );
  8768. };
  8769. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8770. THREE.MeshPhongMaterial.prototype.clone = function () {
  8771. var material = new THREE.MeshPhongMaterial();
  8772. THREE.Material.prototype.clone.call( this, material );
  8773. material.color.copy( this.color );
  8774. material.ambient.copy( this.ambient );
  8775. material.emissive.copy( this.emissive );
  8776. material.specular.copy( this.specular );
  8777. material.shininess = this.shininess;
  8778. material.metal = this.metal;
  8779. material.wrapAround = this.wrapAround;
  8780. material.wrapRGB.copy( this.wrapRGB );
  8781. material.map = this.map;
  8782. material.lightMap = this.lightMap;
  8783. material.bumpMap = this.bumpMap;
  8784. material.bumpScale = this.bumpScale;
  8785. material.normalMap = this.normalMap;
  8786. material.normalScale.copy( this.normalScale );
  8787. material.specularMap = this.specularMap;
  8788. material.envMap = this.envMap;
  8789. material.combine = this.combine;
  8790. material.reflectivity = this.reflectivity;
  8791. material.refractionRatio = this.refractionRatio;
  8792. material.fog = this.fog;
  8793. material.shading = this.shading;
  8794. material.wireframe = this.wireframe;
  8795. material.wireframeLinewidth = this.wireframeLinewidth;
  8796. material.wireframeLinecap = this.wireframeLinecap;
  8797. material.wireframeLinejoin = this.wireframeLinejoin;
  8798. material.vertexColors = this.vertexColors;
  8799. material.skinning = this.skinning;
  8800. material.morphTargets = this.morphTargets;
  8801. material.morphNormals = this.morphNormals;
  8802. return material;
  8803. };
  8804. /**
  8805. * @author mrdoob / http://mrdoob.com/
  8806. * @author alteredq / http://alteredqualia.com/
  8807. *
  8808. * parameters = {
  8809. * opacity: <float>,
  8810. *
  8811. * blending: THREE.NormalBlending,
  8812. * depthTest: <bool>,
  8813. * depthWrite: <bool>,
  8814. *
  8815. * wireframe: <boolean>,
  8816. * wireframeLinewidth: <float>
  8817. * }
  8818. */
  8819. THREE.MeshDepthMaterial = function ( parameters ) {
  8820. THREE.Material.call( this );
  8821. this.wireframe = false;
  8822. this.wireframeLinewidth = 1;
  8823. this.setValues( parameters );
  8824. };
  8825. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8826. THREE.MeshDepthMaterial.prototype.clone = function () {
  8827. var material = new THREE.MeshDepthMaterial();
  8828. THREE.Material.prototype.clone.call( this, material );
  8829. material.wireframe = this.wireframe;
  8830. material.wireframeLinewidth = this.wireframeLinewidth;
  8831. return material;
  8832. };
  8833. /**
  8834. * @author mrdoob / http://mrdoob.com/
  8835. *
  8836. * parameters = {
  8837. * opacity: <float>,
  8838. *
  8839. * shading: THREE.FlatShading,
  8840. * blending: THREE.NormalBlending,
  8841. * depthTest: <bool>,
  8842. * depthWrite: <bool>,
  8843. *
  8844. * wireframe: <boolean>,
  8845. * wireframeLinewidth: <float>
  8846. * }
  8847. */
  8848. THREE.MeshNormalMaterial = function ( parameters ) {
  8849. THREE.Material.call( this, parameters );
  8850. this.shading = THREE.FlatShading;
  8851. this.wireframe = false;
  8852. this.wireframeLinewidth = 1;
  8853. this.morphTargets = false;
  8854. this.setValues( parameters );
  8855. };
  8856. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8857. THREE.MeshNormalMaterial.prototype.clone = function () {
  8858. var material = new THREE.MeshNormalMaterial();
  8859. THREE.Material.prototype.clone.call( this, material );
  8860. material.shading = this.shading;
  8861. material.wireframe = this.wireframe;
  8862. material.wireframeLinewidth = this.wireframeLinewidth;
  8863. return material;
  8864. };
  8865. /**
  8866. * @author mrdoob / http://mrdoob.com/
  8867. */
  8868. THREE.MeshFaceMaterial = function ( materials ) {
  8869. this.materials = materials instanceof Array ? materials : [];
  8870. };
  8871. THREE.MeshFaceMaterial.prototype.clone = function () {
  8872. var material = new THREE.MeshFaceMaterial();
  8873. for ( var i = 0; i < this.materials.length; i ++ ) {
  8874. material.materials.push( this.materials[ i ].clone() );
  8875. }
  8876. return material;
  8877. };
  8878. /**
  8879. * @author mrdoob / http://mrdoob.com/
  8880. * @author alteredq / http://alteredqualia.com/
  8881. *
  8882. * parameters = {
  8883. * color: <hex>,
  8884. * opacity: <float>,
  8885. * map: new THREE.Texture( <Image> ),
  8886. *
  8887. * size: <float>,
  8888. *
  8889. * blending: THREE.NormalBlending,
  8890. * depthTest: <bool>,
  8891. * depthWrite: <bool>,
  8892. *
  8893. * vertexColors: <bool>,
  8894. *
  8895. * fog: <bool>
  8896. * }
  8897. */
  8898. THREE.ParticleSystemMaterial = function ( parameters ) {
  8899. THREE.Material.call( this );
  8900. this.color = new THREE.Color( 0xffffff );
  8901. this.map = null;
  8902. this.size = 1;
  8903. this.sizeAttenuation = true;
  8904. this.vertexColors = false;
  8905. this.fog = true;
  8906. this.setValues( parameters );
  8907. };
  8908. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8909. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8910. var material = new THREE.ParticleSystemMaterial();
  8911. THREE.Material.prototype.clone.call( this, material );
  8912. material.color.copy( this.color );
  8913. material.map = this.map;
  8914. material.size = this.size;
  8915. material.sizeAttenuation = this.sizeAttenuation;
  8916. material.vertexColors = this.vertexColors;
  8917. material.fog = this.fog;
  8918. return material;
  8919. };
  8920. // backwards compatibility
  8921. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8922. /**
  8923. * @author alteredq / http://alteredqualia.com/
  8924. *
  8925. * parameters = {
  8926. * fragmentShader: <string>,
  8927. * vertexShader: <string>,
  8928. *
  8929. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8930. *
  8931. * defines: { "label" : "value" },
  8932. *
  8933. * shading: THREE.SmoothShading,
  8934. * blending: THREE.NormalBlending,
  8935. * depthTest: <bool>,
  8936. * depthWrite: <bool>,
  8937. *
  8938. * wireframe: <boolean>,
  8939. * wireframeLinewidth: <float>,
  8940. *
  8941. * lights: <bool>,
  8942. *
  8943. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8944. *
  8945. * skinning: <bool>,
  8946. * morphTargets: <bool>,
  8947. * morphNormals: <bool>,
  8948. *
  8949. * fog: <bool>
  8950. * }
  8951. */
  8952. THREE.ShaderMaterial = function ( parameters ) {
  8953. THREE.Material.call( this );
  8954. this.fragmentShader = "void main() {}";
  8955. this.vertexShader = "void main() {}";
  8956. this.uniforms = {};
  8957. this.defines = {};
  8958. this.attributes = null;
  8959. this.shading = THREE.SmoothShading;
  8960. this.linewidth = 1;
  8961. this.wireframe = false;
  8962. this.wireframeLinewidth = 1;
  8963. this.fog = false; // set to use scene fog
  8964. this.lights = false; // set to use scene lights
  8965. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8966. this.skinning = false; // set to use skinning attribute streams
  8967. this.morphTargets = false; // set to use morph targets
  8968. this.morphNormals = false; // set to use morph normals
  8969. // When rendered geometry doesn't include these attributes but the material does,
  8970. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8971. this.defaultAttributeValues = {
  8972. "color" : [ 1, 1, 1 ],
  8973. "uv" : [ 0, 0 ],
  8974. "uv2" : [ 0, 0 ]
  8975. };
  8976. this.index0AttributeName = undefined;
  8977. this.setValues( parameters );
  8978. };
  8979. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8980. THREE.ShaderMaterial.prototype.clone = function () {
  8981. var material = new THREE.ShaderMaterial();
  8982. THREE.Material.prototype.clone.call( this, material );
  8983. material.fragmentShader = this.fragmentShader;
  8984. material.vertexShader = this.vertexShader;
  8985. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8986. material.attributes = this.attributes;
  8987. material.defines = this.defines;
  8988. material.shading = this.shading;
  8989. material.wireframe = this.wireframe;
  8990. material.wireframeLinewidth = this.wireframeLinewidth;
  8991. material.fog = this.fog;
  8992. material.lights = this.lights;
  8993. material.vertexColors = this.vertexColors;
  8994. material.skinning = this.skinning;
  8995. material.morphTargets = this.morphTargets;
  8996. material.morphNormals = this.morphNormals;
  8997. return material;
  8998. };
  8999. /**
  9000. * @author mrdoob / http://mrdoob.com/
  9001. */
  9002. THREE.RawShaderMaterial = function ( parameters ) {
  9003. THREE.ShaderMaterial.call( this, parameters );
  9004. };
  9005. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  9006. THREE.RawShaderMaterial.prototype.clone = function () {
  9007. var material = new THREE.RawShaderMaterial();
  9008. THREE.ShaderMaterial.prototype.clone.call( this, material );
  9009. return material;
  9010. };
  9011. /**
  9012. * @author alteredq / http://alteredqualia.com/
  9013. *
  9014. * parameters = {
  9015. * color: <hex>,
  9016. * opacity: <float>,
  9017. * map: new THREE.Texture( <Image> ),
  9018. *
  9019. * blending: THREE.NormalBlending,
  9020. * depthTest: <bool>,
  9021. * depthWrite: <bool>,
  9022. *
  9023. * uvOffset: new THREE.Vector2(),
  9024. * uvScale: new THREE.Vector2(),
  9025. *
  9026. * fog: <bool>
  9027. * }
  9028. */
  9029. THREE.SpriteMaterial = function ( parameters ) {
  9030. THREE.Material.call( this );
  9031. // defaults
  9032. this.color = new THREE.Color( 0xffffff );
  9033. this.map = null;
  9034. this.rotation = 0;
  9035. this.fog = false;
  9036. // set parameters
  9037. this.setValues( parameters );
  9038. };
  9039. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  9040. THREE.SpriteMaterial.prototype.clone = function () {
  9041. var material = new THREE.SpriteMaterial();
  9042. THREE.Material.prototype.clone.call( this, material );
  9043. material.color.copy( this.color );
  9044. material.map = this.map;
  9045. material.rotation = this.rotation;
  9046. material.fog = this.fog;
  9047. return material;
  9048. };
  9049. /**
  9050. * @author mrdoob / http://mrdoob.com/
  9051. *
  9052. * parameters = {
  9053. * color: <hex>,
  9054. * program: <function>,
  9055. * opacity: <float>,
  9056. * blending: THREE.NormalBlending
  9057. * }
  9058. */
  9059. THREE.SpriteCanvasMaterial = function ( parameters ) {
  9060. THREE.Material.call( this );
  9061. this.color = new THREE.Color( 0xffffff );
  9062. this.program = function ( context, color ) {};
  9063. this.setValues( parameters );
  9064. };
  9065. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  9066. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  9067. var material = new THREE.SpriteCanvasMaterial();
  9068. THREE.Material.prototype.clone.call( this, material );
  9069. material.color.copy( this.color );
  9070. material.program = this.program;
  9071. return material;
  9072. };
  9073. // backwards compatibility
  9074. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  9075. /**
  9076. * @author mrdoob / http://mrdoob.com/
  9077. * @author alteredq / http://alteredqualia.com/
  9078. * @author szimek / https://github.com/szimek/
  9079. */
  9080. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  9081. this.id = THREE.TextureIdCount ++;
  9082. this.uuid = THREE.Math.generateUUID();
  9083. this.name = '';
  9084. this.image = image;
  9085. this.mipmaps = [];
  9086. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  9087. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  9088. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  9089. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  9090. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  9091. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  9092. this.format = format !== undefined ? format : THREE.RGBAFormat;
  9093. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  9094. this.offset = new THREE.Vector2( 0, 0 );
  9095. this.repeat = new THREE.Vector2( 1, 1 );
  9096. this.generateMipmaps = true;
  9097. this.premultiplyAlpha = false;
  9098. this.flipY = true;
  9099. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  9100. this._needsUpdate = false;
  9101. this.onUpdate = null;
  9102. };
  9103. THREE.Texture.prototype = {
  9104. constructor: THREE.Texture,
  9105. get needsUpdate () {
  9106. return this._needsUpdate;
  9107. },
  9108. set needsUpdate ( value ) {
  9109. if ( value === true ) this.update();
  9110. this._needsUpdate = value;
  9111. },
  9112. clone: function ( texture ) {
  9113. if ( texture === undefined ) texture = new THREE.Texture();
  9114. texture.image = this.image;
  9115. texture.mipmaps = this.mipmaps.slice(0);
  9116. texture.mapping = this.mapping;
  9117. texture.wrapS = this.wrapS;
  9118. texture.wrapT = this.wrapT;
  9119. texture.magFilter = this.magFilter;
  9120. texture.minFilter = this.minFilter;
  9121. texture.anisotropy = this.anisotropy;
  9122. texture.format = this.format;
  9123. texture.type = this.type;
  9124. texture.offset.copy( this.offset );
  9125. texture.repeat.copy( this.repeat );
  9126. texture.generateMipmaps = this.generateMipmaps;
  9127. texture.premultiplyAlpha = this.premultiplyAlpha;
  9128. texture.flipY = this.flipY;
  9129. texture.unpackAlignment = this.unpackAlignment;
  9130. return texture;
  9131. },
  9132. update: function () {
  9133. this.dispatchEvent( { type: 'update' } );
  9134. },
  9135. dispose: function () {
  9136. this.dispatchEvent( { type: 'dispose' } );
  9137. }
  9138. };
  9139. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  9140. THREE.TextureIdCount = 0;
  9141. /**
  9142. * @author alteredq / http://alteredqualia.com/
  9143. */
  9144. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9145. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9146. this.image = { width: width, height: height };
  9147. this.mipmaps = mipmaps;
  9148. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  9149. };
  9150. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  9151. THREE.CompressedTexture.prototype.clone = function () {
  9152. var texture = new THREE.CompressedTexture();
  9153. THREE.Texture.prototype.clone.call( this, texture );
  9154. return texture;
  9155. };
  9156. /**
  9157. * @author alteredq / http://alteredqualia.com/
  9158. */
  9159. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9160. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9161. this.image = { data: data, width: width, height: height };
  9162. };
  9163. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  9164. THREE.DataTexture.prototype.clone = function () {
  9165. var texture = new THREE.DataTexture();
  9166. THREE.Texture.prototype.clone.call( this, texture );
  9167. return texture;
  9168. };
  9169. /**
  9170. * @author alteredq / http://alteredqualia.com/
  9171. */
  9172. THREE.ParticleSystem = function ( geometry, material ) {
  9173. THREE.Object3D.call( this );
  9174. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9175. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  9176. this.sortParticles = false;
  9177. this.frustumCulled = false;
  9178. };
  9179. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  9180. THREE.ParticleSystem.prototype.clone = function ( object ) {
  9181. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  9182. object.sortParticles = this.sortParticles;
  9183. THREE.Object3D.prototype.clone.call( this, object );
  9184. return object;
  9185. };
  9186. /**
  9187. * @author mrdoob / http://mrdoob.com/
  9188. */
  9189. THREE.Line = function ( geometry, material, type ) {
  9190. THREE.Object3D.call( this );
  9191. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9192. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  9193. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  9194. };
  9195. THREE.LineStrip = 0;
  9196. THREE.LinePieces = 1;
  9197. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  9198. THREE.Line.prototype.clone = function ( object ) {
  9199. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  9200. THREE.Object3D.prototype.clone.call( this, object );
  9201. return object;
  9202. };
  9203. /**
  9204. * @author mrdoob / http://mrdoob.com/
  9205. * @author alteredq / http://alteredqualia.com/
  9206. * @author mikael emtinger / http://gomo.se/
  9207. * @author jonobr1 / http://jonobr1.com/
  9208. */
  9209. THREE.Mesh = function ( geometry, material ) {
  9210. THREE.Object3D.call( this );
  9211. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9212. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9213. this.updateMorphTargets();
  9214. };
  9215. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9216. THREE.Mesh.prototype.updateMorphTargets = function () {
  9217. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9218. this.morphTargetBase = -1;
  9219. this.morphTargetForcedOrder = [];
  9220. this.morphTargetInfluences = [];
  9221. this.morphTargetDictionary = {};
  9222. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9223. this.morphTargetInfluences.push( 0 );
  9224. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9225. }
  9226. }
  9227. };
  9228. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9229. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9230. return this.morphTargetDictionary[ name ];
  9231. }
  9232. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  9233. return 0;
  9234. };
  9235. THREE.Mesh.prototype.clone = function ( object ) {
  9236. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9237. THREE.Object3D.prototype.clone.call( this, object );
  9238. return object;
  9239. };
  9240. /**
  9241. * @author mikael emtinger / http://gomo.se/
  9242. * @author alteredq / http://alteredqualia.com/
  9243. */
  9244. THREE.Bone = function( belongsToSkin ) {
  9245. THREE.Object3D.call( this );
  9246. this.skin = belongsToSkin;
  9247. this.skinMatrix = new THREE.Matrix4();
  9248. };
  9249. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9250. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  9251. // update local
  9252. if ( this.matrixAutoUpdate ) {
  9253. forceUpdate |= this.updateMatrix();
  9254. }
  9255. // update skin matrix
  9256. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  9257. if( parentSkinMatrix ) {
  9258. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  9259. } else {
  9260. this.skinMatrix.copy( this.matrix );
  9261. }
  9262. this.matrixWorldNeedsUpdate = false;
  9263. forceUpdate = true;
  9264. }
  9265. // update children
  9266. var child, i, l = this.children.length;
  9267. for ( i = 0; i < l; i ++ ) {
  9268. this.children[ i ].update( this.skinMatrix, forceUpdate );
  9269. }
  9270. };
  9271. /**
  9272. * @author mikael emtinger / http://gomo.se/
  9273. * @author alteredq / http://alteredqualia.com/
  9274. */
  9275. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9276. THREE.Mesh.call( this, geometry, material );
  9277. //
  9278. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9279. // init bones
  9280. this.identityMatrix = new THREE.Matrix4();
  9281. this.bones = [];
  9282. this.boneMatrices = [];
  9283. var b, bone, gbone, p, q, s;
  9284. if ( this.geometry && this.geometry.bones !== undefined ) {
  9285. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  9286. gbone = this.geometry.bones[ b ];
  9287. p = gbone.pos;
  9288. q = gbone.rotq;
  9289. s = gbone.scl;
  9290. bone = this.addBone();
  9291. bone.name = gbone.name;
  9292. bone.position.set( p[0], p[1], p[2] );
  9293. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  9294. if ( s !== undefined ) {
  9295. bone.scale.set( s[0], s[1], s[2] );
  9296. } else {
  9297. bone.scale.set( 1, 1, 1 );
  9298. }
  9299. }
  9300. for ( b = 0; b < this.bones.length; b ++ ) {
  9301. gbone = this.geometry.bones[ b ];
  9302. bone = this.bones[ b ];
  9303. if ( gbone.parent === -1 ) {
  9304. this.add( bone );
  9305. } else {
  9306. this.bones[ gbone.parent ].add( bone );
  9307. }
  9308. }
  9309. //
  9310. var nBones = this.bones.length;
  9311. if ( this.useVertexTexture ) {
  9312. // layout (1 matrix = 4 pixels)
  9313. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9314. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9315. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9316. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9317. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9318. var size;
  9319. if ( nBones > 256 )
  9320. size = 64;
  9321. else if ( nBones > 64 )
  9322. size = 32;
  9323. else if ( nBones > 16 )
  9324. size = 16;
  9325. else
  9326. size = 8;
  9327. this.boneTextureWidth = size;
  9328. this.boneTextureHeight = size;
  9329. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9330. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9331. this.boneTexture.minFilter = THREE.NearestFilter;
  9332. this.boneTexture.magFilter = THREE.NearestFilter;
  9333. this.boneTexture.generateMipmaps = false;
  9334. this.boneTexture.flipY = false;
  9335. } else {
  9336. this.boneMatrices = new Float32Array( 16 * nBones );
  9337. }
  9338. this.pose();
  9339. }
  9340. };
  9341. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9342. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  9343. if ( bone === undefined ) {
  9344. bone = new THREE.Bone( this );
  9345. }
  9346. this.bones.push( bone );
  9347. return bone;
  9348. };
  9349. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  9350. var offsetMatrix = new THREE.Matrix4();
  9351. return function ( force ) {
  9352. this.matrixAutoUpdate && this.updateMatrix();
  9353. // update matrixWorld
  9354. if ( this.matrixWorldNeedsUpdate || force ) {
  9355. if ( this.parent ) {
  9356. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9357. } else {
  9358. this.matrixWorld.copy( this.matrix );
  9359. }
  9360. this.matrixWorldNeedsUpdate = false;
  9361. force = true;
  9362. }
  9363. // update children
  9364. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9365. var child = this.children[ i ];
  9366. if ( child instanceof THREE.Bone ) {
  9367. child.update( this.identityMatrix, false );
  9368. } else {
  9369. child.updateMatrixWorld( true );
  9370. }
  9371. }
  9372. // make a snapshot of the bones' rest position
  9373. if ( this.boneInverses == undefined ) {
  9374. this.boneInverses = [];
  9375. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9376. var inverse = new THREE.Matrix4();
  9377. inverse.getInverse( this.bones[ b ].skinMatrix );
  9378. this.boneInverses.push( inverse );
  9379. }
  9380. }
  9381. // flatten bone matrices to array
  9382. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9383. // compute the offset between the current and the original transform;
  9384. // TODO: we could get rid of this multiplication step if the skinMatrix
  9385. // was already representing the offset; however, this requires some
  9386. // major changes to the animation system
  9387. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  9388. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9389. }
  9390. if ( this.useVertexTexture ) {
  9391. this.boneTexture.needsUpdate = true;
  9392. }
  9393. };
  9394. }();
  9395. THREE.SkinnedMesh.prototype.pose = function () {
  9396. this.updateMatrixWorld( true );
  9397. this.normalizeSkinWeights();
  9398. };
  9399. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9400. if ( this.geometry instanceof THREE.Geometry ) {
  9401. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9402. var sw = this.geometry.skinWeights[ i ];
  9403. var scale = 1.0 / sw.lengthManhattan();
  9404. if ( scale !== Infinity ) {
  9405. sw.multiplyScalar( scale );
  9406. } else {
  9407. sw.set( 1 ); // this will be normalized by the shader anyway
  9408. }
  9409. }
  9410. } else {
  9411. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9412. }
  9413. };
  9414. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  9415. if ( object === undefined ) {
  9416. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9417. }
  9418. THREE.Mesh.prototype.clone.call( this, object );
  9419. return object;
  9420. };
  9421. /**
  9422. * @author alteredq / http://alteredqualia.com/
  9423. */
  9424. THREE.MorphAnimMesh = function ( geometry, material ) {
  9425. THREE.Mesh.call( this, geometry, material );
  9426. // API
  9427. this.duration = 1000; // milliseconds
  9428. this.mirroredLoop = false;
  9429. this.time = 0;
  9430. // internals
  9431. this.lastKeyframe = 0;
  9432. this.currentKeyframe = 0;
  9433. this.direction = 1;
  9434. this.directionBackwards = false;
  9435. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9436. };
  9437. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9438. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9439. this.startKeyframe = start;
  9440. this.endKeyframe = end;
  9441. this.length = this.endKeyframe - this.startKeyframe + 1;
  9442. };
  9443. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9444. this.direction = 1;
  9445. this.directionBackwards = false;
  9446. };
  9447. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9448. this.direction = -1;
  9449. this.directionBackwards = true;
  9450. };
  9451. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9452. var geometry = this.geometry;
  9453. if ( ! geometry.animations ) geometry.animations = {};
  9454. var firstAnimation, animations = geometry.animations;
  9455. var pattern = /([a-z]+)(\d+)/;
  9456. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9457. var morph = geometry.morphTargets[ i ];
  9458. var parts = morph.name.match( pattern );
  9459. if ( parts && parts.length > 1 ) {
  9460. var label = parts[ 1 ];
  9461. var num = parts[ 2 ];
  9462. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  9463. var animation = animations[ label ];
  9464. if ( i < animation.start ) animation.start = i;
  9465. if ( i > animation.end ) animation.end = i;
  9466. if ( ! firstAnimation ) firstAnimation = label;
  9467. }
  9468. }
  9469. geometry.firstAnimation = firstAnimation;
  9470. };
  9471. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9472. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9473. this.geometry.animations[ label ] = { start: start, end: end };
  9474. };
  9475. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9476. var animation = this.geometry.animations[ label ];
  9477. if ( animation ) {
  9478. this.setFrameRange( animation.start, animation.end );
  9479. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9480. this.time = 0;
  9481. } else {
  9482. console.warn( "animation[" + label + "] undefined" );
  9483. }
  9484. };
  9485. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9486. var frameTime = this.duration / this.length;
  9487. this.time += this.direction * delta;
  9488. if ( this.mirroredLoop ) {
  9489. if ( this.time > this.duration || this.time < 0 ) {
  9490. this.direction *= -1;
  9491. if ( this.time > this.duration ) {
  9492. this.time = this.duration;
  9493. this.directionBackwards = true;
  9494. }
  9495. if ( this.time < 0 ) {
  9496. this.time = 0;
  9497. this.directionBackwards = false;
  9498. }
  9499. }
  9500. } else {
  9501. this.time = this.time % this.duration;
  9502. if ( this.time < 0 ) this.time += this.duration;
  9503. }
  9504. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9505. if ( keyframe !== this.currentKeyframe ) {
  9506. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9507. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9508. this.morphTargetInfluences[ keyframe ] = 0;
  9509. this.lastKeyframe = this.currentKeyframe;
  9510. this.currentKeyframe = keyframe;
  9511. }
  9512. var mix = ( this.time % frameTime ) / frameTime;
  9513. if ( this.directionBackwards ) {
  9514. mix = 1 - mix;
  9515. }
  9516. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9517. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9518. };
  9519. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9520. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9521. object.duration = this.duration;
  9522. object.mirroredLoop = this.mirroredLoop;
  9523. object.time = this.time;
  9524. object.lastKeyframe = this.lastKeyframe;
  9525. object.currentKeyframe = this.currentKeyframe;
  9526. object.direction = this.direction;
  9527. object.directionBackwards = this.directionBackwards;
  9528. THREE.Mesh.prototype.clone.call( this, object );
  9529. return object;
  9530. };
  9531. /**
  9532. * @author mikael emtinger / http://gomo.se/
  9533. * @author alteredq / http://alteredqualia.com/
  9534. * @author mrdoob / http://mrdoob.com/
  9535. */
  9536. THREE.LOD = function () {
  9537. THREE.Object3D.call( this );
  9538. this.objects = [];
  9539. };
  9540. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9541. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9542. if ( distance === undefined ) distance = 0;
  9543. distance = Math.abs( distance );
  9544. for ( var l = 0; l < this.objects.length; l ++ ) {
  9545. if ( distance < this.objects[ l ].distance ) {
  9546. break;
  9547. }
  9548. }
  9549. this.objects.splice( l, 0, { distance: distance, object: object } );
  9550. this.add( object );
  9551. };
  9552. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9553. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9554. if ( distance < this.objects[ i ].distance ) {
  9555. break;
  9556. }
  9557. }
  9558. return this.objects[ i - 1 ].object;
  9559. };
  9560. THREE.LOD.prototype.update = function () {
  9561. var v1 = new THREE.Vector3();
  9562. var v2 = new THREE.Vector3();
  9563. return function ( camera ) {
  9564. if ( this.objects.length > 1 ) {
  9565. v1.setFromMatrixPosition( camera.matrixWorld );
  9566. v2.setFromMatrixPosition( this.matrixWorld );
  9567. var distance = v1.distanceTo( v2 );
  9568. this.objects[ 0 ].object.visible = true;
  9569. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9570. if ( distance >= this.objects[ i ].distance ) {
  9571. this.objects[ i - 1 ].object.visible = false;
  9572. this.objects[ i ].object.visible = true;
  9573. } else {
  9574. break;
  9575. }
  9576. }
  9577. for( ; i < l; i ++ ) {
  9578. this.objects[ i ].object.visible = false;
  9579. }
  9580. }
  9581. };
  9582. }();
  9583. THREE.LOD.prototype.clone = function ( object ) {
  9584. if ( object === undefined ) object = new THREE.LOD();
  9585. THREE.Object3D.prototype.clone.call( this, object );
  9586. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9587. var x = this.objects[i].object.clone();
  9588. x.visible = i === 0;
  9589. object.addLevel( x, this.objects[i].distance );
  9590. }
  9591. return object;
  9592. };
  9593. /**
  9594. * @author mikael emtinger / http://gomo.se/
  9595. * @author alteredq / http://alteredqualia.com/
  9596. */
  9597. THREE.Sprite = ( function () {
  9598. var vertices = new THREE.Float32Attribute( 3, 3 );
  9599. vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  9600. var geometry = new THREE.BufferGeometry();
  9601. geometry.addAttribute( 'position', vertices );
  9602. return function ( material ) {
  9603. THREE.Object3D.call( this );
  9604. this.geometry = geometry;
  9605. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9606. };
  9607. } )();
  9608. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9609. /*
  9610. * Custom update matrix
  9611. */
  9612. THREE.Sprite.prototype.updateMatrix = function () {
  9613. this.matrix.compose( this.position, this.quaternion, this.scale );
  9614. this.matrixWorldNeedsUpdate = true;
  9615. };
  9616. THREE.Sprite.prototype.clone = function ( object ) {
  9617. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9618. THREE.Object3D.prototype.clone.call( this, object );
  9619. return object;
  9620. };
  9621. // Backwards compatibility
  9622. THREE.Particle = THREE.Sprite;
  9623. /**
  9624. * @author mrdoob / http://mrdoob.com/
  9625. */
  9626. THREE.Scene = function () {
  9627. THREE.Object3D.call( this );
  9628. this.fog = null;
  9629. this.overrideMaterial = null;
  9630. this.autoUpdate = true; // checked by the renderer
  9631. this.matrixAutoUpdate = false;
  9632. this.__lights = [];
  9633. this.__objectsAdded = [];
  9634. this.__objectsRemoved = [];
  9635. };
  9636. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9637. THREE.Scene.prototype.__addObject = function ( object ) {
  9638. if ( object instanceof THREE.Light ) {
  9639. if ( this.__lights.indexOf( object ) === - 1 ) {
  9640. this.__lights.push( object );
  9641. }
  9642. if ( object.target && object.target.parent === undefined ) {
  9643. this.add( object.target );
  9644. }
  9645. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9646. this.__objectsAdded.push( object );
  9647. // check if previously removed
  9648. var i = this.__objectsRemoved.indexOf( object );
  9649. if ( i !== -1 ) {
  9650. this.__objectsRemoved.splice( i, 1 );
  9651. }
  9652. }
  9653. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9654. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9655. for ( var c = 0; c < object.children.length; c ++ ) {
  9656. this.__addObject( object.children[ c ] );
  9657. }
  9658. };
  9659. THREE.Scene.prototype.__removeObject = function ( object ) {
  9660. if ( object instanceof THREE.Light ) {
  9661. var i = this.__lights.indexOf( object );
  9662. if ( i !== -1 ) {
  9663. this.__lights.splice( i, 1 );
  9664. }
  9665. if ( object.shadowCascadeArray ) {
  9666. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9667. this.__removeObject( object.shadowCascadeArray[ x ] );
  9668. }
  9669. }
  9670. } else if ( !( object instanceof THREE.Camera ) ) {
  9671. this.__objectsRemoved.push( object );
  9672. // check if previously added
  9673. var i = this.__objectsAdded.indexOf( object );
  9674. if ( i !== -1 ) {
  9675. this.__objectsAdded.splice( i, 1 );
  9676. }
  9677. }
  9678. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9679. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9680. for ( var c = 0; c < object.children.length; c ++ ) {
  9681. this.__removeObject( object.children[ c ] );
  9682. }
  9683. };
  9684. THREE.Scene.prototype.clone = function ( object ) {
  9685. if ( object === undefined ) object = new THREE.Scene();
  9686. THREE.Object3D.prototype.clone.call(this, object);
  9687. if ( this.fog !== null ) object.fog = this.fog.clone();
  9688. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9689. object.autoUpdate = this.autoUpdate;
  9690. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9691. return object;
  9692. };
  9693. /**
  9694. * @author mrdoob / http://mrdoob.com/
  9695. * @author alteredq / http://alteredqualia.com/
  9696. */
  9697. THREE.Fog = function ( color, near, far ) {
  9698. this.name = '';
  9699. this.color = new THREE.Color( color );
  9700. this.near = ( near !== undefined ) ? near : 1;
  9701. this.far = ( far !== undefined ) ? far : 1000;
  9702. };
  9703. THREE.Fog.prototype.clone = function () {
  9704. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9705. };
  9706. /**
  9707. * @author mrdoob / http://mrdoob.com/
  9708. * @author alteredq / http://alteredqualia.com/
  9709. */
  9710. THREE.FogExp2 = function ( color, density ) {
  9711. this.name = '';
  9712. this.color = new THREE.Color( color );
  9713. this.density = ( density !== undefined ) ? density : 0.00025;
  9714. };
  9715. THREE.FogExp2.prototype.clone = function () {
  9716. return new THREE.FogExp2( this.color.getHex(), this.density );
  9717. };
  9718. /**
  9719. * @author mrdoob / http://mrdoob.com/
  9720. */
  9721. THREE.CanvasRenderer = function ( parameters ) {
  9722. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9723. var smoothstep = THREE.Math.smoothstep;
  9724. parameters = parameters || {};
  9725. var _this = this,
  9726. _renderData, _elements, _lights,
  9727. _projector = new THREE.Projector(),
  9728. _canvas = parameters.canvas !== undefined
  9729. ? parameters.canvas
  9730. : document.createElement( 'canvas' ),
  9731. _canvasWidth = _canvas.width,
  9732. _canvasHeight = _canvas.height,
  9733. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9734. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9735. _context = _canvas.getContext( '2d', {
  9736. alpha: parameters.alpha === true
  9737. } ),
  9738. _clearColor = new THREE.Color( 0x000000 ),
  9739. _clearAlpha = 0,
  9740. _contextGlobalAlpha = 1,
  9741. _contextGlobalCompositeOperation = 0,
  9742. _contextStrokeStyle = null,
  9743. _contextFillStyle = null,
  9744. _contextLineWidth = null,
  9745. _contextLineCap = null,
  9746. _contextLineJoin = null,
  9747. _contextDashSize = null,
  9748. _contextGapSize = 0,
  9749. _camera,
  9750. _v1, _v2, _v3, _v4,
  9751. _v5 = new THREE.RenderableVertex(),
  9752. _v6 = new THREE.RenderableVertex(),
  9753. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9754. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9755. _color = new THREE.Color(),
  9756. _color1 = new THREE.Color(),
  9757. _color2 = new THREE.Color(),
  9758. _color3 = new THREE.Color(),
  9759. _color4 = new THREE.Color(),
  9760. _diffuseColor = new THREE.Color(),
  9761. _emissiveColor = new THREE.Color(),
  9762. _lightColor = new THREE.Color(),
  9763. _patterns = {},
  9764. _image, _uvs,
  9765. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9766. _clipBox = new THREE.Box2(),
  9767. _clearBox = new THREE.Box2(),
  9768. _elemBox = new THREE.Box2(),
  9769. _ambientLight = new THREE.Color(),
  9770. _directionalLights = new THREE.Color(),
  9771. _pointLights = new THREE.Color(),
  9772. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9773. _centroid = new THREE.Vector3(),
  9774. _normal = new THREE.Vector3(),
  9775. _normalViewMatrix = new THREE.Matrix3();
  9776. // dash+gap fallbacks for Firefox and everything else
  9777. if ( _context.setLineDash === undefined ) {
  9778. if ( _context.mozDash !== undefined ) {
  9779. _context.setLineDash = function ( values ) {
  9780. _context.mozDash = values[ 0 ] !== null ? values : null;
  9781. }
  9782. } else {
  9783. _context.setLineDash = function () {}
  9784. }
  9785. }
  9786. this.domElement = _canvas;
  9787. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9788. ? parameters.devicePixelRatio
  9789. : self.devicePixelRatio !== undefined
  9790. ? self.devicePixelRatio
  9791. : 1;
  9792. this.autoClear = true;
  9793. this.sortObjects = true;
  9794. this.sortElements = true;
  9795. this.info = {
  9796. render: {
  9797. vertices: 0,
  9798. faces: 0
  9799. }
  9800. }
  9801. // WebGLRenderer compatibility
  9802. this.supportsVertexTextures = function () {};
  9803. this.setFaceCulling = function () {};
  9804. this.setSize = function ( width, height, updateStyle ) {
  9805. _canvasWidth = width * this.devicePixelRatio;
  9806. _canvasHeight = height * this.devicePixelRatio;
  9807. _canvas.width = _canvasWidth;
  9808. _canvas.height = _canvasHeight;
  9809. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9810. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9811. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9812. _canvas.style.width = width + 'px';
  9813. _canvas.style.height = height + 'px';
  9814. }
  9815. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  9816. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9817. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9818. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9819. _contextGlobalAlpha = 1;
  9820. _contextGlobalCompositeOperation = 0;
  9821. _contextStrokeStyle = null;
  9822. _contextFillStyle = null;
  9823. _contextLineWidth = null;
  9824. _contextLineCap = null;
  9825. _contextLineJoin = null;
  9826. this.setViewport( 0, 0, width, height );
  9827. };
  9828. this.setViewport = function ( x, y, width, height ) {
  9829. _context.setTransform( width / _canvasWidth, 0, 0, - height / _canvasHeight, x, _canvasHeight - y );
  9830. _context.translate( _canvasWidthHalf, _canvasHeightHalf );
  9831. };
  9832. this.setScissor = function () {};
  9833. this.enableScissorTest = function () {};
  9834. this.setClearColor = function ( color, alpha ) {
  9835. _clearColor.set( color );
  9836. _clearAlpha = alpha !== undefined ? alpha : 1;
  9837. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9838. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9839. };
  9840. this.setClearColorHex = function ( hex, alpha ) {
  9841. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9842. this.setClearColor( hex, alpha );
  9843. };
  9844. this.getMaxAnisotropy = function () {
  9845. return 0;
  9846. };
  9847. this.clear = function () {
  9848. if ( _clearBox.empty() === false ) {
  9849. _clearBox.intersect( _clipBox );
  9850. _clearBox.expandByScalar( 2 );
  9851. if ( _clearAlpha < 1 ) {
  9852. _context.clearRect(
  9853. _clearBox.min.x | 0,
  9854. _clearBox.min.y | 0,
  9855. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9856. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9857. );
  9858. }
  9859. if ( _clearAlpha > 0 ) {
  9860. setBlending( THREE.NormalBlending );
  9861. setOpacity( 1 );
  9862. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9863. _context.fillRect(
  9864. _clearBox.min.x | 0,
  9865. _clearBox.min.y | 0,
  9866. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9867. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9868. );
  9869. }
  9870. _clearBox.makeEmpty();
  9871. }
  9872. };
  9873. // compatibility
  9874. this.clearColor = function () {};
  9875. this.clearDepth = function () {};
  9876. this.clearStencil = function () {};
  9877. this.render = function ( scene, camera ) {
  9878. if ( camera instanceof THREE.Camera === false ) {
  9879. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9880. return;
  9881. }
  9882. if ( this.autoClear === true ) this.clear();
  9883. _this.info.render.vertices = 0;
  9884. _this.info.render.faces = 0;
  9885. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9886. _elements = _renderData.elements;
  9887. _lights = _renderData.lights;
  9888. _camera = camera;
  9889. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  9890. /* DEBUG
  9891. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9892. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9893. */
  9894. calculateLights();
  9895. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  9896. var element = _elements[ e ];
  9897. var material = element.material;
  9898. if ( material === undefined || material.visible === false ) continue;
  9899. _elemBox.makeEmpty();
  9900. if ( element instanceof THREE.RenderableSprite ) {
  9901. _v1 = element;
  9902. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9903. renderSprite( _v1, element, material );
  9904. } else if ( element instanceof THREE.RenderableLine ) {
  9905. _v1 = element.v1; _v2 = element.v2;
  9906. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9907. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9908. _elemBox.setFromPoints( [
  9909. _v1.positionScreen,
  9910. _v2.positionScreen
  9911. ] );
  9912. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9913. renderLine( _v1, _v2, element, material );
  9914. }
  9915. } else if ( element instanceof THREE.RenderableFace ) {
  9916. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9917. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9918. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9919. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9920. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9921. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9922. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9923. if ( material.overdraw > 0 ) {
  9924. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9925. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9926. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9927. }
  9928. _elemBox.setFromPoints( [
  9929. _v1.positionScreen,
  9930. _v2.positionScreen,
  9931. _v3.positionScreen
  9932. ] );
  9933. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9934. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9935. }
  9936. }
  9937. /* DEBUG
  9938. setLineWidth( 1 );
  9939. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9940. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9941. */
  9942. _clearBox.union( _elemBox );
  9943. }
  9944. /* DEBUG
  9945. setLineWidth( 1 );
  9946. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9947. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9948. */
  9949. // _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9950. };
  9951. //
  9952. function calculateLights() {
  9953. _ambientLight.setRGB( 0, 0, 0 );
  9954. _directionalLights.setRGB( 0, 0, 0 );
  9955. _pointLights.setRGB( 0, 0, 0 );
  9956. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9957. var light = _lights[ l ];
  9958. var lightColor = light.color;
  9959. if ( light instanceof THREE.AmbientLight ) {
  9960. _ambientLight.add( lightColor );
  9961. } else if ( light instanceof THREE.DirectionalLight ) {
  9962. // for sprites
  9963. _directionalLights.add( lightColor );
  9964. } else if ( light instanceof THREE.PointLight ) {
  9965. // for sprites
  9966. _pointLights.add( lightColor );
  9967. }
  9968. }
  9969. }
  9970. function calculateLight( position, normal, color ) {
  9971. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9972. var light = _lights[ l ];
  9973. _lightColor.copy( light.color );
  9974. if ( light instanceof THREE.DirectionalLight ) {
  9975. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9976. var amount = normal.dot( lightPosition );
  9977. if ( amount <= 0 ) continue;
  9978. amount *= light.intensity;
  9979. color.add( _lightColor.multiplyScalar( amount ) );
  9980. } else if ( light instanceof THREE.PointLight ) {
  9981. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9982. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9983. if ( amount <= 0 ) continue;
  9984. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9985. if ( amount == 0 ) continue;
  9986. amount *= light.intensity;
  9987. color.add( _lightColor.multiplyScalar( amount ) );
  9988. }
  9989. }
  9990. }
  9991. function renderSprite( v1, element, material ) {
  9992. setOpacity( material.opacity );
  9993. setBlending( material.blending );
  9994. var scaleX = element.scale.x * _canvasWidthHalf;
  9995. var scaleY = element.scale.y * _canvasHeightHalf;
  9996. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9997. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9998. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9999. if ( material instanceof THREE.SpriteMaterial ||
  10000. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  10001. var texture = material.map;
  10002. if ( texture !== null ) {
  10003. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10004. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10005. textureToPattern( texture );
  10006. }
  10007. texture.addEventListener( 'update', onTextureUpdate );
  10008. }
  10009. var pattern = _patterns[ texture.id ];
  10010. if ( pattern !== undefined ) {
  10011. setFillStyle( pattern );
  10012. } else {
  10013. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  10014. }
  10015. //
  10016. var bitmap = texture.image;
  10017. var ox = bitmap.width * texture.offset.x;
  10018. var oy = bitmap.height * texture.offset.y;
  10019. var sx = bitmap.width * texture.repeat.x;
  10020. var sy = bitmap.height * texture.repeat.y;
  10021. var cx = scaleX / sx;
  10022. var cy = scaleY / sy;
  10023. _context.save();
  10024. _context.translate( v1.x, v1.y );
  10025. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10026. _context.translate( - scaleX / 2, - scaleY / 2 );
  10027. _context.scale( cx, cy );
  10028. _context.translate( - ox, - oy );
  10029. _context.fillRect( ox, oy, sx, sy );
  10030. _context.restore();
  10031. } else { // no texture
  10032. setFillStyle( material.color.getStyle() );
  10033. _context.save();
  10034. _context.translate( v1.x, v1.y );
  10035. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10036. _context.scale( scaleX, - scaleY );
  10037. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  10038. _context.restore();
  10039. }
  10040. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  10041. setStrokeStyle( material.color.getStyle() );
  10042. setFillStyle( material.color.getStyle() );
  10043. _context.save();
  10044. _context.translate( v1.x, v1.y );
  10045. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10046. _context.scale( scaleX, scaleY );
  10047. material.program( _context );
  10048. _context.restore();
  10049. }
  10050. /* DEBUG
  10051. setStrokeStyle( 'rgb(255,255,0)' );
  10052. _context.beginPath();
  10053. _context.moveTo( v1.x - 10, v1.y );
  10054. _context.lineTo( v1.x + 10, v1.y );
  10055. _context.moveTo( v1.x, v1.y - 10 );
  10056. _context.lineTo( v1.x, v1.y + 10 );
  10057. _context.stroke();
  10058. */
  10059. }
  10060. function renderLine( v1, v2, element, material ) {
  10061. setOpacity( material.opacity );
  10062. setBlending( material.blending );
  10063. _context.beginPath();
  10064. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  10065. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  10066. if ( material instanceof THREE.LineBasicMaterial ) {
  10067. setLineWidth( material.linewidth );
  10068. setLineCap( material.linecap );
  10069. setLineJoin( material.linejoin );
  10070. if ( material.vertexColors !== THREE.VertexColors ) {
  10071. setStrokeStyle( material.color.getStyle() );
  10072. } else {
  10073. var colorStyle1 = element.vertexColors[0].getStyle();
  10074. var colorStyle2 = element.vertexColors[1].getStyle();
  10075. if ( colorStyle1 === colorStyle2 ) {
  10076. setStrokeStyle( colorStyle1 );
  10077. } else {
  10078. try {
  10079. var grad = _context.createLinearGradient(
  10080. v1.positionScreen.x,
  10081. v1.positionScreen.y,
  10082. v2.positionScreen.x,
  10083. v2.positionScreen.y
  10084. );
  10085. grad.addColorStop( 0, colorStyle1 );
  10086. grad.addColorStop( 1, colorStyle2 );
  10087. } catch ( exception ) {
  10088. grad = colorStyle1;
  10089. }
  10090. setStrokeStyle( grad );
  10091. }
  10092. }
  10093. _context.stroke();
  10094. _elemBox.expandByScalar( material.linewidth * 2 );
  10095. } else if ( material instanceof THREE.LineDashedMaterial ) {
  10096. setLineWidth( material.linewidth );
  10097. setLineCap( material.linecap );
  10098. setLineJoin( material.linejoin );
  10099. setStrokeStyle( material.color.getStyle() );
  10100. setDashAndGap( material.dashSize, material.gapSize );
  10101. _context.stroke();
  10102. _elemBox.expandByScalar( material.linewidth * 2 );
  10103. setDashAndGap( null, null );
  10104. }
  10105. }
  10106. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  10107. _this.info.render.vertices += 3;
  10108. _this.info.render.faces ++;
  10109. setOpacity( material.opacity );
  10110. setBlending( material.blending );
  10111. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  10112. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  10113. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  10114. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  10115. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  10116. _diffuseColor.copy( material.color );
  10117. _emissiveColor.copy( material.emissive );
  10118. if ( material.vertexColors === THREE.FaceColors ) {
  10119. _diffuseColor.multiply( element.color );
  10120. }
  10121. _color.copy( _ambientLight );
  10122. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  10123. calculateLight( _centroid, element.normalModel, _color );
  10124. _color.multiply( _diffuseColor ).add( _emissiveColor );
  10125. material.wireframe === true
  10126. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10127. : fillPath( _color );
  10128. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  10129. if ( material.map !== null ) {
  10130. if ( material.map.mapping instanceof THREE.UVMapping ) {
  10131. _uvs = element.uvs;
  10132. 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 );
  10133. }
  10134. } else if ( material.envMap !== null ) {
  10135. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  10136. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  10137. _uv1x = 0.5 * _normal.x + 0.5;
  10138. _uv1y = 0.5 * _normal.y + 0.5;
  10139. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  10140. _uv2x = 0.5 * _normal.x + 0.5;
  10141. _uv2y = 0.5 * _normal.y + 0.5;
  10142. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10143. _uv3x = 0.5 * _normal.x + 0.5;
  10144. _uv3y = 0.5 * _normal.y + 0.5;
  10145. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  10146. } else if ( material.envMap.mapping instanceof THREE.SphericalRefractionMapping ) {
  10147. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  10148. _uv1x = - 0.5 * _normal.x + 0.5;
  10149. _uv1y = - 0.5 * _normal.y + 0.5;
  10150. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  10151. _uv2x = - 0.5 * _normal.x + 0.5;
  10152. _uv2y = - 0.5 * _normal.y + 0.5;
  10153. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10154. _uv3x = - 0.5 * _normal.x + 0.5;
  10155. _uv3y = - 0.5 * _normal.y + 0.5;
  10156. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  10157. }
  10158. } else {
  10159. _color.copy( material.color );
  10160. if ( material.vertexColors === THREE.FaceColors ) {
  10161. _color.multiply( element.color );
  10162. }
  10163. material.wireframe === true
  10164. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10165. : fillPath( _color );
  10166. }
  10167. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  10168. _color.r = _color.g = _color.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _camera.near, _camera.far );
  10169. material.wireframe === true
  10170. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10171. : fillPath( _color );
  10172. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  10173. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  10174. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  10175. material.wireframe === true
  10176. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10177. : fillPath( _color );
  10178. } else {
  10179. _color.setRGB( 1, 1, 1 );
  10180. material.wireframe === true
  10181. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10182. : fillPath( _color );
  10183. }
  10184. }
  10185. //
  10186. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  10187. _context.beginPath();
  10188. _context.moveTo( x0, y0 );
  10189. _context.lineTo( x1, y1 );
  10190. _context.lineTo( x2, y2 );
  10191. _context.closePath();
  10192. }
  10193. function strokePath( color, linewidth, linecap, linejoin ) {
  10194. setLineWidth( linewidth );
  10195. setLineCap( linecap );
  10196. setLineJoin( linejoin );
  10197. setStrokeStyle( color.getStyle() );
  10198. _context.stroke();
  10199. _elemBox.expandByScalar( linewidth * 2 );
  10200. }
  10201. function fillPath( color ) {
  10202. setFillStyle( color.getStyle() );
  10203. _context.fill();
  10204. }
  10205. function onTextureUpdate ( event ) {
  10206. textureToPattern( event.target );
  10207. }
  10208. function textureToPattern( texture ) {
  10209. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  10210. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  10211. var image = texture.image;
  10212. var canvas = document.createElement( 'canvas' );
  10213. canvas.width = image.width;
  10214. canvas.height = image.height;
  10215. var context = canvas.getContext( '2d' );
  10216. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  10217. context.drawImage( image, 0, 0 );
  10218. _patterns[ texture.id ] = _context.createPattern(
  10219. canvas, repeatX === true && repeatY === true
  10220. ? 'repeat'
  10221. : repeatX === true && repeatY === false
  10222. ? 'repeat-x'
  10223. : repeatX === false && repeatY === true
  10224. ? 'repeat-y'
  10225. : 'no-repeat'
  10226. );
  10227. }
  10228. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  10229. if ( texture instanceof THREE.DataTexture ) return;
  10230. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10231. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10232. textureToPattern( texture );
  10233. }
  10234. texture.addEventListener( 'update', onTextureUpdate );
  10235. }
  10236. var pattern = _patterns[ texture.id ];
  10237. if ( pattern !== undefined ) {
  10238. setFillStyle( pattern );
  10239. } else {
  10240. setFillStyle( 'rgba(0,0,0,1)' );
  10241. _context.fill();
  10242. return;
  10243. }
  10244. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10245. var a, b, c, d, e, f, det, idet,
  10246. offsetX = texture.offset.x / texture.repeat.x,
  10247. offsetY = texture.offset.y / texture.repeat.y,
  10248. width = texture.image.width * texture.repeat.x,
  10249. height = texture.image.height * texture.repeat.y;
  10250. u0 = ( u0 + offsetX ) * width;
  10251. v0 = ( v0 + offsetY ) * height;
  10252. u1 = ( u1 + offsetX ) * width;
  10253. v1 = ( v1 + offsetY ) * height;
  10254. u2 = ( u2 + offsetX ) * width;
  10255. v2 = ( v2 + offsetY ) * height;
  10256. x1 -= x0; y1 -= y0;
  10257. x2 -= x0; y2 -= y0;
  10258. u1 -= u0; v1 -= v0;
  10259. u2 -= u0; v2 -= v0;
  10260. det = u1 * v2 - u2 * v1;
  10261. if ( det === 0 ) return;
  10262. idet = 1 / det;
  10263. a = ( v2 * x1 - v1 * x2 ) * idet;
  10264. b = ( v2 * y1 - v1 * y2 ) * idet;
  10265. c = ( u1 * x2 - u2 * x1 ) * idet;
  10266. d = ( u1 * y2 - u2 * y1 ) * idet;
  10267. e = x0 - a * u0 - c * v0;
  10268. f = y0 - b * u0 - d * v0;
  10269. _context.save();
  10270. _context.transform( a, b, c, d, e, f );
  10271. _context.fill();
  10272. _context.restore();
  10273. }
  10274. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  10275. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10276. var a, b, c, d, e, f, det, idet,
  10277. width = image.width - 1,
  10278. height = image.height - 1;
  10279. u0 *= width; v0 *= height;
  10280. u1 *= width; v1 *= height;
  10281. u2 *= width; v2 *= height;
  10282. x1 -= x0; y1 -= y0;
  10283. x2 -= x0; y2 -= y0;
  10284. u1 -= u0; v1 -= v0;
  10285. u2 -= u0; v2 -= v0;
  10286. det = u1 * v2 - u2 * v1;
  10287. idet = 1 / det;
  10288. a = ( v2 * x1 - v1 * x2 ) * idet;
  10289. b = ( v2 * y1 - v1 * y2 ) * idet;
  10290. c = ( u1 * x2 - u2 * x1 ) * idet;
  10291. d = ( u1 * y2 - u2 * y1 ) * idet;
  10292. e = x0 - a * u0 - c * v0;
  10293. f = y0 - b * u0 - d * v0;
  10294. _context.save();
  10295. _context.transform( a, b, c, d, e, f );
  10296. _context.clip();
  10297. _context.drawImage( image, 0, 0 );
  10298. _context.restore();
  10299. }
  10300. // Hide anti-alias gaps
  10301. function expand( v1, v2, pixels ) {
  10302. var x = v2.x - v1.x, y = v2.y - v1.y,
  10303. det = x * x + y * y, idet;
  10304. if ( det === 0 ) return;
  10305. idet = pixels / Math.sqrt( det );
  10306. x *= idet; y *= idet;
  10307. v2.x += x; v2.y += y;
  10308. v1.x -= x; v1.y -= y;
  10309. }
  10310. // Context cached methods.
  10311. function setOpacity( value ) {
  10312. if ( _contextGlobalAlpha !== value ) {
  10313. _context.globalAlpha = value;
  10314. _contextGlobalAlpha = value;
  10315. }
  10316. }
  10317. function setBlending( value ) {
  10318. if ( _contextGlobalCompositeOperation !== value ) {
  10319. if ( value === THREE.NormalBlending ) {
  10320. _context.globalCompositeOperation = 'source-over';
  10321. } else if ( value === THREE.AdditiveBlending ) {
  10322. _context.globalCompositeOperation = 'lighter';
  10323. } else if ( value === THREE.SubtractiveBlending ) {
  10324. _context.globalCompositeOperation = 'darker';
  10325. }
  10326. _contextGlobalCompositeOperation = value;
  10327. }
  10328. }
  10329. function setLineWidth( value ) {
  10330. if ( _contextLineWidth !== value ) {
  10331. _context.lineWidth = value;
  10332. _contextLineWidth = value;
  10333. }
  10334. }
  10335. function setLineCap( value ) {
  10336. // "butt", "round", "square"
  10337. if ( _contextLineCap !== value ) {
  10338. _context.lineCap = value;
  10339. _contextLineCap = value;
  10340. }
  10341. }
  10342. function setLineJoin( value ) {
  10343. // "round", "bevel", "miter"
  10344. if ( _contextLineJoin !== value ) {
  10345. _context.lineJoin = value;
  10346. _contextLineJoin = value;
  10347. }
  10348. }
  10349. function setStrokeStyle( value ) {
  10350. if ( _contextStrokeStyle !== value ) {
  10351. _context.strokeStyle = value;
  10352. _contextStrokeStyle = value;
  10353. }
  10354. }
  10355. function setFillStyle( value ) {
  10356. if ( _contextFillStyle !== value ) {
  10357. _context.fillStyle = value;
  10358. _contextFillStyle = value;
  10359. }
  10360. }
  10361. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  10362. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  10363. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  10364. _contextDashSize = dashSizeValue;
  10365. _contextGapSize = gapSizeValue;
  10366. }
  10367. }
  10368. };
  10369. /**
  10370. * Shader chunks for WebLG Shader library
  10371. *
  10372. * @author alteredq / http://alteredqualia.com/
  10373. * @author mrdoob / http://mrdoob.com/
  10374. * @author mikael emtinger / http://gomo.se/
  10375. */
  10376. THREE.ShaderChunk = {
  10377. // FOG
  10378. fog_pars_fragment: [
  10379. "#ifdef USE_FOG",
  10380. " uniform vec3 fogColor;",
  10381. " #ifdef FOG_EXP2",
  10382. " uniform float fogDensity;",
  10383. " #else",
  10384. " uniform float fogNear;",
  10385. " uniform float fogFar;",
  10386. " #endif",
  10387. "#endif"
  10388. ].join("\n"),
  10389. fog_fragment: [
  10390. "#ifdef USE_FOG",
  10391. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10392. " #ifdef FOG_EXP2",
  10393. " const float LOG2 = 1.442695;",
  10394. " float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  10395. " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  10396. " #else",
  10397. " float fogFactor = smoothstep( fogNear, fogFar, depth );",
  10398. " #endif",
  10399. " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  10400. "#endif"
  10401. ].join("\n"),
  10402. // ENVIRONMENT MAP
  10403. envmap_pars_fragment: [
  10404. "#ifdef USE_ENVMAP",
  10405. " uniform float reflectivity;",
  10406. " uniform samplerCube envMap;",
  10407. " uniform float flipEnvMap;",
  10408. " uniform int combine;",
  10409. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10410. " uniform bool useRefract;",
  10411. " uniform float refractionRatio;",
  10412. " #else",
  10413. " varying vec3 vReflect;",
  10414. " #endif",
  10415. "#endif"
  10416. ].join("\n"),
  10417. envmap_fragment: [
  10418. "#ifdef USE_ENVMAP",
  10419. " vec3 reflectVec;",
  10420. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10421. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10422. // http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations
  10423. // "Transforming Normal Vectors with the Inverse Transformation"
  10424. " vec3 worldNormal = normalize( vec3( vec4( normal, 0.0 ) * viewMatrix ) );",
  10425. " if ( useRefract ) {",
  10426. " reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );",
  10427. " } else { ",
  10428. " reflectVec = reflect( cameraToVertex, worldNormal );",
  10429. " }",
  10430. " #else",
  10431. " reflectVec = vReflect;",
  10432. " #endif",
  10433. " #ifdef DOUBLE_SIDED",
  10434. " float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10435. " vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10436. " #else",
  10437. " vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10438. " #endif",
  10439. " #ifdef GAMMA_INPUT",
  10440. " cubeColor.xyz *= cubeColor.xyz;",
  10441. " #endif",
  10442. " if ( combine == 1 ) {",
  10443. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  10444. " } else if ( combine == 2 ) {",
  10445. " gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  10446. " } else {",
  10447. " gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  10448. " }",
  10449. "#endif"
  10450. ].join("\n"),
  10451. envmap_pars_vertex: [
  10452. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10453. " varying vec3 vReflect;",
  10454. " uniform float refractionRatio;",
  10455. " uniform bool useRefract;",
  10456. "#endif"
  10457. ].join("\n"),
  10458. worldpos_vertex : [
  10459. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  10460. " #ifdef USE_SKINNING",
  10461. " vec4 worldPosition = modelMatrix * skinned;",
  10462. " #endif",
  10463. " #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10464. " vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  10465. " #endif",
  10466. " #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10467. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10468. " #endif",
  10469. "#endif"
  10470. ].join("\n"),
  10471. envmap_vertex : [
  10472. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10473. " vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10474. " worldNormal = normalize( worldNormal );",
  10475. " vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10476. " if ( useRefract ) {",
  10477. " vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10478. " } else {",
  10479. " vReflect = reflect( cameraToVertex, worldNormal );",
  10480. " }",
  10481. "#endif"
  10482. ].join("\n"),
  10483. // COLOR MAP (particles)
  10484. map_particle_pars_fragment: [
  10485. "#ifdef USE_MAP",
  10486. " uniform sampler2D map;",
  10487. "#endif"
  10488. ].join("\n"),
  10489. map_particle_fragment: [
  10490. "#ifdef USE_MAP",
  10491. " gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10492. "#endif"
  10493. ].join("\n"),
  10494. // COLOR MAP (triangles)
  10495. map_pars_vertex: [
  10496. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10497. " varying vec2 vUv;",
  10498. " uniform vec4 offsetRepeat;",
  10499. "#endif"
  10500. ].join("\n"),
  10501. map_pars_fragment: [
  10502. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10503. " varying vec2 vUv;",
  10504. "#endif",
  10505. "#ifdef USE_MAP",
  10506. " uniform sampler2D map;",
  10507. "#endif"
  10508. ].join("\n"),
  10509. map_vertex: [
  10510. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10511. " vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10512. "#endif"
  10513. ].join("\n"),
  10514. map_fragment: [
  10515. "#ifdef USE_MAP",
  10516. " vec4 texelColor = texture2D( map, vUv );",
  10517. " #ifdef GAMMA_INPUT",
  10518. " texelColor.xyz *= texelColor.xyz;",
  10519. " #endif",
  10520. " gl_FragColor = gl_FragColor * texelColor;",
  10521. "#endif"
  10522. ].join("\n"),
  10523. // LIGHT MAP
  10524. lightmap_pars_fragment: [
  10525. "#ifdef USE_LIGHTMAP",
  10526. " varying vec2 vUv2;",
  10527. " uniform sampler2D lightMap;",
  10528. "#endif"
  10529. ].join("\n"),
  10530. lightmap_pars_vertex: [
  10531. "#ifdef USE_LIGHTMAP",
  10532. " varying vec2 vUv2;",
  10533. "#endif"
  10534. ].join("\n"),
  10535. lightmap_fragment: [
  10536. "#ifdef USE_LIGHTMAP",
  10537. " gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10538. "#endif"
  10539. ].join("\n"),
  10540. lightmap_vertex: [
  10541. "#ifdef USE_LIGHTMAP",
  10542. " vUv2 = uv2;",
  10543. "#endif"
  10544. ].join("\n"),
  10545. // BUMP MAP
  10546. bumpmap_pars_fragment: [
  10547. "#ifdef USE_BUMPMAP",
  10548. " uniform sampler2D bumpMap;",
  10549. " uniform float bumpScale;",
  10550. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10551. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10552. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10553. " vec2 dHdxy_fwd() {",
  10554. " vec2 dSTdx = dFdx( vUv );",
  10555. " vec2 dSTdy = dFdy( vUv );",
  10556. " float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10557. " float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10558. " float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10559. " return vec2( dBx, dBy );",
  10560. " }",
  10561. " vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10562. " vec3 vSigmaX = dFdx( surf_pos );",
  10563. " vec3 vSigmaY = dFdy( surf_pos );",
  10564. " vec3 vN = surf_norm;", // normalized
  10565. " vec3 R1 = cross( vSigmaY, vN );",
  10566. " vec3 R2 = cross( vN, vSigmaX );",
  10567. " float fDet = dot( vSigmaX, R1 );",
  10568. " vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10569. " return normalize( abs( fDet ) * surf_norm - vGrad );",
  10570. " }",
  10571. "#endif"
  10572. ].join("\n"),
  10573. // NORMAL MAP
  10574. normalmap_pars_fragment: [
  10575. "#ifdef USE_NORMALMAP",
  10576. " uniform sampler2D normalMap;",
  10577. " uniform vec2 normalScale;",
  10578. // Per-Pixel Tangent Space Normal Mapping
  10579. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10580. " vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10581. " vec3 q0 = dFdx( eye_pos.xyz );",
  10582. " vec3 q1 = dFdy( eye_pos.xyz );",
  10583. " vec2 st0 = dFdx( vUv.st );",
  10584. " vec2 st1 = dFdy( vUv.st );",
  10585. " vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10586. " vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10587. " vec3 N = normalize( surf_norm );",
  10588. " vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10589. " mapN.xy = normalScale * mapN.xy;",
  10590. " mat3 tsn = mat3( S, T, N );",
  10591. " return normalize( tsn * mapN );",
  10592. " }",
  10593. "#endif"
  10594. ].join("\n"),
  10595. // SPECULAR MAP
  10596. specularmap_pars_fragment: [
  10597. "#ifdef USE_SPECULARMAP",
  10598. " uniform sampler2D specularMap;",
  10599. "#endif"
  10600. ].join("\n"),
  10601. specularmap_fragment: [
  10602. "float specularStrength;",
  10603. "#ifdef USE_SPECULARMAP",
  10604. " vec4 texelSpecular = texture2D( specularMap, vUv );",
  10605. " specularStrength = texelSpecular.r;",
  10606. "#else",
  10607. " specularStrength = 1.0;",
  10608. "#endif"
  10609. ].join("\n"),
  10610. // LIGHTS LAMBERT
  10611. lights_lambert_pars_vertex: [
  10612. "uniform vec3 ambient;",
  10613. "uniform vec3 diffuse;",
  10614. "uniform vec3 emissive;",
  10615. "uniform vec3 ambientLightColor;",
  10616. "#if MAX_DIR_LIGHTS > 0",
  10617. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10618. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10619. "#endif",
  10620. "#if MAX_HEMI_LIGHTS > 0",
  10621. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10622. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10623. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10624. "#endif",
  10625. "#if MAX_POINT_LIGHTS > 0",
  10626. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10627. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10628. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10629. "#endif",
  10630. "#if MAX_SPOT_LIGHTS > 0",
  10631. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10632. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10633. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10634. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10635. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10636. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10637. "#endif",
  10638. "#ifdef WRAP_AROUND",
  10639. " uniform vec3 wrapRGB;",
  10640. "#endif"
  10641. ].join("\n"),
  10642. lights_lambert_vertex: [
  10643. "vLightFront = vec3( 0.0 );",
  10644. "#ifdef DOUBLE_SIDED",
  10645. " vLightBack = vec3( 0.0 );",
  10646. "#endif",
  10647. "transformedNormal = normalize( transformedNormal );",
  10648. "#if MAX_DIR_LIGHTS > 0",
  10649. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10650. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10651. " vec3 dirVector = normalize( lDirection.xyz );",
  10652. " float dotProduct = dot( transformedNormal, dirVector );",
  10653. " vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10654. " #ifdef DOUBLE_SIDED",
  10655. " vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10656. " #ifdef WRAP_AROUND",
  10657. " vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10658. " #endif",
  10659. " #endif",
  10660. " #ifdef WRAP_AROUND",
  10661. " vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10662. " directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10663. " #ifdef DOUBLE_SIDED",
  10664. " directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10665. " #endif",
  10666. " #endif",
  10667. " vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10668. " #ifdef DOUBLE_SIDED",
  10669. " vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10670. " #endif",
  10671. "}",
  10672. "#endif",
  10673. "#if MAX_POINT_LIGHTS > 0",
  10674. " for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10675. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10676. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10677. " float lDistance = 1.0;",
  10678. " if ( pointLightDistance[ i ] > 0.0 )",
  10679. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10680. " lVector = normalize( lVector );",
  10681. " float dotProduct = dot( transformedNormal, lVector );",
  10682. " vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10683. " #ifdef DOUBLE_SIDED",
  10684. " vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10685. " #ifdef WRAP_AROUND",
  10686. " vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10687. " #endif",
  10688. " #endif",
  10689. " #ifdef WRAP_AROUND",
  10690. " vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10691. " pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10692. " #ifdef DOUBLE_SIDED",
  10693. " pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10694. " #endif",
  10695. " #endif",
  10696. " vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10697. " #ifdef DOUBLE_SIDED",
  10698. " vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10699. " #endif",
  10700. " }",
  10701. "#endif",
  10702. "#if MAX_SPOT_LIGHTS > 0",
  10703. " for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10704. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10705. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10706. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10707. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10708. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10709. " float lDistance = 1.0;",
  10710. " if ( spotLightDistance[ i ] > 0.0 )",
  10711. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10712. " lVector = normalize( lVector );",
  10713. " float dotProduct = dot( transformedNormal, lVector );",
  10714. " vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10715. " #ifdef DOUBLE_SIDED",
  10716. " vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10717. " #ifdef WRAP_AROUND",
  10718. " vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10719. " #endif",
  10720. " #endif",
  10721. " #ifdef WRAP_AROUND",
  10722. " vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10723. " spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10724. " #ifdef DOUBLE_SIDED",
  10725. " spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10726. " #endif",
  10727. " #endif",
  10728. " vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10729. " #ifdef DOUBLE_SIDED",
  10730. " vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10731. " #endif",
  10732. " }",
  10733. " }",
  10734. "#endif",
  10735. "#if MAX_HEMI_LIGHTS > 0",
  10736. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10737. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10738. " vec3 lVector = normalize( lDirection.xyz );",
  10739. " float dotProduct = dot( transformedNormal, lVector );",
  10740. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10741. " float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10742. " vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10743. " #ifdef DOUBLE_SIDED",
  10744. " vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10745. " #endif",
  10746. " }",
  10747. "#endif",
  10748. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10749. "#ifdef DOUBLE_SIDED",
  10750. " vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10751. "#endif"
  10752. ].join("\n"),
  10753. // LIGHTS PHONG
  10754. lights_phong_pars_vertex: [
  10755. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10756. " varying vec3 vWorldPosition;",
  10757. "#endif"
  10758. ].join("\n"),
  10759. lights_phong_vertex: [
  10760. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10761. " vWorldPosition = worldPosition.xyz;",
  10762. "#endif"
  10763. ].join("\n"),
  10764. lights_phong_pars_fragment: [
  10765. "uniform vec3 ambientLightColor;",
  10766. "#if MAX_DIR_LIGHTS > 0",
  10767. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10768. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10769. "#endif",
  10770. "#if MAX_HEMI_LIGHTS > 0",
  10771. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10772. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10773. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10774. "#endif",
  10775. "#if MAX_POINT_LIGHTS > 0",
  10776. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10777. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10778. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10779. "#endif",
  10780. "#if MAX_SPOT_LIGHTS > 0",
  10781. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10782. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10783. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10784. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10785. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10786. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10787. "#endif",
  10788. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10789. " varying vec3 vWorldPosition;",
  10790. "#endif",
  10791. "#ifdef WRAP_AROUND",
  10792. " uniform vec3 wrapRGB;",
  10793. "#endif",
  10794. "varying vec3 vViewPosition;",
  10795. "varying vec3 vNormal;"
  10796. ].join("\n"),
  10797. lights_phong_fragment: [
  10798. "vec3 normal = normalize( vNormal );",
  10799. "vec3 viewPosition = normalize( vViewPosition );",
  10800. "#ifdef DOUBLE_SIDED",
  10801. " normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10802. "#endif",
  10803. "#ifdef USE_NORMALMAP",
  10804. " normal = perturbNormal2Arb( -vViewPosition, normal );",
  10805. "#elif defined( USE_BUMPMAP )",
  10806. " normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10807. "#endif",
  10808. "#if MAX_POINT_LIGHTS > 0",
  10809. " vec3 pointDiffuse = vec3( 0.0 );",
  10810. " vec3 pointSpecular = vec3( 0.0 );",
  10811. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10812. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10813. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10814. " float lDistance = 1.0;",
  10815. " if ( pointLightDistance[ i ] > 0.0 )",
  10816. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10817. " lVector = normalize( lVector );",
  10818. // diffuse
  10819. " float dotProduct = dot( normal, lVector );",
  10820. " #ifdef WRAP_AROUND",
  10821. " float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10822. " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10823. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10824. " #else",
  10825. " float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10826. " #endif",
  10827. " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10828. // specular
  10829. " vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10830. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10831. " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10832. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10833. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10834. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  10835. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10836. " }",
  10837. "#endif",
  10838. "#if MAX_SPOT_LIGHTS > 0",
  10839. " vec3 spotDiffuse = vec3( 0.0 );",
  10840. " vec3 spotSpecular = vec3( 0.0 );",
  10841. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10842. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10843. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10844. " float lDistance = 1.0;",
  10845. " if ( spotLightDistance[ i ] > 0.0 )",
  10846. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10847. " lVector = normalize( lVector );",
  10848. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10849. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10850. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10851. // diffuse
  10852. " float dotProduct = dot( normal, lVector );",
  10853. " #ifdef WRAP_AROUND",
  10854. " float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10855. " float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10856. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10857. " #else",
  10858. " float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10859. " #endif",
  10860. " spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10861. // specular
  10862. " vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10863. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10864. " float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10865. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10866. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10867. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  10868. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10869. " }",
  10870. " }",
  10871. "#endif",
  10872. "#if MAX_DIR_LIGHTS > 0",
  10873. " vec3 dirDiffuse = vec3( 0.0 );",
  10874. " vec3 dirSpecular = vec3( 0.0 );" ,
  10875. " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10876. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10877. " vec3 dirVector = normalize( lDirection.xyz );",
  10878. // diffuse
  10879. " float dotProduct = dot( normal, dirVector );",
  10880. " #ifdef WRAP_AROUND",
  10881. " float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10882. " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10883. " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10884. " #else",
  10885. " float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10886. " #endif",
  10887. " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10888. // specular
  10889. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10890. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10891. " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10892. /*
  10893. // fresnel term from skin shader
  10894. " const float F0 = 0.128;",
  10895. " float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10896. " float exponential = pow( base, 5.0 );",
  10897. " float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10898. */
  10899. /*
  10900. // fresnel term from fresnel shader
  10901. " const float mFresnelBias = 0.08;",
  10902. " const float mFresnelScale = 0.3;",
  10903. " const float mFresnelPower = 5.0;",
  10904. " float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10905. */
  10906. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10907. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10908. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10909. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  10910. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10911. " }",
  10912. "#endif",
  10913. "#if MAX_HEMI_LIGHTS > 0",
  10914. " vec3 hemiDiffuse = vec3( 0.0 );",
  10915. " vec3 hemiSpecular = vec3( 0.0 );" ,
  10916. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10917. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10918. " vec3 lVector = normalize( lDirection.xyz );",
  10919. // diffuse
  10920. " float dotProduct = dot( normal, lVector );",
  10921. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10922. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10923. " hemiDiffuse += diffuse * hemiColor;",
  10924. // specular (sky light)
  10925. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10926. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10927. " float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10928. // specular (ground light)
  10929. " vec3 lVectorGround = -lVector;",
  10930. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10931. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10932. " float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10933. " float dotProductGround = dot( normal, lVectorGround );",
  10934. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10935. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10936. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  10937. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  10938. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10939. " }",
  10940. "#endif",
  10941. "vec3 totalDiffuse = vec3( 0.0 );",
  10942. "vec3 totalSpecular = vec3( 0.0 );",
  10943. "#if MAX_DIR_LIGHTS > 0",
  10944. " totalDiffuse += dirDiffuse;",
  10945. " totalSpecular += dirSpecular;",
  10946. "#endif",
  10947. "#if MAX_HEMI_LIGHTS > 0",
  10948. " totalDiffuse += hemiDiffuse;",
  10949. " totalSpecular += hemiSpecular;",
  10950. "#endif",
  10951. "#if MAX_POINT_LIGHTS > 0",
  10952. " totalDiffuse += pointDiffuse;",
  10953. " totalSpecular += pointSpecular;",
  10954. "#endif",
  10955. "#if MAX_SPOT_LIGHTS > 0",
  10956. " totalDiffuse += spotDiffuse;",
  10957. " totalSpecular += spotSpecular;",
  10958. "#endif",
  10959. "#ifdef METAL",
  10960. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10961. "#else",
  10962. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10963. "#endif"
  10964. ].join("\n"),
  10965. // VERTEX COLORS
  10966. color_pars_fragment: [
  10967. "#ifdef USE_COLOR",
  10968. " varying vec3 vColor;",
  10969. "#endif"
  10970. ].join("\n"),
  10971. color_fragment: [
  10972. "#ifdef USE_COLOR",
  10973. " gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10974. "#endif"
  10975. ].join("\n"),
  10976. color_pars_vertex: [
  10977. "#ifdef USE_COLOR",
  10978. " varying vec3 vColor;",
  10979. "#endif"
  10980. ].join("\n"),
  10981. color_vertex: [
  10982. "#ifdef USE_COLOR",
  10983. " #ifdef GAMMA_INPUT",
  10984. " vColor = color * color;",
  10985. " #else",
  10986. " vColor = color;",
  10987. " #endif",
  10988. "#endif"
  10989. ].join("\n"),
  10990. // SKINNING
  10991. skinning_pars_vertex: [
  10992. "#ifdef USE_SKINNING",
  10993. " #ifdef BONE_TEXTURE",
  10994. " uniform sampler2D boneTexture;",
  10995. " uniform int boneTextureWidth;",
  10996. " uniform int boneTextureHeight;",
  10997. " mat4 getBoneMatrix( const in float i ) {",
  10998. " float j = i * 4.0;",
  10999. " float x = mod( j, float( boneTextureWidth ) );",
  11000. " float y = floor( j / float( boneTextureWidth ) );",
  11001. " float dx = 1.0 / float( boneTextureWidth );",
  11002. " float dy = 1.0 / float( boneTextureHeight );",
  11003. " y = dy * ( y + 0.5 );",
  11004. " vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  11005. " vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  11006. " vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  11007. " vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  11008. " mat4 bone = mat4( v1, v2, v3, v4 );",
  11009. " return bone;",
  11010. " }",
  11011. " #else",
  11012. " uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  11013. " mat4 getBoneMatrix( const in float i ) {",
  11014. " mat4 bone = boneGlobalMatrices[ int(i) ];",
  11015. " return bone;",
  11016. " }",
  11017. " #endif",
  11018. "#endif"
  11019. ].join("\n"),
  11020. skinbase_vertex: [
  11021. "#ifdef USE_SKINNING",
  11022. " mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  11023. " mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  11024. " mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  11025. " mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  11026. "#endif"
  11027. ].join("\n"),
  11028. skinning_vertex: [
  11029. "#ifdef USE_SKINNING",
  11030. " #ifdef USE_MORPHTARGETS",
  11031. " vec4 skinVertex = vec4( morphed, 1.0 );",
  11032. " #else",
  11033. " vec4 skinVertex = vec4( position, 1.0 );",
  11034. " #endif",
  11035. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11036. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11037. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11038. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11039. "#endif"
  11040. ].join("\n"),
  11041. // MORPHING
  11042. morphtarget_pars_vertex: [
  11043. "#ifdef USE_MORPHTARGETS",
  11044. " #ifndef USE_MORPHNORMALS",
  11045. " uniform float morphTargetInfluences[ 8 ];",
  11046. " #else",
  11047. " uniform float morphTargetInfluences[ 4 ];",
  11048. " #endif",
  11049. "#endif"
  11050. ].join("\n"),
  11051. morphtarget_vertex: [
  11052. "#ifdef USE_MORPHTARGETS",
  11053. " vec3 morphed = vec3( 0.0 );",
  11054. " morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  11055. " morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  11056. " morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  11057. " morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  11058. " #ifndef USE_MORPHNORMALS",
  11059. " morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  11060. " morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  11061. " morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  11062. " morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  11063. " #endif",
  11064. " morphed += position;",
  11065. "#endif"
  11066. ].join("\n"),
  11067. default_vertex : [
  11068. "vec4 mvPosition;",
  11069. "#ifdef USE_SKINNING",
  11070. " mvPosition = modelViewMatrix * skinned;",
  11071. "#endif",
  11072. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  11073. " mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  11074. "#endif",
  11075. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  11076. " mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11077. "#endif",
  11078. "gl_Position = projectionMatrix * mvPosition;"
  11079. ].join("\n"),
  11080. morphnormal_vertex: [
  11081. "#ifdef USE_MORPHNORMALS",
  11082. " vec3 morphedNormal = vec3( 0.0 );",
  11083. " morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  11084. " morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  11085. " morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  11086. " morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  11087. " morphedNormal += normal;",
  11088. "#endif"
  11089. ].join("\n"),
  11090. skinnormal_vertex: [
  11091. "#ifdef USE_SKINNING",
  11092. " mat4 skinMatrix = skinWeight.x * boneMatX;",
  11093. " skinMatrix += skinWeight.y * boneMatY;",
  11094. " skinMatrix += skinWeight.z * boneMatZ;",
  11095. " skinMatrix += skinWeight.w * boneMatW;",
  11096. " #ifdef USE_MORPHNORMALS",
  11097. " vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  11098. " #else",
  11099. " vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  11100. " #endif",
  11101. "#endif"
  11102. ].join("\n"),
  11103. defaultnormal_vertex: [
  11104. "vec3 objectNormal;",
  11105. "#ifdef USE_SKINNING",
  11106. " objectNormal = skinnedNormal.xyz;",
  11107. "#endif",
  11108. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  11109. " objectNormal = morphedNormal;",
  11110. "#endif",
  11111. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  11112. " objectNormal = normal;",
  11113. "#endif",
  11114. "#ifdef FLIP_SIDED",
  11115. " objectNormal = -objectNormal;",
  11116. "#endif",
  11117. "vec3 transformedNormal = normalMatrix * objectNormal;"
  11118. ].join("\n"),
  11119. // SHADOW MAP
  11120. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  11121. // http://spidergl.org/example.php?id=6
  11122. // http://fabiensanglard.net/shadowmapping
  11123. shadowmap_pars_fragment: [
  11124. "#ifdef USE_SHADOWMAP",
  11125. " uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  11126. " uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  11127. " uniform float shadowDarkness[ MAX_SHADOWS ];",
  11128. " uniform float shadowBias[ MAX_SHADOWS ];",
  11129. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11130. " float unpackDepth( const in vec4 rgba_depth ) {",
  11131. " 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 );",
  11132. " float depth = dot( rgba_depth, bit_shift );",
  11133. " return depth;",
  11134. " }",
  11135. "#endif"
  11136. ].join("\n"),
  11137. shadowmap_fragment: [
  11138. "#ifdef USE_SHADOWMAP",
  11139. " #ifdef SHADOWMAP_DEBUG",
  11140. " vec3 frustumColors[3];",
  11141. " frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  11142. " frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  11143. " frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  11144. " #endif",
  11145. " #ifdef SHADOWMAP_CASCADE",
  11146. " int inFrustumCount = 0;",
  11147. " #endif",
  11148. " float fDepth;",
  11149. " vec3 shadowColor = vec3( 1.0 );",
  11150. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11151. " vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  11152. // "if ( something && something )" breaks ATI OpenGL shader compiler
  11153. // "if ( all( something, something ) )" using this instead
  11154. " bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  11155. " bool inFrustum = all( inFrustumVec );",
  11156. // don't shadow pixels outside of light frustum
  11157. // use just first frustum (for cascades)
  11158. // don't shadow pixels behind far plane of light frustum
  11159. " #ifdef SHADOWMAP_CASCADE",
  11160. " inFrustumCount += int( inFrustum );",
  11161. " bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  11162. " #else",
  11163. " bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  11164. " #endif",
  11165. " bool frustumTest = all( frustumTestVec );",
  11166. " if ( frustumTest ) {",
  11167. " shadowCoord.z += shadowBias[ i ];",
  11168. " #if defined( SHADOWMAP_TYPE_PCF )",
  11169. // Percentage-close filtering
  11170. // (9 pixel kernel)
  11171. // http://fabiensanglard.net/shadowmappingPCF/
  11172. " float shadow = 0.0;",
  11173. /*
  11174. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  11175. // must enroll loop manually
  11176. " for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  11177. " for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  11178. " vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  11179. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  11180. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  11181. " float fDepth = unpackDepth( rgbaDepth );",
  11182. " if ( fDepth < shadowCoord.z )",
  11183. " shadow += 1.0;",
  11184. " }",
  11185. " shadow /= 9.0;",
  11186. */
  11187. " const float shadowDelta = 1.0 / 9.0;",
  11188. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11189. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11190. " float dx0 = -1.25 * xPixelOffset;",
  11191. " float dy0 = -1.25 * yPixelOffset;",
  11192. " float dx1 = 1.25 * xPixelOffset;",
  11193. " float dy1 = 1.25 * yPixelOffset;",
  11194. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11195. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11196. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11197. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11198. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11199. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11200. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11201. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11202. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11203. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11204. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11205. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11206. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11207. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11208. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11209. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11210. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11211. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11212. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11213. " #elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  11214. // Percentage-close filtering
  11215. // (9 pixel kernel)
  11216. // http://fabiensanglard.net/shadowmappingPCF/
  11217. " float shadow = 0.0;",
  11218. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11219. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11220. " float dx0 = -1.0 * xPixelOffset;",
  11221. " float dy0 = -1.0 * yPixelOffset;",
  11222. " float dx1 = 1.0 * xPixelOffset;",
  11223. " float dy1 = 1.0 * yPixelOffset;",
  11224. " mat3 shadowKernel;",
  11225. " mat3 depthKernel;",
  11226. " depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11227. " depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11228. " depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11229. " depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11230. " depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11231. " depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11232. " depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11233. " depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11234. " depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11235. " vec3 shadowZ = vec3( shadowCoord.z );",
  11236. " shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  11237. " shadowKernel[0] *= vec3(0.25);",
  11238. " shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  11239. " shadowKernel[1] *= vec3(0.25);",
  11240. " shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  11241. " shadowKernel[2] *= vec3(0.25);",
  11242. " vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  11243. " shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  11244. " shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  11245. " vec4 shadowValues;",
  11246. " shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  11247. " shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  11248. " shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  11249. " shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  11250. " shadow = dot( shadowValues, vec4( 1.0 ) );",
  11251. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11252. " #else",
  11253. " vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  11254. " float fDepth = unpackDepth( rgbaDepth );",
  11255. " if ( fDepth < shadowCoord.z )",
  11256. // spot with multiple shadows is darker
  11257. " shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  11258. // spot with multiple shadows has the same color as single shadow spot
  11259. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  11260. " #endif",
  11261. " }",
  11262. " #ifdef SHADOWMAP_DEBUG",
  11263. " #ifdef SHADOWMAP_CASCADE",
  11264. " if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  11265. " #else",
  11266. " if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  11267. " #endif",
  11268. " #endif",
  11269. " }",
  11270. " #ifdef GAMMA_OUTPUT",
  11271. " shadowColor *= shadowColor;",
  11272. " #endif",
  11273. " gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  11274. "#endif"
  11275. ].join("\n"),
  11276. shadowmap_pars_vertex: [
  11277. "#ifdef USE_SHADOWMAP",
  11278. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11279. " uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  11280. "#endif"
  11281. ].join("\n"),
  11282. shadowmap_vertex: [
  11283. "#ifdef USE_SHADOWMAP",
  11284. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11285. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11286. " }",
  11287. "#endif"
  11288. ].join("\n"),
  11289. // ALPHATEST
  11290. alphatest_fragment: [
  11291. "#ifdef ALPHATEST",
  11292. " if ( gl_FragColor.a < ALPHATEST ) discard;",
  11293. "#endif"
  11294. ].join("\n"),
  11295. // LINEAR SPACE
  11296. linear_to_gamma_fragment: [
  11297. "#ifdef GAMMA_OUTPUT",
  11298. " gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  11299. "#endif"
  11300. ].join("\n")
  11301. };
  11302. /**
  11303. * Uniform Utilities
  11304. */
  11305. THREE.UniformsUtils = {
  11306. merge: function ( uniforms ) {
  11307. var u, p, tmp, merged = {};
  11308. for ( u = 0; u < uniforms.length; u ++ ) {
  11309. tmp = this.clone( uniforms[ u ] );
  11310. for ( p in tmp ) {
  11311. merged[ p ] = tmp[ p ];
  11312. }
  11313. }
  11314. return merged;
  11315. },
  11316. clone: function ( uniforms_src ) {
  11317. var u, p, parameter, parameter_src, uniforms_dst = {};
  11318. for ( u in uniforms_src ) {
  11319. uniforms_dst[ u ] = {};
  11320. for ( p in uniforms_src[ u ] ) {
  11321. parameter_src = uniforms_src[ u ][ p ];
  11322. if ( parameter_src instanceof THREE.Color ||
  11323. parameter_src instanceof THREE.Vector2 ||
  11324. parameter_src instanceof THREE.Vector3 ||
  11325. parameter_src instanceof THREE.Vector4 ||
  11326. parameter_src instanceof THREE.Matrix4 ||
  11327. parameter_src instanceof THREE.Texture ) {
  11328. uniforms_dst[ u ][ p ] = parameter_src.clone();
  11329. } else if ( parameter_src instanceof Array ) {
  11330. uniforms_dst[ u ][ p ] = parameter_src.slice();
  11331. } else {
  11332. uniforms_dst[ u ][ p ] = parameter_src;
  11333. }
  11334. }
  11335. }
  11336. return uniforms_dst;
  11337. }
  11338. };
  11339. /**
  11340. * Uniforms library for shared webgl shaders
  11341. */
  11342. THREE.UniformsLib = {
  11343. common: {
  11344. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11345. "opacity" : { type: "f", value: 1.0 },
  11346. "map" : { type: "t", value: null },
  11347. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  11348. "lightMap" : { type: "t", value: null },
  11349. "specularMap" : { type: "t", value: null },
  11350. "envMap" : { type: "t", value: null },
  11351. "flipEnvMap" : { type: "f", value: -1 },
  11352. "useRefract" : { type: "i", value: 0 },
  11353. "reflectivity" : { type: "f", value: 1.0 },
  11354. "refractionRatio" : { type: "f", value: 0.98 },
  11355. "combine" : { type: "i", value: 0 },
  11356. "morphTargetInfluences" : { type: "f", value: 0 }
  11357. },
  11358. bump: {
  11359. "bumpMap" : { type: "t", value: null },
  11360. "bumpScale" : { type: "f", value: 1 }
  11361. },
  11362. normalmap: {
  11363. "normalMap" : { type: "t", value: null },
  11364. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  11365. },
  11366. fog : {
  11367. "fogDensity" : { type: "f", value: 0.00025 },
  11368. "fogNear" : { type: "f", value: 1 },
  11369. "fogFar" : { type: "f", value: 2000 },
  11370. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11371. },
  11372. lights: {
  11373. "ambientLightColor" : { type: "fv", value: [] },
  11374. "directionalLightDirection" : { type: "fv", value: [] },
  11375. "directionalLightColor" : { type: "fv", value: [] },
  11376. "hemisphereLightDirection" : { type: "fv", value: [] },
  11377. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  11378. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  11379. "pointLightColor" : { type: "fv", value: [] },
  11380. "pointLightPosition" : { type: "fv", value: [] },
  11381. "pointLightDistance" : { type: "fv1", value: [] },
  11382. "spotLightColor" : { type: "fv", value: [] },
  11383. "spotLightPosition" : { type: "fv", value: [] },
  11384. "spotLightDirection" : { type: "fv", value: [] },
  11385. "spotLightDistance" : { type: "fv1", value: [] },
  11386. "spotLightAngleCos" : { type: "fv1", value: [] },
  11387. "spotLightExponent" : { type: "fv1", value: [] }
  11388. },
  11389. particle: {
  11390. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11391. "opacity" : { type: "f", value: 1.0 },
  11392. "size" : { type: "f", value: 1.0 },
  11393. "scale" : { type: "f", value: 1.0 },
  11394. "map" : { type: "t", value: null },
  11395. "fogDensity" : { type: "f", value: 0.00025 },
  11396. "fogNear" : { type: "f", value: 1 },
  11397. "fogFar" : { type: "f", value: 2000 },
  11398. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11399. },
  11400. shadowmap: {
  11401. "shadowMap": { type: "tv", value: [] },
  11402. "shadowMapSize": { type: "v2v", value: [] },
  11403. "shadowBias" : { type: "fv1", value: [] },
  11404. "shadowDarkness": { type: "fv1", value: [] },
  11405. "shadowMatrix" : { type: "m4v", value: [] }
  11406. }
  11407. };
  11408. /**
  11409. * Webgl Shader Library for three.js
  11410. *
  11411. * @author alteredq / http://alteredqualia.com/
  11412. * @author mrdoob / http://mrdoob.com/
  11413. * @author mikael emtinger / http://gomo.se/
  11414. */
  11415. THREE.ShaderLib = {
  11416. 'basic': {
  11417. uniforms: THREE.UniformsUtils.merge( [
  11418. THREE.UniformsLib[ "common" ],
  11419. THREE.UniformsLib[ "fog" ],
  11420. THREE.UniformsLib[ "shadowmap" ]
  11421. ] ),
  11422. vertexShader: [
  11423. THREE.ShaderChunk[ "map_pars_vertex" ],
  11424. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11425. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11426. THREE.ShaderChunk[ "color_pars_vertex" ],
  11427. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11428. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11429. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11430. "void main() {",
  11431. THREE.ShaderChunk[ "map_vertex" ],
  11432. THREE.ShaderChunk[ "lightmap_vertex" ],
  11433. THREE.ShaderChunk[ "color_vertex" ],
  11434. THREE.ShaderChunk[ "skinbase_vertex" ],
  11435. " #ifdef USE_ENVMAP",
  11436. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11437. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11438. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11439. " #endif",
  11440. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11441. THREE.ShaderChunk[ "skinning_vertex" ],
  11442. THREE.ShaderChunk[ "default_vertex" ],
  11443. THREE.ShaderChunk[ "worldpos_vertex" ],
  11444. THREE.ShaderChunk[ "envmap_vertex" ],
  11445. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11446. "}"
  11447. ].join("\n"),
  11448. fragmentShader: [
  11449. "uniform vec3 diffuse;",
  11450. "uniform float opacity;",
  11451. THREE.ShaderChunk[ "color_pars_fragment" ],
  11452. THREE.ShaderChunk[ "map_pars_fragment" ],
  11453. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11454. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11455. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11456. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11457. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11458. "void main() {",
  11459. " gl_FragColor = vec4( diffuse, opacity );",
  11460. THREE.ShaderChunk[ "map_fragment" ],
  11461. THREE.ShaderChunk[ "alphatest_fragment" ],
  11462. THREE.ShaderChunk[ "specularmap_fragment" ],
  11463. THREE.ShaderChunk[ "lightmap_fragment" ],
  11464. THREE.ShaderChunk[ "color_fragment" ],
  11465. THREE.ShaderChunk[ "envmap_fragment" ],
  11466. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11467. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11468. THREE.ShaderChunk[ "fog_fragment" ],
  11469. "}"
  11470. ].join("\n")
  11471. },
  11472. 'lambert': {
  11473. uniforms: THREE.UniformsUtils.merge( [
  11474. THREE.UniformsLib[ "common" ],
  11475. THREE.UniformsLib[ "fog" ],
  11476. THREE.UniformsLib[ "lights" ],
  11477. THREE.UniformsLib[ "shadowmap" ],
  11478. {
  11479. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11480. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11481. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11482. }
  11483. ] ),
  11484. vertexShader: [
  11485. "#define LAMBERT",
  11486. "varying vec3 vLightFront;",
  11487. "#ifdef DOUBLE_SIDED",
  11488. " varying vec3 vLightBack;",
  11489. "#endif",
  11490. THREE.ShaderChunk[ "map_pars_vertex" ],
  11491. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11492. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11493. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11494. THREE.ShaderChunk[ "color_pars_vertex" ],
  11495. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11496. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11497. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11498. "void main() {",
  11499. THREE.ShaderChunk[ "map_vertex" ],
  11500. THREE.ShaderChunk[ "lightmap_vertex" ],
  11501. THREE.ShaderChunk[ "color_vertex" ],
  11502. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11503. THREE.ShaderChunk[ "skinbase_vertex" ],
  11504. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11505. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11506. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11507. THREE.ShaderChunk[ "skinning_vertex" ],
  11508. THREE.ShaderChunk[ "default_vertex" ],
  11509. THREE.ShaderChunk[ "worldpos_vertex" ],
  11510. THREE.ShaderChunk[ "envmap_vertex" ],
  11511. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11512. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11513. "}"
  11514. ].join("\n"),
  11515. fragmentShader: [
  11516. "uniform float opacity;",
  11517. "varying vec3 vLightFront;",
  11518. "#ifdef DOUBLE_SIDED",
  11519. " varying vec3 vLightBack;",
  11520. "#endif",
  11521. THREE.ShaderChunk[ "color_pars_fragment" ],
  11522. THREE.ShaderChunk[ "map_pars_fragment" ],
  11523. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11524. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11525. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11526. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11527. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11528. "void main() {",
  11529. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11530. THREE.ShaderChunk[ "map_fragment" ],
  11531. THREE.ShaderChunk[ "alphatest_fragment" ],
  11532. THREE.ShaderChunk[ "specularmap_fragment" ],
  11533. " #ifdef DOUBLE_SIDED",
  11534. //"float isFront = float( gl_FrontFacing );",
  11535. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11536. " if ( gl_FrontFacing )",
  11537. " gl_FragColor.xyz *= vLightFront;",
  11538. " else",
  11539. " gl_FragColor.xyz *= vLightBack;",
  11540. " #else",
  11541. " gl_FragColor.xyz *= vLightFront;",
  11542. " #endif",
  11543. THREE.ShaderChunk[ "lightmap_fragment" ],
  11544. THREE.ShaderChunk[ "color_fragment" ],
  11545. THREE.ShaderChunk[ "envmap_fragment" ],
  11546. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11547. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11548. THREE.ShaderChunk[ "fog_fragment" ],
  11549. "}"
  11550. ].join("\n")
  11551. },
  11552. 'phong': {
  11553. uniforms: THREE.UniformsUtils.merge( [
  11554. THREE.UniformsLib[ "common" ],
  11555. THREE.UniformsLib[ "bump" ],
  11556. THREE.UniformsLib[ "normalmap" ],
  11557. THREE.UniformsLib[ "fog" ],
  11558. THREE.UniformsLib[ "lights" ],
  11559. THREE.UniformsLib[ "shadowmap" ],
  11560. {
  11561. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11562. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11563. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11564. "shininess": { type: "f", value: 30 },
  11565. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11566. }
  11567. ] ),
  11568. vertexShader: [
  11569. "#define PHONG",
  11570. "varying vec3 vViewPosition;",
  11571. "varying vec3 vNormal;",
  11572. THREE.ShaderChunk[ "map_pars_vertex" ],
  11573. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11574. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11575. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11576. THREE.ShaderChunk[ "color_pars_vertex" ],
  11577. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11578. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11579. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11580. "void main() {",
  11581. THREE.ShaderChunk[ "map_vertex" ],
  11582. THREE.ShaderChunk[ "lightmap_vertex" ],
  11583. THREE.ShaderChunk[ "color_vertex" ],
  11584. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11585. THREE.ShaderChunk[ "skinbase_vertex" ],
  11586. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11587. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11588. " vNormal = normalize( transformedNormal );",
  11589. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11590. THREE.ShaderChunk[ "skinning_vertex" ],
  11591. THREE.ShaderChunk[ "default_vertex" ],
  11592. " vViewPosition = -mvPosition.xyz;",
  11593. THREE.ShaderChunk[ "worldpos_vertex" ],
  11594. THREE.ShaderChunk[ "envmap_vertex" ],
  11595. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11596. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11597. "}"
  11598. ].join("\n"),
  11599. fragmentShader: [
  11600. "uniform vec3 diffuse;",
  11601. "uniform float opacity;",
  11602. "uniform vec3 ambient;",
  11603. "uniform vec3 emissive;",
  11604. "uniform vec3 specular;",
  11605. "uniform float shininess;",
  11606. THREE.ShaderChunk[ "color_pars_fragment" ],
  11607. THREE.ShaderChunk[ "map_pars_fragment" ],
  11608. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11609. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11610. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11611. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11612. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11613. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11614. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11615. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11616. "void main() {",
  11617. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11618. THREE.ShaderChunk[ "map_fragment" ],
  11619. THREE.ShaderChunk[ "alphatest_fragment" ],
  11620. THREE.ShaderChunk[ "specularmap_fragment" ],
  11621. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11622. THREE.ShaderChunk[ "lightmap_fragment" ],
  11623. THREE.ShaderChunk[ "color_fragment" ],
  11624. THREE.ShaderChunk[ "envmap_fragment" ],
  11625. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11626. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11627. THREE.ShaderChunk[ "fog_fragment" ],
  11628. "}"
  11629. ].join("\n")
  11630. },
  11631. 'particle_basic': {
  11632. uniforms: THREE.UniformsUtils.merge( [
  11633. THREE.UniformsLib[ "particle" ],
  11634. THREE.UniformsLib[ "shadowmap" ]
  11635. ] ),
  11636. vertexShader: [
  11637. "uniform float size;",
  11638. "uniform float scale;",
  11639. THREE.ShaderChunk[ "color_pars_vertex" ],
  11640. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11641. "void main() {",
  11642. THREE.ShaderChunk[ "color_vertex" ],
  11643. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11644. " #ifdef USE_SIZEATTENUATION",
  11645. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11646. " #else",
  11647. " gl_PointSize = size;",
  11648. " #endif",
  11649. " gl_Position = projectionMatrix * mvPosition;",
  11650. THREE.ShaderChunk[ "worldpos_vertex" ],
  11651. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11652. "}"
  11653. ].join("\n"),
  11654. fragmentShader: [
  11655. "uniform vec3 psColor;",
  11656. "uniform float opacity;",
  11657. THREE.ShaderChunk[ "color_pars_fragment" ],
  11658. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11659. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11660. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11661. "void main() {",
  11662. " gl_FragColor = vec4( psColor, opacity );",
  11663. THREE.ShaderChunk[ "map_particle_fragment" ],
  11664. THREE.ShaderChunk[ "alphatest_fragment" ],
  11665. THREE.ShaderChunk[ "color_fragment" ],
  11666. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11667. THREE.ShaderChunk[ "fog_fragment" ],
  11668. "}"
  11669. ].join("\n")
  11670. },
  11671. 'dashed': {
  11672. uniforms: THREE.UniformsUtils.merge( [
  11673. THREE.UniformsLib[ "common" ],
  11674. THREE.UniformsLib[ "fog" ],
  11675. {
  11676. "scale": { type: "f", value: 1 },
  11677. "dashSize": { type: "f", value: 1 },
  11678. "totalSize": { type: "f", value: 2 }
  11679. }
  11680. ] ),
  11681. vertexShader: [
  11682. "uniform float scale;",
  11683. "attribute float lineDistance;",
  11684. "varying float vLineDistance;",
  11685. THREE.ShaderChunk[ "color_pars_vertex" ],
  11686. "void main() {",
  11687. THREE.ShaderChunk[ "color_vertex" ],
  11688. " vLineDistance = scale * lineDistance;",
  11689. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11690. " gl_Position = projectionMatrix * mvPosition;",
  11691. "}"
  11692. ].join("\n"),
  11693. fragmentShader: [
  11694. "uniform vec3 diffuse;",
  11695. "uniform float opacity;",
  11696. "uniform float dashSize;",
  11697. "uniform float totalSize;",
  11698. "varying float vLineDistance;",
  11699. THREE.ShaderChunk[ "color_pars_fragment" ],
  11700. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11701. "void main() {",
  11702. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11703. " discard;",
  11704. " }",
  11705. " gl_FragColor = vec4( diffuse, opacity );",
  11706. THREE.ShaderChunk[ "color_fragment" ],
  11707. THREE.ShaderChunk[ "fog_fragment" ],
  11708. "}"
  11709. ].join("\n")
  11710. },
  11711. 'depth': {
  11712. uniforms: {
  11713. "mNear": { type: "f", value: 1.0 },
  11714. "mFar" : { type: "f", value: 2000.0 },
  11715. "opacity" : { type: "f", value: 1.0 }
  11716. },
  11717. vertexShader: [
  11718. "void main() {",
  11719. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11720. "}"
  11721. ].join("\n"),
  11722. fragmentShader: [
  11723. "uniform float mNear;",
  11724. "uniform float mFar;",
  11725. "uniform float opacity;",
  11726. "void main() {",
  11727. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11728. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11729. " gl_FragColor = vec4( vec3( color ), opacity );",
  11730. "}"
  11731. ].join("\n")
  11732. },
  11733. 'normal': {
  11734. uniforms: {
  11735. "opacity" : { type: "f", value: 1.0 }
  11736. },
  11737. vertexShader: [
  11738. "varying vec3 vNormal;",
  11739. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11740. "void main() {",
  11741. " vNormal = normalize( normalMatrix * normal );",
  11742. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11743. THREE.ShaderChunk[ "default_vertex" ],
  11744. "}"
  11745. ].join("\n"),
  11746. fragmentShader: [
  11747. "uniform float opacity;",
  11748. "varying vec3 vNormal;",
  11749. "void main() {",
  11750. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11751. "}"
  11752. ].join("\n")
  11753. },
  11754. /* -------------------------------------------------------------------------
  11755. // Normal map shader
  11756. // - Blinn-Phong
  11757. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11758. // - point and directional lights (use with "lights: true" material option)
  11759. ------------------------------------------------------------------------- */
  11760. 'normalmap' : {
  11761. uniforms: THREE.UniformsUtils.merge( [
  11762. THREE.UniformsLib[ "fog" ],
  11763. THREE.UniformsLib[ "lights" ],
  11764. THREE.UniformsLib[ "shadowmap" ],
  11765. {
  11766. "enableAO" : { type: "i", value: 0 },
  11767. "enableDiffuse" : { type: "i", value: 0 },
  11768. "enableSpecular" : { type: "i", value: 0 },
  11769. "enableReflection": { type: "i", value: 0 },
  11770. "enableDisplacement": { type: "i", value: 0 },
  11771. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11772. "tDiffuse" : { type: "t", value: null },
  11773. "tCube" : { type: "t", value: null },
  11774. "tNormal" : { type: "t", value: null },
  11775. "tSpecular" : { type: "t", value: null },
  11776. "tAO" : { type: "t", value: null },
  11777. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11778. "uDisplacementBias": { type: "f", value: 0.0 },
  11779. "uDisplacementScale": { type: "f", value: 1.0 },
  11780. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11781. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11782. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11783. "shininess": { type: "f", value: 30 },
  11784. "opacity": { type: "f", value: 1 },
  11785. "useRefract": { type: "i", value: 0 },
  11786. "refractionRatio": { type: "f", value: 0.98 },
  11787. "reflectivity": { type: "f", value: 0.5 },
  11788. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11789. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11790. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11791. }
  11792. ] ),
  11793. fragmentShader: [
  11794. "uniform vec3 ambient;",
  11795. "uniform vec3 diffuse;",
  11796. "uniform vec3 specular;",
  11797. "uniform float shininess;",
  11798. "uniform float opacity;",
  11799. "uniform bool enableDiffuse;",
  11800. "uniform bool enableSpecular;",
  11801. "uniform bool enableAO;",
  11802. "uniform bool enableReflection;",
  11803. "uniform sampler2D tDiffuse;",
  11804. "uniform sampler2D tNormal;",
  11805. "uniform sampler2D tSpecular;",
  11806. "uniform sampler2D tAO;",
  11807. "uniform samplerCube tCube;",
  11808. "uniform vec2 uNormalScale;",
  11809. "uniform bool useRefract;",
  11810. "uniform float refractionRatio;",
  11811. "uniform float reflectivity;",
  11812. "varying vec3 vTangent;",
  11813. "varying vec3 vBinormal;",
  11814. "varying vec3 vNormal;",
  11815. "varying vec2 vUv;",
  11816. "uniform vec3 ambientLightColor;",
  11817. "#if MAX_DIR_LIGHTS > 0",
  11818. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11819. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11820. "#endif",
  11821. "#if MAX_HEMI_LIGHTS > 0",
  11822. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11823. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11824. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11825. "#endif",
  11826. "#if MAX_POINT_LIGHTS > 0",
  11827. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11828. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11829. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11830. "#endif",
  11831. "#if MAX_SPOT_LIGHTS > 0",
  11832. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11833. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11834. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11835. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11836. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11837. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11838. "#endif",
  11839. "#ifdef WRAP_AROUND",
  11840. " uniform vec3 wrapRGB;",
  11841. "#endif",
  11842. "varying vec3 vWorldPosition;",
  11843. "varying vec3 vViewPosition;",
  11844. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11845. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11846. "void main() {",
  11847. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11848. " vec3 specularTex = vec3( 1.0 );",
  11849. " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11850. " normalTex.xy *= uNormalScale;",
  11851. " normalTex = normalize( normalTex );",
  11852. " if( enableDiffuse ) {",
  11853. " #ifdef GAMMA_INPUT",
  11854. " vec4 texelColor = texture2D( tDiffuse, vUv );",
  11855. " texelColor.xyz *= texelColor.xyz;",
  11856. " gl_FragColor = gl_FragColor * texelColor;",
  11857. " #else",
  11858. " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11859. " #endif",
  11860. " }",
  11861. " if( enableAO ) {",
  11862. " #ifdef GAMMA_INPUT",
  11863. " vec4 aoColor = texture2D( tAO, vUv );",
  11864. " aoColor.xyz *= aoColor.xyz;",
  11865. " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11866. " #else",
  11867. " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11868. " #endif",
  11869. " }",
  11870. " if( enableSpecular )",
  11871. " specularTex = texture2D( tSpecular, vUv ).xyz;",
  11872. " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11873. " vec3 finalNormal = tsb * normalTex;",
  11874. " #ifdef FLIP_SIDED",
  11875. " finalNormal = -finalNormal;",
  11876. " #endif",
  11877. " vec3 normal = normalize( finalNormal );",
  11878. " vec3 viewPosition = normalize( vViewPosition );",
  11879. // point lights
  11880. " #if MAX_POINT_LIGHTS > 0",
  11881. " vec3 pointDiffuse = vec3( 0.0 );",
  11882. " vec3 pointSpecular = vec3( 0.0 );",
  11883. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11884. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11885. " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11886. " float pointDistance = 1.0;",
  11887. " if ( pointLightDistance[ i ] > 0.0 )",
  11888. " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11889. " pointVector = normalize( pointVector );",
  11890. // diffuse
  11891. " #ifdef WRAP_AROUND",
  11892. " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11893. " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11894. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11895. " #else",
  11896. " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11897. " #endif",
  11898. " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11899. // specular
  11900. " vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11901. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11902. " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11903. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11904. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11905. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11906. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11907. " }",
  11908. " #endif",
  11909. // spot lights
  11910. " #if MAX_SPOT_LIGHTS > 0",
  11911. " vec3 spotDiffuse = vec3( 0.0 );",
  11912. " vec3 spotSpecular = vec3( 0.0 );",
  11913. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11914. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11915. " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11916. " float spotDistance = 1.0;",
  11917. " if ( spotLightDistance[ i ] > 0.0 )",
  11918. " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11919. " spotVector = normalize( spotVector );",
  11920. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11921. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11922. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11923. // diffuse
  11924. " #ifdef WRAP_AROUND",
  11925. " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11926. " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11927. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11928. " #else",
  11929. " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11930. " #endif",
  11931. " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11932. // specular
  11933. " vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11934. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11935. " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11936. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11937. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11938. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11939. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11940. " }",
  11941. " }",
  11942. " #endif",
  11943. // directional lights
  11944. " #if MAX_DIR_LIGHTS > 0",
  11945. " vec3 dirDiffuse = vec3( 0.0 );",
  11946. " vec3 dirSpecular = vec3( 0.0 );",
  11947. " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11948. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11949. " vec3 dirVector = normalize( lDirection.xyz );",
  11950. // diffuse
  11951. " #ifdef WRAP_AROUND",
  11952. " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11953. " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11954. " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11955. " #else",
  11956. " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11957. " #endif",
  11958. " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11959. // specular
  11960. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11961. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11962. " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11963. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11964. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11965. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11966. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11967. " }",
  11968. " #endif",
  11969. // hemisphere lights
  11970. " #if MAX_HEMI_LIGHTS > 0",
  11971. " vec3 hemiDiffuse = vec3( 0.0 );",
  11972. " vec3 hemiSpecular = vec3( 0.0 );" ,
  11973. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11974. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11975. " vec3 lVector = normalize( lDirection.xyz );",
  11976. // diffuse
  11977. " float dotProduct = dot( normal, lVector );",
  11978. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11979. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11980. " hemiDiffuse += diffuse * hemiColor;",
  11981. // specular (sky light)
  11982. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11983. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11984. " float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11985. // specular (ground light)
  11986. " vec3 lVectorGround = -lVector;",
  11987. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11988. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11989. " float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11990. " float dotProductGround = dot( normal, lVectorGround );",
  11991. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11992. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11993. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11994. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11995. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11996. " }",
  11997. " #endif",
  11998. // all lights contribution summation
  11999. " vec3 totalDiffuse = vec3( 0.0 );",
  12000. " vec3 totalSpecular = vec3( 0.0 );",
  12001. " #if MAX_DIR_LIGHTS > 0",
  12002. " totalDiffuse += dirDiffuse;",
  12003. " totalSpecular += dirSpecular;",
  12004. " #endif",
  12005. " #if MAX_HEMI_LIGHTS > 0",
  12006. " totalDiffuse += hemiDiffuse;",
  12007. " totalSpecular += hemiSpecular;",
  12008. " #endif",
  12009. " #if MAX_POINT_LIGHTS > 0",
  12010. " totalDiffuse += pointDiffuse;",
  12011. " totalSpecular += pointSpecular;",
  12012. " #endif",
  12013. " #if MAX_SPOT_LIGHTS > 0",
  12014. " totalDiffuse += spotDiffuse;",
  12015. " totalSpecular += spotSpecular;",
  12016. " #endif",
  12017. " #ifdef METAL",
  12018. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  12019. " #else",
  12020. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  12021. " #endif",
  12022. " if ( enableReflection ) {",
  12023. " vec3 vReflect;",
  12024. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  12025. " if ( useRefract ) {",
  12026. " vReflect = refract( cameraToVertex, normal, refractionRatio );",
  12027. " } else {",
  12028. " vReflect = reflect( cameraToVertex, normal );",
  12029. " }",
  12030. " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  12031. " #ifdef GAMMA_INPUT",
  12032. " cubeColor.xyz *= cubeColor.xyz;",
  12033. " #endif",
  12034. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  12035. " }",
  12036. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12037. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  12038. THREE.ShaderChunk[ "fog_fragment" ],
  12039. "}"
  12040. ].join("\n"),
  12041. vertexShader: [
  12042. "attribute vec4 tangent;",
  12043. "uniform vec2 uOffset;",
  12044. "uniform vec2 uRepeat;",
  12045. "uniform bool enableDisplacement;",
  12046. "#ifdef VERTEX_TEXTURES",
  12047. " uniform sampler2D tDisplacement;",
  12048. " uniform float uDisplacementScale;",
  12049. " uniform float uDisplacementBias;",
  12050. "#endif",
  12051. "varying vec3 vTangent;",
  12052. "varying vec3 vBinormal;",
  12053. "varying vec3 vNormal;",
  12054. "varying vec2 vUv;",
  12055. "varying vec3 vWorldPosition;",
  12056. "varying vec3 vViewPosition;",
  12057. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12058. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12059. "void main() {",
  12060. THREE.ShaderChunk[ "skinbase_vertex" ],
  12061. THREE.ShaderChunk[ "skinnormal_vertex" ],
  12062. // normal, tangent and binormal vectors
  12063. " #ifdef USE_SKINNING",
  12064. " vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  12065. " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  12066. " vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  12067. " #else",
  12068. " vNormal = normalize( normalMatrix * normal );",
  12069. " vTangent = normalize( normalMatrix * tangent.xyz );",
  12070. " #endif",
  12071. " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  12072. " vUv = uv * uRepeat + uOffset;",
  12073. // displacement mapping
  12074. " vec3 displacedPosition;",
  12075. " #ifdef VERTEX_TEXTURES",
  12076. " if ( enableDisplacement ) {",
  12077. " vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  12078. " float df = uDisplacementScale * dv.x + uDisplacementBias;",
  12079. " displacedPosition = position + normalize( normal ) * df;",
  12080. " } else {",
  12081. " #ifdef USE_SKINNING",
  12082. " vec4 skinVertex = vec4( position, 1.0 );",
  12083. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  12084. " skinned += boneMatY * skinVertex * skinWeight.y;",
  12085. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  12086. " skinned += boneMatW * skinVertex * skinWeight.w;",
  12087. " displacedPosition = skinned.xyz;",
  12088. " #else",
  12089. " displacedPosition = position;",
  12090. " #endif",
  12091. " }",
  12092. " #else",
  12093. " #ifdef USE_SKINNING",
  12094. " vec4 skinVertex = vec4( position, 1.0 );",
  12095. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  12096. " skinned += boneMatY * skinVertex * skinWeight.y;",
  12097. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  12098. " skinned += boneMatW * skinVertex * skinWeight.w;",
  12099. " displacedPosition = skinned.xyz;",
  12100. " #else",
  12101. " displacedPosition = position;",
  12102. " #endif",
  12103. " #endif",
  12104. //
  12105. " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  12106. " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  12107. " gl_Position = projectionMatrix * mvPosition;",
  12108. //
  12109. " vWorldPosition = worldPosition.xyz;",
  12110. " vViewPosition = -mvPosition.xyz;",
  12111. // shadows
  12112. " #ifdef USE_SHADOWMAP",
  12113. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  12114. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  12115. " }",
  12116. " #endif",
  12117. "}"
  12118. ].join("\n")
  12119. },
  12120. /* -------------------------------------------------------------------------
  12121. // Cube map shader
  12122. ------------------------------------------------------------------------- */
  12123. 'cube': {
  12124. uniforms: { "tCube": { type: "t", value: null },
  12125. "tFlip": { type: "f", value: -1 } },
  12126. vertexShader: [
  12127. "varying vec3 vWorldPosition;",
  12128. "void main() {",
  12129. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  12130. " vWorldPosition = worldPosition.xyz;",
  12131. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  12132. "}"
  12133. ].join("\n"),
  12134. fragmentShader: [
  12135. "uniform samplerCube tCube;",
  12136. "uniform float tFlip;",
  12137. "varying vec3 vWorldPosition;",
  12138. "void main() {",
  12139. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  12140. "}"
  12141. ].join("\n")
  12142. },
  12143. // Depth encoding into RGBA texture
  12144. // based on SpiderGL shadow map example
  12145. // http://spidergl.org/example.php?id=6
  12146. // originally from
  12147. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  12148. // see also here:
  12149. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  12150. 'depthRGBA': {
  12151. uniforms: {},
  12152. vertexShader: [
  12153. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12154. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12155. "void main() {",
  12156. THREE.ShaderChunk[ "skinbase_vertex" ],
  12157. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12158. THREE.ShaderChunk[ "skinning_vertex" ],
  12159. THREE.ShaderChunk[ "default_vertex" ],
  12160. "}"
  12161. ].join("\n"),
  12162. fragmentShader: [
  12163. "vec4 pack_depth( const in float depth ) {",
  12164. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  12165. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  12166. " vec4 res = fract( depth * bit_shift );",
  12167. " res -= res.xxyz * bit_mask;",
  12168. " return res;",
  12169. "}",
  12170. "void main() {",
  12171. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  12172. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  12173. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  12174. //"gl_FragData[ 0 ] = pack_depth( z );",
  12175. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  12176. "}"
  12177. ].join("\n")
  12178. }
  12179. };
  12180. /**
  12181. * @author supereggbert / http://www.paulbrunt.co.uk/
  12182. * @author mrdoob / http://mrdoob.com/
  12183. * @author alteredq / http://alteredqualia.com/
  12184. * @author szimek / https://github.com/szimek/
  12185. */
  12186. THREE.WebGLRenderer = function ( parameters ) {
  12187. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  12188. parameters = parameters || {};
  12189. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  12190. _context = parameters.context !== undefined ? parameters.context : null,
  12191. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  12192. _buffers = {},
  12193. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12194. _depth = parameters.depth !== undefined ? parameters.depth : true,
  12195. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12196. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12197. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12198. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12199. _clearColor = new THREE.Color( 0x000000 ),
  12200. _clearAlpha = 0;
  12201. // public properties
  12202. this.domElement = _canvas;
  12203. this.context = null;
  12204. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  12205. ? parameters.devicePixelRatio
  12206. : self.devicePixelRatio !== undefined
  12207. ? self.devicePixelRatio
  12208. : 1;
  12209. // clearing
  12210. this.autoClear = true;
  12211. this.autoClearColor = true;
  12212. this.autoClearDepth = true;
  12213. this.autoClearStencil = true;
  12214. // scene graph
  12215. this.sortObjects = true;
  12216. this.autoUpdateObjects = true;
  12217. // physically based shading
  12218. this.gammaInput = false;
  12219. this.gammaOutput = false;
  12220. // shadow map
  12221. this.shadowMapEnabled = false;
  12222. this.shadowMapAutoUpdate = true;
  12223. this.shadowMapType = THREE.PCFShadowMap;
  12224. this.shadowMapCullFace = THREE.CullFaceFront;
  12225. this.shadowMapDebug = false;
  12226. this.shadowMapCascade = false;
  12227. // morphs
  12228. this.maxMorphTargets = 8;
  12229. this.maxMorphNormals = 4;
  12230. // flags
  12231. this.autoScaleCubemaps = true;
  12232. // custom render plugins
  12233. this.renderPluginsPre = [];
  12234. this.renderPluginsPost = [];
  12235. // info
  12236. this.info = {
  12237. memory: {
  12238. programs: 0,
  12239. geometries: 0,
  12240. textures: 0
  12241. },
  12242. render: {
  12243. calls: 0,
  12244. vertices: 0,
  12245. faces: 0,
  12246. points: 0
  12247. }
  12248. };
  12249. // internal properties
  12250. var _this = this,
  12251. _programs = [],
  12252. // internal state cache
  12253. _currentProgram = null,
  12254. _currentFramebuffer = null,
  12255. _currentMaterialId = -1,
  12256. _currentGeometryGroupHash = null,
  12257. _currentCamera = null,
  12258. _usedTextureUnits = 0,
  12259. // GL state cache
  12260. _oldDoubleSided = -1,
  12261. _oldFlipSided = -1,
  12262. _oldBlending = -1,
  12263. _oldBlendEquation = -1,
  12264. _oldBlendSrc = -1,
  12265. _oldBlendDst = -1,
  12266. _oldDepthTest = -1,
  12267. _oldDepthWrite = -1,
  12268. _oldPolygonOffset = null,
  12269. _oldPolygonOffsetFactor = null,
  12270. _oldPolygonOffsetUnits = null,
  12271. _oldLineWidth = null,
  12272. _viewportX = 0,
  12273. _viewportY = 0,
  12274. _viewportWidth = _canvas.width,
  12275. _viewportHeight = _canvas.height,
  12276. _currentWidth = 0,
  12277. _currentHeight = 0,
  12278. _newAttributes = new Uint8Array( 16 ),
  12279. _enabledAttributes = new Uint8Array( 16 ),
  12280. // frustum
  12281. _frustum = new THREE.Frustum(),
  12282. // camera matrices cache
  12283. _projScreenMatrix = new THREE.Matrix4(),
  12284. _projScreenMatrixPS = new THREE.Matrix4(),
  12285. _vector3 = new THREE.Vector3(),
  12286. // light arrays cache
  12287. _direction = new THREE.Vector3(),
  12288. _lightsNeedUpdate = true,
  12289. _lights = {
  12290. ambient: [ 0, 0, 0 ],
  12291. directional: { length: 0, colors: new Array(), positions: new Array() },
  12292. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  12293. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  12294. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  12295. };
  12296. // initialize
  12297. var _gl;
  12298. var _glExtensionTextureFloat;
  12299. var _glExtensionTextureFloatLinear;
  12300. var _glExtensionStandardDerivatives;
  12301. var _glExtensionTextureFilterAnisotropic;
  12302. var _glExtensionCompressedTextureS3TC;
  12303. var _glExtensionElementIndexUint;
  12304. initGL();
  12305. setDefaultGLState();
  12306. this.context = _gl;
  12307. // GPU capabilities
  12308. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12309. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12310. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12311. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12312. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12313. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12314. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12315. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12316. //
  12317. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12318. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12319. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12320. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12321. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12322. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12323. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  12324. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  12325. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  12326. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  12327. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  12328. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  12329. // clamp precision to maximum available
  12330. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12331. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12332. if ( _precision === "highp" && ! highpAvailable ) {
  12333. if ( mediumpAvailable ) {
  12334. _precision = "mediump";
  12335. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  12336. } else {
  12337. _precision = "lowp";
  12338. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  12339. }
  12340. }
  12341. if ( _precision === "mediump" && ! mediumpAvailable ) {
  12342. _precision = "lowp";
  12343. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  12344. }
  12345. // API
  12346. this.getContext = function () {
  12347. return _gl;
  12348. };
  12349. this.supportsVertexTextures = function () {
  12350. return _supportsVertexTextures;
  12351. };
  12352. this.supportsFloatTextures = function () {
  12353. return _glExtensionTextureFloat;
  12354. };
  12355. this.supportsStandardDerivatives = function () {
  12356. return _glExtensionStandardDerivatives;
  12357. };
  12358. this.supportsCompressedTextureS3TC = function () {
  12359. return _glExtensionCompressedTextureS3TC;
  12360. };
  12361. this.getMaxAnisotropy = function () {
  12362. return _maxAnisotropy;
  12363. };
  12364. this.getPrecision = function () {
  12365. return _precision;
  12366. };
  12367. this.setSize = function ( width, height, updateStyle ) {
  12368. _canvas.width = width * this.devicePixelRatio;
  12369. _canvas.height = height * this.devicePixelRatio;
  12370. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  12371. _canvas.style.width = width + 'px';
  12372. _canvas.style.height = height + 'px';
  12373. }
  12374. this.setViewport( 0, 0, width, height );
  12375. };
  12376. this.setViewport = function ( x, y, width, height ) {
  12377. _viewportX = x * this.devicePixelRatio;
  12378. _viewportY = y * this.devicePixelRatio;
  12379. _viewportWidth = width * this.devicePixelRatio;
  12380. _viewportHeight = height * this.devicePixelRatio;
  12381. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12382. };
  12383. this.setScissor = function ( x, y, width, height ) {
  12384. _gl.scissor(
  12385. x * this.devicePixelRatio,
  12386. y * this.devicePixelRatio,
  12387. width * this.devicePixelRatio,
  12388. height * this.devicePixelRatio
  12389. );
  12390. };
  12391. this.enableScissorTest = function ( enable ) {
  12392. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12393. };
  12394. // Clearing
  12395. this.setClearColor = function ( color, alpha ) {
  12396. _clearColor.set( color );
  12397. _clearAlpha = alpha !== undefined ? alpha : 1;
  12398. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12399. };
  12400. this.setClearColorHex = function ( hex, alpha ) {
  12401. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  12402. this.setClearColor( hex, alpha );
  12403. };
  12404. this.getClearColor = function () {
  12405. return _clearColor;
  12406. };
  12407. this.getClearAlpha = function () {
  12408. return _clearAlpha;
  12409. };
  12410. this.clear = function ( color, depth, stencil ) {
  12411. var bits = 0;
  12412. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12413. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12414. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12415. _gl.clear( bits );
  12416. };
  12417. this.clearColor = function () {
  12418. _gl.clear( _gl.COLOR_BUFFER_BIT );
  12419. };
  12420. this.clearDepth = function () {
  12421. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  12422. };
  12423. this.clearStencil = function () {
  12424. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  12425. };
  12426. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12427. this.setRenderTarget( renderTarget );
  12428. this.clear( color, depth, stencil );
  12429. };
  12430. // Plugins
  12431. this.addPostPlugin = function ( plugin ) {
  12432. plugin.init( this );
  12433. this.renderPluginsPost.push( plugin );
  12434. };
  12435. this.addPrePlugin = function ( plugin ) {
  12436. plugin.init( this );
  12437. this.renderPluginsPre.push( plugin );
  12438. };
  12439. // Rendering
  12440. this.updateShadowMap = function ( scene, camera ) {
  12441. _currentProgram = null;
  12442. _oldBlending = -1;
  12443. _oldDepthTest = -1;
  12444. _oldDepthWrite = -1;
  12445. _currentGeometryGroupHash = -1;
  12446. _currentMaterialId = -1;
  12447. _lightsNeedUpdate = true;
  12448. _oldDoubleSided = -1;
  12449. _oldFlipSided = -1;
  12450. this.shadowMapPlugin.update( scene, camera );
  12451. };
  12452. // Internal functions
  12453. // Buffer allocation
  12454. function createParticleBuffers ( geometry ) {
  12455. geometry.__webglVertexBuffer = _gl.createBuffer();
  12456. geometry.__webglColorBuffer = _gl.createBuffer();
  12457. _this.info.memory.geometries ++;
  12458. };
  12459. function createLineBuffers ( geometry ) {
  12460. geometry.__webglVertexBuffer = _gl.createBuffer();
  12461. geometry.__webglColorBuffer = _gl.createBuffer();
  12462. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12463. _this.info.memory.geometries ++;
  12464. };
  12465. function createMeshBuffers ( geometryGroup ) {
  12466. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12467. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12468. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12469. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12470. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12471. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12472. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12473. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12474. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12475. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12476. var m, ml;
  12477. if ( geometryGroup.numMorphTargets ) {
  12478. geometryGroup.__webglMorphTargetsBuffers = [];
  12479. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12480. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12481. }
  12482. }
  12483. if ( geometryGroup.numMorphNormals ) {
  12484. geometryGroup.__webglMorphNormalsBuffers = [];
  12485. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12486. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12487. }
  12488. }
  12489. _this.info.memory.geometries ++;
  12490. };
  12491. // Events
  12492. var onGeometryDispose = function ( event ) {
  12493. var geometry = event.target;
  12494. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12495. deallocateGeometry( geometry );
  12496. };
  12497. var onTextureDispose = function ( event ) {
  12498. var texture = event.target;
  12499. texture.removeEventListener( 'dispose', onTextureDispose );
  12500. deallocateTexture( texture );
  12501. _this.info.memory.textures --;
  12502. };
  12503. var onRenderTargetDispose = function ( event ) {
  12504. var renderTarget = event.target;
  12505. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12506. deallocateRenderTarget( renderTarget );
  12507. _this.info.memory.textures --;
  12508. };
  12509. var onMaterialDispose = function ( event ) {
  12510. var material = event.target;
  12511. material.removeEventListener( 'dispose', onMaterialDispose );
  12512. deallocateMaterial( material );
  12513. };
  12514. // Buffer deallocation
  12515. var deleteBuffers = function ( geometry ) {
  12516. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12517. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12518. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12519. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12520. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12521. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12522. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12523. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12524. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12525. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12526. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12527. // custom attributes
  12528. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12529. for ( var id in geometry.__webglCustomAttributesList ) {
  12530. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12531. }
  12532. }
  12533. _this.info.memory.geometries --;
  12534. };
  12535. var deallocateGeometry = function ( geometry ) {
  12536. geometry.__webglInit = undefined;
  12537. if ( geometry instanceof THREE.BufferGeometry ) {
  12538. var attributes = geometry.attributes;
  12539. for ( var key in attributes ) {
  12540. if ( attributes[ key ].buffer !== undefined ) {
  12541. _gl.deleteBuffer( attributes[ key ].buffer );
  12542. }
  12543. }
  12544. _this.info.memory.geometries --;
  12545. } else {
  12546. if ( geometry.geometryGroups !== undefined ) {
  12547. for ( var g in geometry.geometryGroups ) {
  12548. var geometryGroup = geometry.geometryGroups[ g ];
  12549. if ( geometryGroup.numMorphTargets !== undefined ) {
  12550. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12551. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12552. }
  12553. }
  12554. if ( geometryGroup.numMorphNormals !== undefined ) {
  12555. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12556. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12557. }
  12558. }
  12559. deleteBuffers( geometryGroup );
  12560. }
  12561. } else {
  12562. deleteBuffers( geometry );
  12563. }
  12564. }
  12565. };
  12566. var deallocateTexture = function ( texture ) {
  12567. if ( texture.image && texture.image.__webglTextureCube ) {
  12568. // cube texture
  12569. _gl.deleteTexture( texture.image.__webglTextureCube );
  12570. } else {
  12571. // 2D texture
  12572. if ( ! texture.__webglInit ) return;
  12573. texture.__webglInit = false;
  12574. _gl.deleteTexture( texture.__webglTexture );
  12575. }
  12576. };
  12577. var deallocateRenderTarget = function ( renderTarget ) {
  12578. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12579. _gl.deleteTexture( renderTarget.__webglTexture );
  12580. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12581. for ( var i = 0; i < 6; i ++ ) {
  12582. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12583. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12584. }
  12585. } else {
  12586. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12587. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12588. }
  12589. };
  12590. var deallocateMaterial = function ( material ) {
  12591. var program = material.program;
  12592. if ( program === undefined ) return;
  12593. material.program = undefined;
  12594. // only deallocate GL program if this was the last use of shared program
  12595. // assumed there is only single copy of any program in the _programs list
  12596. // (that's how it's constructed)
  12597. var i, il, programInfo;
  12598. var deleteProgram = false;
  12599. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12600. programInfo = _programs[ i ];
  12601. if ( programInfo.program === program ) {
  12602. programInfo.usedTimes --;
  12603. if ( programInfo.usedTimes === 0 ) {
  12604. deleteProgram = true;
  12605. }
  12606. break;
  12607. }
  12608. }
  12609. if ( deleteProgram === true ) {
  12610. // avoid using array.splice, this is costlier than creating new array from scratch
  12611. var newPrograms = [];
  12612. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12613. programInfo = _programs[ i ];
  12614. if ( programInfo.program !== program ) {
  12615. newPrograms.push( programInfo );
  12616. }
  12617. }
  12618. _programs = newPrograms;
  12619. _gl.deleteProgram( program );
  12620. _this.info.memory.programs --;
  12621. }
  12622. };
  12623. // Buffer initialization
  12624. function initCustomAttributes ( geometry, object ) {
  12625. var nvertices = geometry.vertices.length;
  12626. var material = object.material;
  12627. if ( material.attributes ) {
  12628. if ( geometry.__webglCustomAttributesList === undefined ) {
  12629. geometry.__webglCustomAttributesList = [];
  12630. }
  12631. for ( var a in material.attributes ) {
  12632. var attribute = material.attributes[ a ];
  12633. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12634. attribute.__webglInitialized = true;
  12635. var size = 1; // "f" and "i"
  12636. if ( attribute.type === "v2" ) size = 2;
  12637. else if ( attribute.type === "v3" ) size = 3;
  12638. else if ( attribute.type === "v4" ) size = 4;
  12639. else if ( attribute.type === "c" ) size = 3;
  12640. attribute.size = size;
  12641. attribute.array = new Float32Array( nvertices * size );
  12642. attribute.buffer = _gl.createBuffer();
  12643. attribute.buffer.belongsToAttribute = a;
  12644. attribute.needsUpdate = true;
  12645. }
  12646. geometry.__webglCustomAttributesList.push( attribute );
  12647. }
  12648. }
  12649. };
  12650. function initParticleBuffers ( geometry, object ) {
  12651. var nvertices = geometry.vertices.length;
  12652. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12653. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12654. geometry.__sortArray = [];
  12655. geometry.__webglParticleCount = nvertices;
  12656. initCustomAttributes ( geometry, object );
  12657. };
  12658. function initLineBuffers ( geometry, object ) {
  12659. var nvertices = geometry.vertices.length;
  12660. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12661. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12662. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12663. geometry.__webglLineCount = nvertices;
  12664. initCustomAttributes ( geometry, object );
  12665. };
  12666. function initMeshBuffers ( geometryGroup, object ) {
  12667. var geometry = object.geometry,
  12668. faces3 = geometryGroup.faces3,
  12669. nvertices = faces3.length * 3,
  12670. ntris = faces3.length * 1,
  12671. nlines = faces3.length * 3,
  12672. material = getBufferMaterial( object, geometryGroup ),
  12673. uvType = bufferGuessUVType( material ),
  12674. normalType = bufferGuessNormalType( material ),
  12675. vertexColorType = bufferGuessVertexColorType( material );
  12676. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12677. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12678. if ( normalType ) {
  12679. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12680. }
  12681. if ( geometry.hasTangents ) {
  12682. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12683. }
  12684. if ( vertexColorType ) {
  12685. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12686. }
  12687. if ( uvType ) {
  12688. if ( geometry.faceVertexUvs.length > 0 ) {
  12689. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12690. }
  12691. if ( geometry.faceVertexUvs.length > 1 ) {
  12692. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12693. }
  12694. }
  12695. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12696. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12697. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12698. }
  12699. var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  12700. geometryGroup.__typeArray = UintArray;
  12701. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  12702. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  12703. var m, ml;
  12704. if ( geometryGroup.numMorphTargets ) {
  12705. geometryGroup.__morphTargetsArrays = [];
  12706. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12707. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12708. }
  12709. }
  12710. if ( geometryGroup.numMorphNormals ) {
  12711. geometryGroup.__morphNormalsArrays = [];
  12712. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12713. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12714. }
  12715. }
  12716. geometryGroup.__webglFaceCount = ntris * 3;
  12717. geometryGroup.__webglLineCount = nlines * 2;
  12718. // custom attributes
  12719. if ( material.attributes ) {
  12720. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12721. geometryGroup.__webglCustomAttributesList = [];
  12722. }
  12723. for ( var a in material.attributes ) {
  12724. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12725. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12726. var originalAttribute = material.attributes[ a ];
  12727. var attribute = {};
  12728. for ( var property in originalAttribute ) {
  12729. attribute[ property ] = originalAttribute[ property ];
  12730. }
  12731. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12732. attribute.__webglInitialized = true;
  12733. var size = 1; // "f" and "i"
  12734. if( attribute.type === "v2" ) size = 2;
  12735. else if( attribute.type === "v3" ) size = 3;
  12736. else if( attribute.type === "v4" ) size = 4;
  12737. else if( attribute.type === "c" ) size = 3;
  12738. attribute.size = size;
  12739. attribute.array = new Float32Array( nvertices * size );
  12740. attribute.buffer = _gl.createBuffer();
  12741. attribute.buffer.belongsToAttribute = a;
  12742. originalAttribute.needsUpdate = true;
  12743. attribute.__original = originalAttribute;
  12744. }
  12745. geometryGroup.__webglCustomAttributesList.push( attribute );
  12746. }
  12747. }
  12748. geometryGroup.__inittedArrays = true;
  12749. };
  12750. function getBufferMaterial( object, geometryGroup ) {
  12751. return object.material instanceof THREE.MeshFaceMaterial
  12752. ? object.material.materials[ geometryGroup.materialIndex ]
  12753. : object.material;
  12754. };
  12755. function materialNeedsSmoothNormals ( material ) {
  12756. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12757. };
  12758. function bufferGuessNormalType ( material ) {
  12759. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12760. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12761. return false;
  12762. }
  12763. if ( materialNeedsSmoothNormals( material ) ) {
  12764. return THREE.SmoothShading;
  12765. } else {
  12766. return THREE.FlatShading;
  12767. }
  12768. };
  12769. function bufferGuessVertexColorType( material ) {
  12770. if ( material.vertexColors ) {
  12771. return material.vertexColors;
  12772. }
  12773. return false;
  12774. };
  12775. function bufferGuessUVType( material ) {
  12776. // material must use some texture to require uvs
  12777. if ( material.map ||
  12778. material.lightMap ||
  12779. material.bumpMap ||
  12780. material.normalMap ||
  12781. material.specularMap ||
  12782. material instanceof THREE.ShaderMaterial ) {
  12783. return true;
  12784. }
  12785. return false;
  12786. };
  12787. //
  12788. function initDirectBuffers( geometry ) {
  12789. for ( var name in geometry.attributes ) {
  12790. var bufferType = ( name === "index" ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  12791. var attribute = geometry.attributes[ name ];
  12792. attribute.buffer = _gl.createBuffer();
  12793. _gl.bindBuffer( bufferType, attribute.buffer );
  12794. _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW );
  12795. }
  12796. }
  12797. // Buffer setting
  12798. function setParticleBuffers ( geometry, hint, object ) {
  12799. var v, c, vertex, offset, index, color,
  12800. vertices = geometry.vertices,
  12801. vl = vertices.length,
  12802. colors = geometry.colors,
  12803. cl = colors.length,
  12804. vertexArray = geometry.__vertexArray,
  12805. colorArray = geometry.__colorArray,
  12806. sortArray = geometry.__sortArray,
  12807. dirtyVertices = geometry.verticesNeedUpdate,
  12808. dirtyElements = geometry.elementsNeedUpdate,
  12809. dirtyColors = geometry.colorsNeedUpdate,
  12810. customAttributes = geometry.__webglCustomAttributesList,
  12811. i, il,
  12812. a, ca, cal, value,
  12813. customAttribute;
  12814. if ( object.sortParticles ) {
  12815. _projScreenMatrixPS.copy( _projScreenMatrix );
  12816. _projScreenMatrixPS.multiply( object.matrixWorld );
  12817. for ( v = 0; v < vl; v ++ ) {
  12818. vertex = vertices[ v ];
  12819. _vector3.copy( vertex );
  12820. _vector3.applyProjection( _projScreenMatrixPS );
  12821. sortArray[ v ] = [ _vector3.z, v ];
  12822. }
  12823. sortArray.sort( numericalSort );
  12824. for ( v = 0; v < vl; v ++ ) {
  12825. vertex = vertices[ sortArray[v][1] ];
  12826. offset = v * 3;
  12827. vertexArray[ offset ] = vertex.x;
  12828. vertexArray[ offset + 1 ] = vertex.y;
  12829. vertexArray[ offset + 2 ] = vertex.z;
  12830. }
  12831. for ( c = 0; c < cl; c ++ ) {
  12832. offset = c * 3;
  12833. color = colors[ sortArray[c][1] ];
  12834. colorArray[ offset ] = color.r;
  12835. colorArray[ offset + 1 ] = color.g;
  12836. colorArray[ offset + 2 ] = color.b;
  12837. }
  12838. if ( customAttributes ) {
  12839. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12840. customAttribute = customAttributes[ i ];
  12841. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12842. offset = 0;
  12843. cal = customAttribute.value.length;
  12844. if ( customAttribute.size === 1 ) {
  12845. for ( ca = 0; ca < cal; ca ++ ) {
  12846. index = sortArray[ ca ][ 1 ];
  12847. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12848. }
  12849. } else if ( customAttribute.size === 2 ) {
  12850. for ( ca = 0; ca < cal; ca ++ ) {
  12851. index = sortArray[ ca ][ 1 ];
  12852. value = customAttribute.value[ index ];
  12853. customAttribute.array[ offset ] = value.x;
  12854. customAttribute.array[ offset + 1 ] = value.y;
  12855. offset += 2;
  12856. }
  12857. } else if ( customAttribute.size === 3 ) {
  12858. if ( customAttribute.type === "c" ) {
  12859. for ( ca = 0; ca < cal; ca ++ ) {
  12860. index = sortArray[ ca ][ 1 ];
  12861. value = customAttribute.value[ index ];
  12862. customAttribute.array[ offset ] = value.r;
  12863. customAttribute.array[ offset + 1 ] = value.g;
  12864. customAttribute.array[ offset + 2 ] = value.b;
  12865. offset += 3;
  12866. }
  12867. } else {
  12868. for ( ca = 0; ca < cal; ca ++ ) {
  12869. index = sortArray[ ca ][ 1 ];
  12870. value = customAttribute.value[ index ];
  12871. customAttribute.array[ offset ] = value.x;
  12872. customAttribute.array[ offset + 1 ] = value.y;
  12873. customAttribute.array[ offset + 2 ] = value.z;
  12874. offset += 3;
  12875. }
  12876. }
  12877. } else if ( customAttribute.size === 4 ) {
  12878. for ( ca = 0; ca < cal; ca ++ ) {
  12879. index = sortArray[ ca ][ 1 ];
  12880. value = customAttribute.value[ index ];
  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. }
  12889. }
  12890. } else {
  12891. if ( dirtyVertices ) {
  12892. for ( v = 0; v < vl; v ++ ) {
  12893. vertex = vertices[ v ];
  12894. offset = v * 3;
  12895. vertexArray[ offset ] = vertex.x;
  12896. vertexArray[ offset + 1 ] = vertex.y;
  12897. vertexArray[ offset + 2 ] = vertex.z;
  12898. }
  12899. }
  12900. if ( dirtyColors ) {
  12901. for ( c = 0; c < cl; c ++ ) {
  12902. color = colors[ c ];
  12903. offset = c * 3;
  12904. colorArray[ offset ] = color.r;
  12905. colorArray[ offset + 1 ] = color.g;
  12906. colorArray[ offset + 2 ] = color.b;
  12907. }
  12908. }
  12909. if ( customAttributes ) {
  12910. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12911. customAttribute = customAttributes[ i ];
  12912. if ( customAttribute.needsUpdate &&
  12913. ( customAttribute.boundTo === undefined ||
  12914. customAttribute.boundTo === "vertices") ) {
  12915. cal = customAttribute.value.length;
  12916. offset = 0;
  12917. if ( customAttribute.size === 1 ) {
  12918. for ( ca = 0; ca < cal; ca ++ ) {
  12919. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12920. }
  12921. } else if ( customAttribute.size === 2 ) {
  12922. for ( ca = 0; ca < cal; ca ++ ) {
  12923. value = customAttribute.value[ ca ];
  12924. customAttribute.array[ offset ] = value.x;
  12925. customAttribute.array[ offset + 1 ] = value.y;
  12926. offset += 2;
  12927. }
  12928. } else if ( customAttribute.size === 3 ) {
  12929. if ( customAttribute.type === "c" ) {
  12930. for ( ca = 0; ca < cal; ca ++ ) {
  12931. value = customAttribute.value[ ca ];
  12932. customAttribute.array[ offset ] = value.r;
  12933. customAttribute.array[ offset + 1 ] = value.g;
  12934. customAttribute.array[ offset + 2 ] = value.b;
  12935. offset += 3;
  12936. }
  12937. } else {
  12938. for ( ca = 0; ca < cal; ca ++ ) {
  12939. value = customAttribute.value[ ca ];
  12940. customAttribute.array[ offset ] = value.x;
  12941. customAttribute.array[ offset + 1 ] = value.y;
  12942. customAttribute.array[ offset + 2 ] = value.z;
  12943. offset += 3;
  12944. }
  12945. }
  12946. } else if ( customAttribute.size === 4 ) {
  12947. for ( ca = 0; ca < cal; ca ++ ) {
  12948. value = customAttribute.value[ ca ];
  12949. customAttribute.array[ offset ] = value.x;
  12950. customAttribute.array[ offset + 1 ] = value.y;
  12951. customAttribute.array[ offset + 2 ] = value.z;
  12952. customAttribute.array[ offset + 3 ] = value.w;
  12953. offset += 4;
  12954. }
  12955. }
  12956. }
  12957. }
  12958. }
  12959. }
  12960. if ( dirtyVertices || object.sortParticles ) {
  12961. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12962. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12963. }
  12964. if ( dirtyColors || object.sortParticles ) {
  12965. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12966. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12967. }
  12968. if ( customAttributes ) {
  12969. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12970. customAttribute = customAttributes[ i ];
  12971. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12972. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12973. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12974. }
  12975. }
  12976. }
  12977. }
  12978. function setLineBuffers ( geometry, hint ) {
  12979. var v, c, d, vertex, offset, color,
  12980. vertices = geometry.vertices,
  12981. colors = geometry.colors,
  12982. lineDistances = geometry.lineDistances,
  12983. vl = vertices.length,
  12984. cl = colors.length,
  12985. dl = lineDistances.length,
  12986. vertexArray = geometry.__vertexArray,
  12987. colorArray = geometry.__colorArray,
  12988. lineDistanceArray = geometry.__lineDistanceArray,
  12989. dirtyVertices = geometry.verticesNeedUpdate,
  12990. dirtyColors = geometry.colorsNeedUpdate,
  12991. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12992. customAttributes = geometry.__webglCustomAttributesList,
  12993. i, il,
  12994. a, ca, cal, value,
  12995. customAttribute;
  12996. if ( dirtyVertices ) {
  12997. for ( v = 0; v < vl; v ++ ) {
  12998. vertex = vertices[ v ];
  12999. offset = v * 3;
  13000. vertexArray[ offset ] = vertex.x;
  13001. vertexArray[ offset + 1 ] = vertex.y;
  13002. vertexArray[ offset + 2 ] = vertex.z;
  13003. }
  13004. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  13005. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13006. }
  13007. if ( dirtyColors ) {
  13008. for ( c = 0; c < cl; c ++ ) {
  13009. color = colors[ c ];
  13010. offset = c * 3;
  13011. colorArray[ offset ] = color.r;
  13012. colorArray[ offset + 1 ] = color.g;
  13013. colorArray[ offset + 2 ] = color.b;
  13014. }
  13015. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  13016. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13017. }
  13018. if ( dirtyLineDistances ) {
  13019. for ( d = 0; d < dl; d ++ ) {
  13020. lineDistanceArray[ d ] = lineDistances[ d ];
  13021. }
  13022. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  13023. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  13024. }
  13025. if ( customAttributes ) {
  13026. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13027. customAttribute = customAttributes[ i ];
  13028. if ( customAttribute.needsUpdate &&
  13029. ( customAttribute.boundTo === undefined ||
  13030. customAttribute.boundTo === "vertices" ) ) {
  13031. offset = 0;
  13032. cal = customAttribute.value.length;
  13033. if ( customAttribute.size === 1 ) {
  13034. for ( ca = 0; ca < cal; ca ++ ) {
  13035. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  13036. }
  13037. } else if ( customAttribute.size === 2 ) {
  13038. for ( ca = 0; ca < cal; ca ++ ) {
  13039. value = customAttribute.value[ ca ];
  13040. customAttribute.array[ offset ] = value.x;
  13041. customAttribute.array[ offset + 1 ] = value.y;
  13042. offset += 2;
  13043. }
  13044. } else if ( customAttribute.size === 3 ) {
  13045. if ( customAttribute.type === "c" ) {
  13046. for ( ca = 0; ca < cal; ca ++ ) {
  13047. value = customAttribute.value[ ca ];
  13048. customAttribute.array[ offset ] = value.r;
  13049. customAttribute.array[ offset + 1 ] = value.g;
  13050. customAttribute.array[ offset + 2 ] = value.b;
  13051. offset += 3;
  13052. }
  13053. } else {
  13054. for ( ca = 0; ca < cal; ca ++ ) {
  13055. value = customAttribute.value[ ca ];
  13056. customAttribute.array[ offset ] = value.x;
  13057. customAttribute.array[ offset + 1 ] = value.y;
  13058. customAttribute.array[ offset + 2 ] = value.z;
  13059. offset += 3;
  13060. }
  13061. }
  13062. } else if ( customAttribute.size === 4 ) {
  13063. for ( ca = 0; ca < cal; ca ++ ) {
  13064. value = customAttribute.value[ ca ];
  13065. customAttribute.array[ offset ] = value.x;
  13066. customAttribute.array[ offset + 1 ] = value.y;
  13067. customAttribute.array[ offset + 2 ] = value.z;
  13068. customAttribute.array[ offset + 3 ] = value.w;
  13069. offset += 4;
  13070. }
  13071. }
  13072. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13073. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13074. }
  13075. }
  13076. }
  13077. }
  13078. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  13079. if ( ! geometryGroup.__inittedArrays ) {
  13080. return;
  13081. }
  13082. var normalType = bufferGuessNormalType( material ),
  13083. vertexColorType = bufferGuessVertexColorType( material ),
  13084. uvType = bufferGuessUVType( material ),
  13085. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  13086. var f, fl, fi, face,
  13087. vertexNormals, faceNormal, normal,
  13088. vertexColors, faceColor,
  13089. vertexTangents,
  13090. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  13091. c1, c2, c3, c4,
  13092. sw1, sw2, sw3, sw4,
  13093. si1, si2, si3, si4,
  13094. sa1, sa2, sa3, sa4,
  13095. sb1, sb2, sb3, sb4,
  13096. m, ml, i, il,
  13097. vn, uvi, uv2i,
  13098. vk, vkl, vka,
  13099. nka, chf, faceVertexNormals,
  13100. a,
  13101. vertexIndex = 0,
  13102. offset = 0,
  13103. offset_uv = 0,
  13104. offset_uv2 = 0,
  13105. offset_face = 0,
  13106. offset_normal = 0,
  13107. offset_tangent = 0,
  13108. offset_line = 0,
  13109. offset_color = 0,
  13110. offset_skin = 0,
  13111. offset_morphTarget = 0,
  13112. offset_custom = 0,
  13113. offset_customSrc = 0,
  13114. value,
  13115. vertexArray = geometryGroup.__vertexArray,
  13116. uvArray = geometryGroup.__uvArray,
  13117. uv2Array = geometryGroup.__uv2Array,
  13118. normalArray = geometryGroup.__normalArray,
  13119. tangentArray = geometryGroup.__tangentArray,
  13120. colorArray = geometryGroup.__colorArray,
  13121. skinIndexArray = geometryGroup.__skinIndexArray,
  13122. skinWeightArray = geometryGroup.__skinWeightArray,
  13123. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  13124. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  13125. customAttributes = geometryGroup.__webglCustomAttributesList,
  13126. customAttribute,
  13127. faceArray = geometryGroup.__faceArray,
  13128. lineArray = geometryGroup.__lineArray,
  13129. geometry = object.geometry, // this is shared for all chunks
  13130. dirtyVertices = geometry.verticesNeedUpdate,
  13131. dirtyElements = geometry.elementsNeedUpdate,
  13132. dirtyUvs = geometry.uvsNeedUpdate,
  13133. dirtyNormals = geometry.normalsNeedUpdate,
  13134. dirtyTangents = geometry.tangentsNeedUpdate,
  13135. dirtyColors = geometry.colorsNeedUpdate,
  13136. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  13137. vertices = geometry.vertices,
  13138. chunk_faces3 = geometryGroup.faces3,
  13139. obj_faces = geometry.faces,
  13140. obj_uvs = geometry.faceVertexUvs[ 0 ],
  13141. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  13142. obj_colors = geometry.colors,
  13143. obj_skinIndices = geometry.skinIndices,
  13144. obj_skinWeights = geometry.skinWeights,
  13145. morphTargets = geometry.morphTargets,
  13146. morphNormals = geometry.morphNormals;
  13147. if ( dirtyVertices ) {
  13148. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13149. face = obj_faces[ chunk_faces3[ f ] ];
  13150. v1 = vertices[ face.a ];
  13151. v2 = vertices[ face.b ];
  13152. v3 = vertices[ face.c ];
  13153. vertexArray[ offset ] = v1.x;
  13154. vertexArray[ offset + 1 ] = v1.y;
  13155. vertexArray[ offset + 2 ] = v1.z;
  13156. vertexArray[ offset + 3 ] = v2.x;
  13157. vertexArray[ offset + 4 ] = v2.y;
  13158. vertexArray[ offset + 5 ] = v2.z;
  13159. vertexArray[ offset + 6 ] = v3.x;
  13160. vertexArray[ offset + 7 ] = v3.y;
  13161. vertexArray[ offset + 8 ] = v3.z;
  13162. offset += 9;
  13163. }
  13164. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13165. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13166. }
  13167. if ( dirtyMorphTargets ) {
  13168. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  13169. offset_morphTarget = 0;
  13170. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13171. chf = chunk_faces3[ f ];
  13172. face = obj_faces[ chf ];
  13173. // morph positions
  13174. v1 = morphTargets[ vk ].vertices[ face.a ];
  13175. v2 = morphTargets[ vk ].vertices[ face.b ];
  13176. v3 = morphTargets[ vk ].vertices[ face.c ];
  13177. vka = morphTargetsArrays[ vk ];
  13178. vka[ offset_morphTarget ] = v1.x;
  13179. vka[ offset_morphTarget + 1 ] = v1.y;
  13180. vka[ offset_morphTarget + 2 ] = v1.z;
  13181. vka[ offset_morphTarget + 3 ] = v2.x;
  13182. vka[ offset_morphTarget + 4 ] = v2.y;
  13183. vka[ offset_morphTarget + 5 ] = v2.z;
  13184. vka[ offset_morphTarget + 6 ] = v3.x;
  13185. vka[ offset_morphTarget + 7 ] = v3.y;
  13186. vka[ offset_morphTarget + 8 ] = v3.z;
  13187. // morph normals
  13188. if ( material.morphNormals ) {
  13189. if ( needsSmoothNormals ) {
  13190. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  13191. n1 = faceVertexNormals.a;
  13192. n2 = faceVertexNormals.b;
  13193. n3 = faceVertexNormals.c;
  13194. } else {
  13195. n1 = morphNormals[ vk ].faceNormals[ chf ];
  13196. n2 = n1;
  13197. n3 = n1;
  13198. }
  13199. nka = morphNormalsArrays[ vk ];
  13200. nka[ offset_morphTarget ] = n1.x;
  13201. nka[ offset_morphTarget + 1 ] = n1.y;
  13202. nka[ offset_morphTarget + 2 ] = n1.z;
  13203. nka[ offset_morphTarget + 3 ] = n2.x;
  13204. nka[ offset_morphTarget + 4 ] = n2.y;
  13205. nka[ offset_morphTarget + 5 ] = n2.z;
  13206. nka[ offset_morphTarget + 6 ] = n3.x;
  13207. nka[ offset_morphTarget + 7 ] = n3.y;
  13208. nka[ offset_morphTarget + 8 ] = n3.z;
  13209. }
  13210. //
  13211. offset_morphTarget += 9;
  13212. }
  13213. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  13214. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  13215. if ( material.morphNormals ) {
  13216. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  13217. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  13218. }
  13219. }
  13220. }
  13221. if ( obj_skinWeights.length ) {
  13222. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13223. face = obj_faces[ chunk_faces3[ f ] ];
  13224. // weights
  13225. sw1 = obj_skinWeights[ face.a ];
  13226. sw2 = obj_skinWeights[ face.b ];
  13227. sw3 = obj_skinWeights[ face.c ];
  13228. skinWeightArray[ offset_skin ] = sw1.x;
  13229. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  13230. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  13231. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  13232. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  13233. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  13234. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  13235. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  13236. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  13237. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  13238. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  13239. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  13240. // indices
  13241. si1 = obj_skinIndices[ face.a ];
  13242. si2 = obj_skinIndices[ face.b ];
  13243. si3 = obj_skinIndices[ face.c ];
  13244. skinIndexArray[ offset_skin ] = si1.x;
  13245. skinIndexArray[ offset_skin + 1 ] = si1.y;
  13246. skinIndexArray[ offset_skin + 2 ] = si1.z;
  13247. skinIndexArray[ offset_skin + 3 ] = si1.w;
  13248. skinIndexArray[ offset_skin + 4 ] = si2.x;
  13249. skinIndexArray[ offset_skin + 5 ] = si2.y;
  13250. skinIndexArray[ offset_skin + 6 ] = si2.z;
  13251. skinIndexArray[ offset_skin + 7 ] = si2.w;
  13252. skinIndexArray[ offset_skin + 8 ] = si3.x;
  13253. skinIndexArray[ offset_skin + 9 ] = si3.y;
  13254. skinIndexArray[ offset_skin + 10 ] = si3.z;
  13255. skinIndexArray[ offset_skin + 11 ] = si3.w;
  13256. offset_skin += 12;
  13257. }
  13258. if ( offset_skin > 0 ) {
  13259. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13260. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  13261. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13262. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  13263. }
  13264. }
  13265. if ( dirtyColors && vertexColorType ) {
  13266. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13267. face = obj_faces[ chunk_faces3[ f ] ];
  13268. vertexColors = face.vertexColors;
  13269. faceColor = face.color;
  13270. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  13271. c1 = vertexColors[ 0 ];
  13272. c2 = vertexColors[ 1 ];
  13273. c3 = vertexColors[ 2 ];
  13274. } else {
  13275. c1 = faceColor;
  13276. c2 = faceColor;
  13277. c3 = faceColor;
  13278. }
  13279. colorArray[ offset_color ] = c1.r;
  13280. colorArray[ offset_color + 1 ] = c1.g;
  13281. colorArray[ offset_color + 2 ] = c1.b;
  13282. colorArray[ offset_color + 3 ] = c2.r;
  13283. colorArray[ offset_color + 4 ] = c2.g;
  13284. colorArray[ offset_color + 5 ] = c2.b;
  13285. colorArray[ offset_color + 6 ] = c3.r;
  13286. colorArray[ offset_color + 7 ] = c3.g;
  13287. colorArray[ offset_color + 8 ] = c3.b;
  13288. offset_color += 9;
  13289. }
  13290. if ( offset_color > 0 ) {
  13291. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13292. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13293. }
  13294. }
  13295. if ( dirtyTangents && geometry.hasTangents ) {
  13296. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13297. face = obj_faces[ chunk_faces3[ f ] ];
  13298. vertexTangents = face.vertexTangents;
  13299. t1 = vertexTangents[ 0 ];
  13300. t2 = vertexTangents[ 1 ];
  13301. t3 = vertexTangents[ 2 ];
  13302. tangentArray[ offset_tangent ] = t1.x;
  13303. tangentArray[ offset_tangent + 1 ] = t1.y;
  13304. tangentArray[ offset_tangent + 2 ] = t1.z;
  13305. tangentArray[ offset_tangent + 3 ] = t1.w;
  13306. tangentArray[ offset_tangent + 4 ] = t2.x;
  13307. tangentArray[ offset_tangent + 5 ] = t2.y;
  13308. tangentArray[ offset_tangent + 6 ] = t2.z;
  13309. tangentArray[ offset_tangent + 7 ] = t2.w;
  13310. tangentArray[ offset_tangent + 8 ] = t3.x;
  13311. tangentArray[ offset_tangent + 9 ] = t3.y;
  13312. tangentArray[ offset_tangent + 10 ] = t3.z;
  13313. tangentArray[ offset_tangent + 11 ] = t3.w;
  13314. offset_tangent += 12;
  13315. }
  13316. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13317. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  13318. }
  13319. if ( dirtyNormals && normalType ) {
  13320. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13321. face = obj_faces[ chunk_faces3[ f ] ];
  13322. vertexNormals = face.vertexNormals;
  13323. faceNormal = face.normal;
  13324. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  13325. for ( i = 0; i < 3; i ++ ) {
  13326. vn = vertexNormals[ i ];
  13327. normalArray[ offset_normal ] = vn.x;
  13328. normalArray[ offset_normal + 1 ] = vn.y;
  13329. normalArray[ offset_normal + 2 ] = vn.z;
  13330. offset_normal += 3;
  13331. }
  13332. } else {
  13333. for ( i = 0; i < 3; i ++ ) {
  13334. normalArray[ offset_normal ] = faceNormal.x;
  13335. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13336. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13337. offset_normal += 3;
  13338. }
  13339. }
  13340. }
  13341. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13342. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  13343. }
  13344. if ( dirtyUvs && obj_uvs && uvType ) {
  13345. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13346. fi = chunk_faces3[ f ];
  13347. uv = obj_uvs[ fi ];
  13348. if ( uv === undefined ) continue;
  13349. for ( i = 0; i < 3; i ++ ) {
  13350. uvi = uv[ i ];
  13351. uvArray[ offset_uv ] = uvi.x;
  13352. uvArray[ offset_uv + 1 ] = uvi.y;
  13353. offset_uv += 2;
  13354. }
  13355. }
  13356. if ( offset_uv > 0 ) {
  13357. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13358. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  13359. }
  13360. }
  13361. if ( dirtyUvs && obj_uvs2 && uvType ) {
  13362. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13363. fi = chunk_faces3[ f ];
  13364. uv2 = obj_uvs2[ fi ];
  13365. if ( uv2 === undefined ) continue;
  13366. for ( i = 0; i < 3; i ++ ) {
  13367. uv2i = uv2[ i ];
  13368. uv2Array[ offset_uv2 ] = uv2i.x;
  13369. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13370. offset_uv2 += 2;
  13371. }
  13372. }
  13373. if ( offset_uv2 > 0 ) {
  13374. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13375. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  13376. }
  13377. }
  13378. if ( dirtyElements ) {
  13379. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13380. faceArray[ offset_face ] = vertexIndex;
  13381. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13382. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  13383. offset_face += 3;
  13384. lineArray[ offset_line ] = vertexIndex;
  13385. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13386. lineArray[ offset_line + 2 ] = vertexIndex;
  13387. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13388. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13389. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13390. offset_line += 6;
  13391. vertexIndex += 3;
  13392. }
  13393. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13394. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13395. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13396. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13397. }
  13398. if ( customAttributes ) {
  13399. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13400. customAttribute = customAttributes[ i ];
  13401. if ( ! customAttribute.__original.needsUpdate ) continue;
  13402. offset_custom = 0;
  13403. offset_customSrc = 0;
  13404. if ( customAttribute.size === 1 ) {
  13405. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13406. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13407. face = obj_faces[ chunk_faces3[ f ] ];
  13408. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13409. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13410. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13411. offset_custom += 3;
  13412. }
  13413. } else if ( customAttribute.boundTo === "faces" ) {
  13414. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13415. value = customAttribute.value[ chunk_faces3[ f ] ];
  13416. customAttribute.array[ offset_custom ] = value;
  13417. customAttribute.array[ offset_custom + 1 ] = value;
  13418. customAttribute.array[ offset_custom + 2 ] = value;
  13419. offset_custom += 3;
  13420. }
  13421. }
  13422. } else if ( customAttribute.size === 2 ) {
  13423. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13424. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13425. face = obj_faces[ chunk_faces3[ f ] ];
  13426. v1 = customAttribute.value[ face.a ];
  13427. v2 = customAttribute.value[ face.b ];
  13428. v3 = customAttribute.value[ face.c ];
  13429. customAttribute.array[ offset_custom ] = v1.x;
  13430. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13431. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13432. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13433. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13434. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13435. offset_custom += 6;
  13436. }
  13437. } else if ( customAttribute.boundTo === "faces" ) {
  13438. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13439. value = customAttribute.value[ chunk_faces3[ f ] ];
  13440. v1 = value;
  13441. v2 = value;
  13442. v3 = value;
  13443. customAttribute.array[ offset_custom ] = v1.x;
  13444. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13445. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13446. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13447. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13448. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13449. offset_custom += 6;
  13450. }
  13451. }
  13452. } else if ( customAttribute.size === 3 ) {
  13453. var pp;
  13454. if ( customAttribute.type === "c" ) {
  13455. pp = [ "r", "g", "b" ];
  13456. } else {
  13457. pp = [ "x", "y", "z" ];
  13458. }
  13459. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13460. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13461. face = obj_faces[ chunk_faces3[ f ] ];
  13462. v1 = customAttribute.value[ face.a ];
  13463. v2 = customAttribute.value[ face.b ];
  13464. v3 = customAttribute.value[ face.c ];
  13465. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13466. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13467. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13468. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13469. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13470. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13471. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13472. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13473. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13474. offset_custom += 9;
  13475. }
  13476. } else if ( customAttribute.boundTo === "faces" ) {
  13477. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13478. value = customAttribute.value[ chunk_faces3[ f ] ];
  13479. v1 = value;
  13480. v2 = value;
  13481. v3 = value;
  13482. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13483. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13484. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13485. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13486. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13487. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13488. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13489. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13490. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13491. offset_custom += 9;
  13492. }
  13493. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13494. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13495. value = customAttribute.value[ chunk_faces3[ f ] ];
  13496. v1 = value[ 0 ];
  13497. v2 = value[ 1 ];
  13498. v3 = value[ 2 ];
  13499. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13500. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13501. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13502. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13503. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13504. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13505. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13506. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13507. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13508. offset_custom += 9;
  13509. }
  13510. }
  13511. } else if ( customAttribute.size === 4 ) {
  13512. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13513. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13514. face = obj_faces[ chunk_faces3[ f ] ];
  13515. v1 = customAttribute.value[ face.a ];
  13516. v2 = customAttribute.value[ face.b ];
  13517. v3 = customAttribute.value[ face.c ];
  13518. customAttribute.array[ offset_custom ] = v1.x;
  13519. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13520. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13521. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13522. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13523. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13524. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13525. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13526. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13527. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13528. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13529. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13530. offset_custom += 12;
  13531. }
  13532. } else if ( customAttribute.boundTo === "faces" ) {
  13533. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13534. value = customAttribute.value[ chunk_faces3[ f ] ];
  13535. v1 = value;
  13536. v2 = value;
  13537. v3 = value;
  13538. customAttribute.array[ offset_custom ] = v1.x;
  13539. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13540. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13541. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13542. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13543. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13544. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13545. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13546. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13547. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13548. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13549. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13550. offset_custom += 12;
  13551. }
  13552. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13553. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13554. value = customAttribute.value[ chunk_faces3[ f ] ];
  13555. v1 = value[ 0 ];
  13556. v2 = value[ 1 ];
  13557. v3 = value[ 2 ];
  13558. customAttribute.array[ offset_custom ] = v1.x;
  13559. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13560. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13561. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13562. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13563. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13564. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13565. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13566. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13567. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13568. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13569. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13570. offset_custom += 12;
  13571. }
  13572. }
  13573. }
  13574. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13575. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13576. }
  13577. }
  13578. if ( dispose ) {
  13579. delete geometryGroup.__inittedArrays;
  13580. delete geometryGroup.__colorArray;
  13581. delete geometryGroup.__normalArray;
  13582. delete geometryGroup.__tangentArray;
  13583. delete geometryGroup.__uvArray;
  13584. delete geometryGroup.__uv2Array;
  13585. delete geometryGroup.__faceArray;
  13586. delete geometryGroup.__vertexArray;
  13587. delete geometryGroup.__lineArray;
  13588. delete geometryGroup.__skinIndexArray;
  13589. delete geometryGroup.__skinWeightArray;
  13590. }
  13591. };
  13592. function setDirectBuffers( geometry, hint ) {
  13593. var attributes = geometry.attributes;
  13594. var attributeName, attributeItem;
  13595. for ( attributeName in attributes ) {
  13596. attributeItem = attributes[ attributeName ];
  13597. if ( attributeItem.needsUpdate ) {
  13598. if ( attributeName === 'index' ) {
  13599. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13600. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13601. } else {
  13602. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13603. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13604. }
  13605. attributeItem.needsUpdate = false;
  13606. }
  13607. }
  13608. }
  13609. // Buffer rendering
  13610. this.renderBufferImmediate = function ( object, program, material ) {
  13611. initAttributes();
  13612. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13613. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13614. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13615. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13616. if ( object.hasPositions ) {
  13617. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13618. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13619. enableAttribute( program.attributes.position );
  13620. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13621. }
  13622. if ( object.hasNormals ) {
  13623. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13624. if ( material.shading === THREE.FlatShading ) {
  13625. var nx, ny, nz,
  13626. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13627. normalArray,
  13628. i, il = object.count * 3;
  13629. for( i = 0; i < il; i += 9 ) {
  13630. normalArray = object.normalArray;
  13631. nax = normalArray[ i ];
  13632. nay = normalArray[ i + 1 ];
  13633. naz = normalArray[ i + 2 ];
  13634. nbx = normalArray[ i + 3 ];
  13635. nby = normalArray[ i + 4 ];
  13636. nbz = normalArray[ i + 5 ];
  13637. ncx = normalArray[ i + 6 ];
  13638. ncy = normalArray[ i + 7 ];
  13639. ncz = normalArray[ i + 8 ];
  13640. nx = ( nax + nbx + ncx ) / 3;
  13641. ny = ( nay + nby + ncy ) / 3;
  13642. nz = ( naz + nbz + ncz ) / 3;
  13643. normalArray[ i ] = nx;
  13644. normalArray[ i + 1 ] = ny;
  13645. normalArray[ i + 2 ] = nz;
  13646. normalArray[ i + 3 ] = nx;
  13647. normalArray[ i + 4 ] = ny;
  13648. normalArray[ i + 5 ] = nz;
  13649. normalArray[ i + 6 ] = nx;
  13650. normalArray[ i + 7 ] = ny;
  13651. normalArray[ i + 8 ] = nz;
  13652. }
  13653. }
  13654. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13655. enableAttribute( program.attributes.normal );
  13656. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13657. }
  13658. if ( object.hasUvs && material.map ) {
  13659. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13660. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13661. enableAttribute( program.attributes.uv );
  13662. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13663. }
  13664. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13665. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13666. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13667. enableAttribute( program.attributes.color );
  13668. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13669. }
  13670. disableUnusedAttributes();
  13671. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13672. object.count = 0;
  13673. };
  13674. function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13675. for ( var attributeName in programAttributes ) {
  13676. var attributePointer = programAttributes[ attributeName ];
  13677. var attributeItem = geometryAttributes[ attributeName ];
  13678. if ( attributePointer >= 0 ) {
  13679. if ( attributeItem ) {
  13680. var attributeSize = attributeItem.itemSize;
  13681. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13682. enableAttribute( attributePointer );
  13683. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13684. } else if ( material.defaultAttributeValues ) {
  13685. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13686. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13687. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13688. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13689. }
  13690. }
  13691. }
  13692. }
  13693. disableUnusedAttributes();
  13694. }
  13695. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13696. if ( material.visible === false ) return;
  13697. var linewidth, a, attribute;
  13698. var attributeItem, attributeName, attributePointer, attributeSize;
  13699. var program = setProgram( camera, lights, fog, material, object );
  13700. var programAttributes = program.attributes;
  13701. var geometryAttributes = geometry.attributes;
  13702. var updateBuffers = false,
  13703. wireframeBit = material.wireframe ? 1 : 0,
  13704. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13705. if ( geometryHash !== _currentGeometryGroupHash ) {
  13706. _currentGeometryGroupHash = geometryHash;
  13707. updateBuffers = true;
  13708. }
  13709. if ( updateBuffers ) {
  13710. initAttributes();
  13711. }
  13712. // render mesh
  13713. if ( object instanceof THREE.Mesh ) {
  13714. var index = geometryAttributes[ "index" ];
  13715. if ( index ) {
  13716. // indexed triangles
  13717. var type, size;
  13718. if ( index.array instanceof Uint32Array ) {
  13719. type = _gl.UNSIGNED_INT;
  13720. size = 4;
  13721. } else {
  13722. type = _gl.UNSIGNED_SHORT;
  13723. size = 2;
  13724. }
  13725. var offsets = geometry.offsets;
  13726. if ( offsets.length === 0 ) {
  13727. if ( updateBuffers ) {
  13728. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13729. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13730. }
  13731. _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 );
  13732. _this.info.render.calls ++;
  13733. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13734. _this.info.render.faces += index.array.length / 3;
  13735. } else {
  13736. // if there is more than 1 chunk
  13737. // must set attribute pointers to use new offsets for each chunk
  13738. // even if geometry and materials didn't change
  13739. updateBuffers = true;
  13740. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13741. var startIndex = offsets[ i ].index;
  13742. if ( updateBuffers ) {
  13743. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13744. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13745. }
  13746. // render indexed triangles
  13747. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size );
  13748. _this.info.render.calls ++;
  13749. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13750. _this.info.render.faces += offsets[ i ].count / 3;
  13751. }
  13752. }
  13753. } else {
  13754. // non-indexed triangles
  13755. if ( updateBuffers ) {
  13756. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13757. }
  13758. var position = geometry.attributes[ "position" ];
  13759. // render non-indexed triangles
  13760. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13761. _this.info.render.calls ++;
  13762. _this.info.render.vertices += position.array.length / 3;
  13763. _this.info.render.faces += position.array.length / 9;
  13764. }
  13765. } else if ( object instanceof THREE.ParticleSystem ) {
  13766. // render particles
  13767. if ( updateBuffers ) {
  13768. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13769. }
  13770. var position = geometryAttributes[ "position" ];
  13771. // render particles
  13772. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13773. _this.info.render.calls ++;
  13774. _this.info.render.points += position.array.length / 3;
  13775. } else if ( object instanceof THREE.Line ) {
  13776. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13777. setLineWidth( material.linewidth );
  13778. var index = geometryAttributes[ "index" ];
  13779. if ( index ) {
  13780. // indexed lines
  13781. var type, size;
  13782. if ( index.array instanceof Uint32Array ){
  13783. type = _gl.UNSIGNED_INT;
  13784. size = 4;
  13785. } else {
  13786. type = _gl.UNSIGNED_SHORT;
  13787. size = 2;
  13788. }
  13789. var offsets = geometry.offsets;
  13790. if ( offsets.length === 0 ) {
  13791. if ( updateBuffers ) {
  13792. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13793. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13794. }
  13795. _gl.drawElements( _gl.LINES, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  13796. _this.info.render.calls ++;
  13797. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13798. } else {
  13799. // if there is more than 1 chunk
  13800. // must set attribute pointers to use new offsets for each chunk
  13801. // even if geometry and materials didn't change
  13802. if ( offsets.length > 1 ) updateBuffers = true;
  13803. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13804. var startIndex = offsets[ i ].index;
  13805. if ( updateBuffers ) {
  13806. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13807. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13808. }
  13809. // render indexed lines
  13810. _gl.drawElements( _gl.LINES, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  13811. _this.info.render.calls ++;
  13812. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13813. }
  13814. }
  13815. } else {
  13816. // non-indexed lines
  13817. if ( updateBuffers ) {
  13818. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13819. }
  13820. var position = geometryAttributes[ "position" ];
  13821. _gl.drawArrays( mode, 0, position.array.length / 3 );
  13822. _this.info.render.calls ++;
  13823. _this.info.render.points += position.array.length / 3;
  13824. }
  13825. }
  13826. };
  13827. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13828. if ( material.visible === false ) return;
  13829. var linewidth, a, attribute, i, il;
  13830. var program = setProgram( camera, lights, fog, material, object );
  13831. var attributes = program.attributes;
  13832. var updateBuffers = false,
  13833. wireframeBit = material.wireframe ? 1 : 0,
  13834. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13835. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13836. _currentGeometryGroupHash = geometryGroupHash;
  13837. updateBuffers = true;
  13838. }
  13839. if ( updateBuffers ) {
  13840. initAttributes();
  13841. }
  13842. // vertices
  13843. if ( !material.morphTargets && attributes.position >= 0 ) {
  13844. if ( updateBuffers ) {
  13845. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13846. enableAttribute( attributes.position );
  13847. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13848. }
  13849. } else {
  13850. if ( object.morphTargetBase ) {
  13851. setupMorphTargets( material, geometryGroup, object );
  13852. }
  13853. }
  13854. if ( updateBuffers ) {
  13855. // custom attributes
  13856. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13857. if ( geometryGroup.__webglCustomAttributesList ) {
  13858. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13859. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13860. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13861. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13862. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13863. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13864. }
  13865. }
  13866. }
  13867. // colors
  13868. if ( attributes.color >= 0 ) {
  13869. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13870. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13871. enableAttribute( attributes.color );
  13872. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13873. } else if ( material.defaultAttributeValues ) {
  13874. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13875. }
  13876. }
  13877. // normals
  13878. if ( attributes.normal >= 0 ) {
  13879. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13880. enableAttribute( attributes.normal );
  13881. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13882. }
  13883. // tangents
  13884. if ( attributes.tangent >= 0 ) {
  13885. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13886. enableAttribute( attributes.tangent );
  13887. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13888. }
  13889. // uvs
  13890. if ( attributes.uv >= 0 ) {
  13891. if ( object.geometry.faceVertexUvs[0] ) {
  13892. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13893. enableAttribute( attributes.uv );
  13894. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13895. } else if ( material.defaultAttributeValues ) {
  13896. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13897. }
  13898. }
  13899. if ( attributes.uv2 >= 0 ) {
  13900. if ( object.geometry.faceVertexUvs[1] ) {
  13901. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13902. enableAttribute( attributes.uv2 );
  13903. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13904. } else if ( material.defaultAttributeValues ) {
  13905. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13906. }
  13907. }
  13908. if ( material.skinning &&
  13909. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13910. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13911. enableAttribute( attributes.skinIndex );
  13912. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13913. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13914. enableAttribute( attributes.skinWeight );
  13915. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13916. }
  13917. // line distances
  13918. if ( attributes.lineDistance >= 0 ) {
  13919. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13920. enableAttribute( attributes.lineDistance );
  13921. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13922. }
  13923. }
  13924. disableUnusedAttributes();
  13925. // render mesh
  13926. if ( object instanceof THREE.Mesh ) {
  13927. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  13928. // wireframe
  13929. if ( material.wireframe ) {
  13930. setLineWidth( material.wireframeLinewidth );
  13931. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13932. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  13933. // triangles
  13934. } else {
  13935. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13936. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  13937. }
  13938. _this.info.render.calls ++;
  13939. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13940. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13941. // render lines
  13942. } else if ( object instanceof THREE.Line ) {
  13943. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13944. setLineWidth( material.linewidth );
  13945. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  13946. _this.info.render.calls ++;
  13947. // render particles
  13948. } else if ( object instanceof THREE.ParticleSystem ) {
  13949. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13950. _this.info.render.calls ++;
  13951. _this.info.render.points += geometryGroup.__webglParticleCount;
  13952. }
  13953. };
  13954. function initAttributes() {
  13955. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  13956. _newAttributes[ i ] = 0;
  13957. }
  13958. }
  13959. function enableAttribute( attribute ) {
  13960. _newAttributes[ attribute ] = 1;
  13961. if ( _enabledAttributes[ attribute ] === 0 ) {
  13962. _gl.enableVertexAttribArray( attribute );
  13963. _enabledAttributes[ attribute ] = 1;
  13964. }
  13965. }
  13966. function disableUnusedAttributes() {
  13967. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  13968. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  13969. _gl.disableVertexAttribArray( i );
  13970. _enabledAttributes[ i ] = 0;
  13971. }
  13972. }
  13973. }
  13974. function setupMorphTargets ( material, geometryGroup, object ) {
  13975. // set base
  13976. var attributes = material.program.attributes;
  13977. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13978. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13979. enableAttribute( attributes.position );
  13980. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13981. } else if ( attributes.position >= 0 ) {
  13982. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13983. enableAttribute( attributes.position );
  13984. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13985. }
  13986. if ( object.morphTargetForcedOrder.length ) {
  13987. // set forced order
  13988. var m = 0;
  13989. var order = object.morphTargetForcedOrder;
  13990. var influences = object.morphTargetInfluences;
  13991. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13992. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13993. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13994. enableAttribute( attributes[ "morphTarget" + m ] );
  13995. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13996. }
  13997. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13998. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13999. enableAttribute( attributes[ "morphNormal" + m ] );
  14000. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14001. }
  14002. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  14003. m ++;
  14004. }
  14005. } else {
  14006. // find the most influencing
  14007. var influence, activeInfluenceIndices = [];
  14008. var influences = object.morphTargetInfluences;
  14009. var i, il = influences.length;
  14010. for ( i = 0; i < il; i ++ ) {
  14011. influence = influences[ i ];
  14012. if ( influence > 0 ) {
  14013. activeInfluenceIndices.push( [ influence, i ] );
  14014. }
  14015. }
  14016. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  14017. activeInfluenceIndices.sort( numericalSort );
  14018. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  14019. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  14020. activeInfluenceIndices.sort( numericalSort );
  14021. } else if ( activeInfluenceIndices.length === 0 ) {
  14022. activeInfluenceIndices.push( [ 0, 0 ] );
  14023. };
  14024. var influenceIndex, m = 0;
  14025. while ( m < material.numSupportedMorphTargets ) {
  14026. if ( activeInfluenceIndices[ m ] ) {
  14027. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  14028. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  14029. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  14030. enableAttribute( attributes[ "morphTarget" + m ] );
  14031. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14032. }
  14033. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  14034. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  14035. enableAttribute( attributes[ "morphNormal" + m ] );
  14036. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14037. }
  14038. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  14039. } else {
  14040. /*
  14041. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14042. if ( material.morphNormals ) {
  14043. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14044. }
  14045. */
  14046. object.__webglMorphTargetInfluences[ m ] = 0;
  14047. }
  14048. m ++;
  14049. }
  14050. }
  14051. // load updated influences uniform
  14052. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  14053. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  14054. }
  14055. };
  14056. // Sorting
  14057. function painterSortStable ( a, b ) {
  14058. if ( a.z !== b.z ) {
  14059. return b.z - a.z;
  14060. } else {
  14061. return a.id - b.id;
  14062. }
  14063. };
  14064. function numericalSort ( a, b ) {
  14065. return b[ 0 ] - a[ 0 ];
  14066. };
  14067. // Rendering
  14068. this.render = function ( scene, camera, renderTarget, forceClear ) {
  14069. if ( camera instanceof THREE.Camera === false ) {
  14070. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  14071. return;
  14072. }
  14073. var i, il,
  14074. webglObject, object,
  14075. renderList,
  14076. lights = scene.__lights,
  14077. fog = scene.fog;
  14078. // reset caching for this frame
  14079. _currentMaterialId = -1;
  14080. _lightsNeedUpdate = true;
  14081. // update scene graph
  14082. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14083. // update camera matrices and frustum
  14084. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  14085. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  14086. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  14087. _frustum.setFromMatrix( _projScreenMatrix );
  14088. // update WebGL objects
  14089. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  14090. // custom render plugins (pre pass)
  14091. renderPlugins( this.renderPluginsPre, scene, camera );
  14092. //
  14093. _this.info.render.calls = 0;
  14094. _this.info.render.vertices = 0;
  14095. _this.info.render.faces = 0;
  14096. _this.info.render.points = 0;
  14097. this.setRenderTarget( renderTarget );
  14098. if ( this.autoClear || forceClear ) {
  14099. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  14100. }
  14101. // set matrices for regular objects (frustum culled)
  14102. renderList = scene.__webglObjects;
  14103. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14104. webglObject = renderList[ i ];
  14105. object = webglObject.object;
  14106. webglObject.id = i;
  14107. webglObject.render = false;
  14108. if ( object.visible ) {
  14109. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  14110. setupMatrices( object, camera );
  14111. unrollBufferMaterial( webglObject );
  14112. webglObject.render = true;
  14113. if ( this.sortObjects === true ) {
  14114. if ( object.renderDepth !== null ) {
  14115. webglObject.z = object.renderDepth;
  14116. } else {
  14117. _vector3.setFromMatrixPosition( object.matrixWorld );
  14118. _vector3.applyProjection( _projScreenMatrix );
  14119. webglObject.z = _vector3.z;
  14120. }
  14121. }
  14122. }
  14123. }
  14124. }
  14125. if ( this.sortObjects ) {
  14126. renderList.sort( painterSortStable );
  14127. }
  14128. // set matrices for immediate objects
  14129. renderList = scene.__webglObjectsImmediate;
  14130. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14131. webglObject = renderList[ i ];
  14132. object = webglObject.object;
  14133. if ( object.visible ) {
  14134. setupMatrices( object, camera );
  14135. unrollImmediateBufferMaterial( webglObject );
  14136. }
  14137. }
  14138. if ( scene.overrideMaterial ) {
  14139. var material = scene.overrideMaterial;
  14140. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14141. this.setDepthTest( material.depthTest );
  14142. this.setDepthWrite( material.depthWrite );
  14143. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14144. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  14145. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  14146. } else {
  14147. var material = null;
  14148. // opaque pass (front-to-back order)
  14149. this.setBlending( THREE.NoBlending );
  14150. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  14151. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  14152. // transparent pass (back-to-front order)
  14153. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  14154. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  14155. }
  14156. // custom render plugins (post pass)
  14157. renderPlugins( this.renderPluginsPost, scene, camera );
  14158. // Generate mipmap if we're using any kind of mipmap filtering
  14159. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  14160. updateRenderTargetMipmap( renderTarget );
  14161. }
  14162. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14163. this.setDepthTest( true );
  14164. this.setDepthWrite( true );
  14165. // _gl.finish();
  14166. };
  14167. function renderPlugins( plugins, scene, camera ) {
  14168. if ( ! plugins.length ) return;
  14169. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  14170. // reset state for plugin (to start from clean slate)
  14171. _currentProgram = null;
  14172. _currentCamera = null;
  14173. _oldBlending = -1;
  14174. _oldDepthTest = -1;
  14175. _oldDepthWrite = -1;
  14176. _oldDoubleSided = -1;
  14177. _oldFlipSided = -1;
  14178. _currentGeometryGroupHash = -1;
  14179. _currentMaterialId = -1;
  14180. _lightsNeedUpdate = true;
  14181. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  14182. // reset state after plugin (anything could have changed)
  14183. _currentProgram = null;
  14184. _currentCamera = null;
  14185. _oldBlending = -1;
  14186. _oldDepthTest = -1;
  14187. _oldDepthWrite = -1;
  14188. _oldDoubleSided = -1;
  14189. _oldFlipSided = -1;
  14190. _currentGeometryGroupHash = -1;
  14191. _currentMaterialId = -1;
  14192. _lightsNeedUpdate = true;
  14193. }
  14194. };
  14195. function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14196. var webglObject, object, buffer, material, start, end, delta;
  14197. if ( reverse ) {
  14198. start = renderList.length - 1;
  14199. end = -1;
  14200. delta = -1;
  14201. } else {
  14202. start = 0;
  14203. end = renderList.length;
  14204. delta = 1;
  14205. }
  14206. for ( var i = start; i !== end; i += delta ) {
  14207. webglObject = renderList[ i ];
  14208. if ( webglObject.render ) {
  14209. object = webglObject.object;
  14210. buffer = webglObject.buffer;
  14211. if ( overrideMaterial ) {
  14212. material = overrideMaterial;
  14213. } else {
  14214. material = webglObject[ materialType ];
  14215. if ( ! material ) continue;
  14216. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14217. _this.setDepthTest( material.depthTest );
  14218. _this.setDepthWrite( material.depthWrite );
  14219. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14220. }
  14221. _this.setMaterialFaces( material );
  14222. if ( buffer instanceof THREE.BufferGeometry ) {
  14223. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  14224. } else {
  14225. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  14226. }
  14227. }
  14228. }
  14229. };
  14230. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14231. var webglObject, object, material, program;
  14232. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  14233. webglObject = renderList[ i ];
  14234. object = webglObject.object;
  14235. if ( object.visible ) {
  14236. if ( overrideMaterial ) {
  14237. material = overrideMaterial;
  14238. } else {
  14239. material = webglObject[ materialType ];
  14240. if ( ! material ) continue;
  14241. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14242. _this.setDepthTest( material.depthTest );
  14243. _this.setDepthWrite( material.depthWrite );
  14244. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14245. }
  14246. _this.renderImmediateObject( camera, lights, fog, material, object );
  14247. }
  14248. }
  14249. };
  14250. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  14251. var program = setProgram( camera, lights, fog, material, object );
  14252. _currentGeometryGroupHash = -1;
  14253. _this.setMaterialFaces( material );
  14254. if ( object.immediateRenderCallback ) {
  14255. object.immediateRenderCallback( program, _gl, _frustum );
  14256. } else {
  14257. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  14258. }
  14259. };
  14260. function unrollImmediateBufferMaterial ( globject ) {
  14261. var object = globject.object,
  14262. material = object.material;
  14263. if ( material.transparent ) {
  14264. globject.transparent = material;
  14265. globject.opaque = null;
  14266. } else {
  14267. globject.opaque = material;
  14268. globject.transparent = null;
  14269. }
  14270. };
  14271. function unrollBufferMaterial ( globject ) {
  14272. var object = globject.object;
  14273. var buffer = globject.buffer;
  14274. var geometry = object.geometry;
  14275. var material = object.material;
  14276. if ( material instanceof THREE.MeshFaceMaterial ) {
  14277. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  14278. material = material.materials[ materialIndex ];
  14279. if ( material.transparent ) {
  14280. globject.transparent = material;
  14281. globject.opaque = null;
  14282. } else {
  14283. globject.opaque = material;
  14284. globject.transparent = null;
  14285. }
  14286. } else {
  14287. if ( material ) {
  14288. if ( material.transparent ) {
  14289. globject.transparent = material;
  14290. globject.opaque = null;
  14291. } else {
  14292. globject.opaque = material;
  14293. globject.transparent = null;
  14294. }
  14295. }
  14296. }
  14297. };
  14298. // Objects refresh
  14299. this.initWebGLObjects = function ( scene ) {
  14300. if ( !scene.__webglObjects ) {
  14301. scene.__webglObjects = [];
  14302. scene.__webglObjectsImmediate = [];
  14303. scene.__webglSprites = [];
  14304. scene.__webglFlares = [];
  14305. }
  14306. while ( scene.__objectsAdded.length ) {
  14307. addObject( scene.__objectsAdded[ 0 ], scene );
  14308. scene.__objectsAdded.splice( 0, 1 );
  14309. }
  14310. while ( scene.__objectsRemoved.length ) {
  14311. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14312. scene.__objectsRemoved.splice( 0, 1 );
  14313. }
  14314. // update must be called after objects adding / removal
  14315. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14316. var object = scene.__webglObjects[ o ].object;
  14317. // TODO: Remove this hack (WebGLRenderer refactoring)
  14318. if ( object.__webglInit === undefined ) {
  14319. if ( object.__webglActive !== undefined ) {
  14320. removeObject( object, scene );
  14321. }
  14322. addObject( object, scene );
  14323. }
  14324. updateObject( object );
  14325. }
  14326. };
  14327. // Objects adding
  14328. function addObject( object, scene ) {
  14329. var g, geometry, material, geometryGroup;
  14330. if ( object.__webglInit === undefined ) {
  14331. object.__webglInit = true;
  14332. object._modelViewMatrix = new THREE.Matrix4();
  14333. object._normalMatrix = new THREE.Matrix3();
  14334. geometry = object.geometry;
  14335. if ( geometry === undefined ) {
  14336. // ImmediateRenderObject
  14337. } else if ( geometry.__webglInit === undefined ) {
  14338. geometry.__webglInit = true;
  14339. geometry.addEventListener( 'dispose', onGeometryDispose );
  14340. if ( geometry instanceof THREE.BufferGeometry ) {
  14341. initDirectBuffers( geometry );
  14342. } else if ( object instanceof THREE.Mesh ) {
  14343. material = object.material;
  14344. if ( geometry.geometryGroups === undefined ) {
  14345. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 );
  14346. }
  14347. // create separate VBOs per geometry chunk
  14348. for ( g in geometry.geometryGroups ) {
  14349. geometryGroup = geometry.geometryGroups[ g ];
  14350. // initialise VBO on the first access
  14351. if ( ! geometryGroup.__webglVertexBuffer ) {
  14352. createMeshBuffers( geometryGroup );
  14353. initMeshBuffers( geometryGroup, object );
  14354. geometry.verticesNeedUpdate = true;
  14355. geometry.morphTargetsNeedUpdate = true;
  14356. geometry.elementsNeedUpdate = true;
  14357. geometry.uvsNeedUpdate = true;
  14358. geometry.normalsNeedUpdate = true;
  14359. geometry.tangentsNeedUpdate = true;
  14360. geometry.colorsNeedUpdate = true;
  14361. }
  14362. }
  14363. } else if ( object instanceof THREE.Line ) {
  14364. if ( ! geometry.__webglVertexBuffer ) {
  14365. createLineBuffers( geometry );
  14366. initLineBuffers( geometry, object );
  14367. geometry.verticesNeedUpdate = true;
  14368. geometry.colorsNeedUpdate = true;
  14369. geometry.lineDistancesNeedUpdate = true;
  14370. }
  14371. } else if ( object instanceof THREE.ParticleSystem ) {
  14372. if ( ! geometry.__webglVertexBuffer ) {
  14373. createParticleBuffers( geometry );
  14374. initParticleBuffers( geometry, object );
  14375. geometry.verticesNeedUpdate = true;
  14376. geometry.colorsNeedUpdate = true;
  14377. }
  14378. }
  14379. }
  14380. }
  14381. if ( object.__webglActive === undefined ) {
  14382. if ( object instanceof THREE.Mesh ) {
  14383. geometry = object.geometry;
  14384. if ( geometry instanceof THREE.BufferGeometry ) {
  14385. addBuffer( scene.__webglObjects, geometry, object );
  14386. } else if ( geometry instanceof THREE.Geometry ) {
  14387. for ( g in geometry.geometryGroups ) {
  14388. geometryGroup = geometry.geometryGroups[ g ];
  14389. addBuffer( scene.__webglObjects, geometryGroup, object );
  14390. }
  14391. }
  14392. } else if ( object instanceof THREE.Line ||
  14393. object instanceof THREE.ParticleSystem ) {
  14394. geometry = object.geometry;
  14395. addBuffer( scene.__webglObjects, geometry, object );
  14396. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14397. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14398. } else if ( object instanceof THREE.Sprite ) {
  14399. scene.__webglSprites.push( object );
  14400. } else if ( object instanceof THREE.LensFlare ) {
  14401. scene.__webglFlares.push( object );
  14402. }
  14403. object.__webglActive = true;
  14404. }
  14405. };
  14406. function addBuffer( objlist, buffer, object ) {
  14407. objlist.push(
  14408. {
  14409. id: null,
  14410. buffer: buffer,
  14411. object: object,
  14412. opaque: null,
  14413. transparent: null,
  14414. z: 0
  14415. }
  14416. );
  14417. };
  14418. function addBufferImmediate( objlist, object ) {
  14419. objlist.push(
  14420. {
  14421. id: null,
  14422. object: object,
  14423. opaque: null,
  14424. transparent: null,
  14425. z: 0
  14426. }
  14427. );
  14428. };
  14429. // Objects updates
  14430. function updateObject( object ) {
  14431. var geometry = object.geometry,
  14432. geometryGroup, customAttributesDirty, material;
  14433. if ( geometry instanceof THREE.BufferGeometry ) {
  14434. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  14435. } else if ( object instanceof THREE.Mesh ) {
  14436. // check all geometry groups
  14437. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14438. geometryGroup = geometry.geometryGroupsList[ i ];
  14439. material = getBufferMaterial( object, geometryGroup );
  14440. if ( geometry.buffersNeedUpdate ) {
  14441. initMeshBuffers( geometryGroup, object );
  14442. }
  14443. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14444. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14445. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14446. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14447. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14448. }
  14449. }
  14450. geometry.verticesNeedUpdate = false;
  14451. geometry.morphTargetsNeedUpdate = false;
  14452. geometry.elementsNeedUpdate = false;
  14453. geometry.uvsNeedUpdate = false;
  14454. geometry.normalsNeedUpdate = false;
  14455. geometry.colorsNeedUpdate = false;
  14456. geometry.tangentsNeedUpdate = false;
  14457. geometry.buffersNeedUpdate = false;
  14458. material.attributes && clearCustomAttributes( material );
  14459. } else if ( object instanceof THREE.Line ) {
  14460. material = getBufferMaterial( object, geometry );
  14461. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14462. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14463. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14464. }
  14465. geometry.verticesNeedUpdate = false;
  14466. geometry.colorsNeedUpdate = false;
  14467. geometry.lineDistancesNeedUpdate = false;
  14468. material.attributes && clearCustomAttributes( material );
  14469. } else if ( object instanceof THREE.ParticleSystem ) {
  14470. material = getBufferMaterial( object, geometry );
  14471. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14472. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14473. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14474. }
  14475. geometry.verticesNeedUpdate = false;
  14476. geometry.colorsNeedUpdate = false;
  14477. material.attributes && clearCustomAttributes( material );
  14478. }
  14479. };
  14480. // Objects updates - custom attributes check
  14481. function areCustomAttributesDirty( material ) {
  14482. for ( var a in material.attributes ) {
  14483. if ( material.attributes[ a ].needsUpdate ) return true;
  14484. }
  14485. return false;
  14486. };
  14487. function clearCustomAttributes( material ) {
  14488. for ( var a in material.attributes ) {
  14489. material.attributes[ a ].needsUpdate = false;
  14490. }
  14491. };
  14492. // Objects removal
  14493. function removeObject( object, scene ) {
  14494. if ( object instanceof THREE.Mesh ||
  14495. object instanceof THREE.ParticleSystem ||
  14496. object instanceof THREE.Line ) {
  14497. removeInstances( scene.__webglObjects, object );
  14498. } else if ( object instanceof THREE.Sprite ) {
  14499. removeInstancesDirect( scene.__webglSprites, object );
  14500. } else if ( object instanceof THREE.LensFlare ) {
  14501. removeInstancesDirect( scene.__webglFlares, object );
  14502. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14503. removeInstances( scene.__webglObjectsImmediate, object );
  14504. }
  14505. delete object.__webglActive;
  14506. };
  14507. function removeInstances( objlist, object ) {
  14508. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14509. if ( objlist[ o ].object === object ) {
  14510. objlist.splice( o, 1 );
  14511. }
  14512. }
  14513. };
  14514. function removeInstancesDirect( objlist, object ) {
  14515. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14516. if ( objlist[ o ] === object ) {
  14517. objlist.splice( o, 1 );
  14518. }
  14519. }
  14520. };
  14521. // Materials
  14522. this.initMaterial = function ( material, lights, fog, object ) {
  14523. material.addEventListener( 'dispose', onMaterialDispose );
  14524. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14525. if ( material instanceof THREE.MeshDepthMaterial ) {
  14526. shaderID = 'depth';
  14527. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14528. shaderID = 'normal';
  14529. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14530. shaderID = 'basic';
  14531. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14532. shaderID = 'lambert';
  14533. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14534. shaderID = 'phong';
  14535. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14536. shaderID = 'basic';
  14537. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14538. shaderID = 'dashed';
  14539. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14540. shaderID = 'particle_basic';
  14541. }
  14542. if ( shaderID ) {
  14543. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14544. }
  14545. // heuristics to create shader parameters according to lights in the scene
  14546. // (not to blow over maxLights budget)
  14547. maxLightCount = allocateLights( lights );
  14548. maxShadows = allocateShadows( lights );
  14549. maxBones = allocateBones( object );
  14550. parameters = {
  14551. precision: _precision,
  14552. supportsVertexTextures: _supportsVertexTextures,
  14553. map: !!material.map,
  14554. envMap: !!material.envMap,
  14555. lightMap: !!material.lightMap,
  14556. bumpMap: !!material.bumpMap,
  14557. normalMap: !!material.normalMap,
  14558. specularMap: !!material.specularMap,
  14559. vertexColors: material.vertexColors,
  14560. fog: fog,
  14561. useFog: material.fog,
  14562. fogExp: fog instanceof THREE.FogExp2,
  14563. sizeAttenuation: material.sizeAttenuation,
  14564. skinning: material.skinning,
  14565. maxBones: maxBones,
  14566. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14567. morphTargets: material.morphTargets,
  14568. morphNormals: material.morphNormals,
  14569. maxMorphTargets: this.maxMorphTargets,
  14570. maxMorphNormals: this.maxMorphNormals,
  14571. maxDirLights: maxLightCount.directional,
  14572. maxPointLights: maxLightCount.point,
  14573. maxSpotLights: maxLightCount.spot,
  14574. maxHemiLights: maxLightCount.hemi,
  14575. maxShadows: maxShadows,
  14576. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  14577. shadowMapType: this.shadowMapType,
  14578. shadowMapDebug: this.shadowMapDebug,
  14579. shadowMapCascade: this.shadowMapCascade,
  14580. alphaTest: material.alphaTest,
  14581. metal: material.metal,
  14582. wrapAround: material.wrapAround,
  14583. doubleSided: material.side === THREE.DoubleSide,
  14584. flipSided: material.side === THREE.BackSide
  14585. };
  14586. // Generate code
  14587. var chunks = [];
  14588. if ( shaderID ) {
  14589. chunks.push( shaderID );
  14590. } else {
  14591. chunks.push( material.fragmentShader );
  14592. chunks.push( material.vertexShader );
  14593. }
  14594. for ( var d in material.defines ) {
  14595. chunks.push( d );
  14596. chunks.push( material.defines[ d ] );
  14597. }
  14598. for ( var p in parameters ) {
  14599. chunks.push( p );
  14600. chunks.push( parameters[ p ] );
  14601. }
  14602. var code = chunks.join();
  14603. var program;
  14604. // Check if code has been already compiled
  14605. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  14606. var programInfo = _programs[ p ];
  14607. if ( programInfo.code === code ) {
  14608. program = programInfo;
  14609. program.usedTimes ++;
  14610. break;
  14611. }
  14612. }
  14613. if ( program === undefined ) {
  14614. program = new THREE.WebGLProgram( this, code, material, parameters );
  14615. _programs.push( program );
  14616. _this.info.memory.programs = _programs.length;
  14617. }
  14618. material.program = program;
  14619. var attributes = material.program.attributes;
  14620. if ( material.morphTargets ) {
  14621. material.numSupportedMorphTargets = 0;
  14622. var id, base = "morphTarget";
  14623. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14624. id = base + i;
  14625. if ( attributes[ id ] >= 0 ) {
  14626. material.numSupportedMorphTargets ++;
  14627. }
  14628. }
  14629. }
  14630. if ( material.morphNormals ) {
  14631. material.numSupportedMorphNormals = 0;
  14632. var id, base = "morphNormal";
  14633. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14634. id = base + i;
  14635. if ( attributes[ id ] >= 0 ) {
  14636. material.numSupportedMorphNormals ++;
  14637. }
  14638. }
  14639. }
  14640. material.uniformsList = [];
  14641. for ( u in material.uniforms ) {
  14642. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14643. }
  14644. };
  14645. function setMaterialShaders( material, shaders ) {
  14646. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14647. material.vertexShader = shaders.vertexShader;
  14648. material.fragmentShader = shaders.fragmentShader;
  14649. };
  14650. function setProgram( camera, lights, fog, material, object ) {
  14651. _usedTextureUnits = 0;
  14652. if ( material.needsUpdate ) {
  14653. if ( material.program ) deallocateMaterial( material );
  14654. _this.initMaterial( material, lights, fog, object );
  14655. material.needsUpdate = false;
  14656. }
  14657. if ( material.morphTargets ) {
  14658. if ( ! object.__webglMorphTargetInfluences ) {
  14659. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14660. }
  14661. }
  14662. var refreshMaterial = false;
  14663. var program = material.program,
  14664. p_uniforms = program.uniforms,
  14665. m_uniforms = material.uniforms;
  14666. if ( program.id !== _currentProgram ) {
  14667. _gl.useProgram( program.program );
  14668. _currentProgram = program.id;
  14669. refreshMaterial = true;
  14670. }
  14671. if ( material.id !== _currentMaterialId ) {
  14672. _currentMaterialId = material.id;
  14673. refreshMaterial = true;
  14674. }
  14675. if ( refreshMaterial || camera !== _currentCamera ) {
  14676. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14677. if ( camera !== _currentCamera ) _currentCamera = camera;
  14678. }
  14679. // skinning uniforms must be set even if material didn't change
  14680. // auto-setting of texture unit for bone texture must go before other textures
  14681. // not sure why, but otherwise weird things happen
  14682. if ( material.skinning ) {
  14683. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14684. if ( p_uniforms.boneTexture !== null ) {
  14685. var textureUnit = getTextureUnit();
  14686. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14687. _this.setTexture( object.boneTexture, textureUnit );
  14688. }
  14689. if ( p_uniforms.boneTextureWidth !== null ) {
  14690. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14691. }
  14692. if ( p_uniforms.boneTextureHeight !== null ) {
  14693. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14694. }
  14695. } else {
  14696. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14697. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14698. }
  14699. }
  14700. }
  14701. if ( refreshMaterial ) {
  14702. // refresh uniforms common to several materials
  14703. if ( fog && material.fog ) {
  14704. refreshUniformsFog( m_uniforms, fog );
  14705. }
  14706. if ( material instanceof THREE.MeshPhongMaterial ||
  14707. material instanceof THREE.MeshLambertMaterial ||
  14708. material.lights ) {
  14709. if ( _lightsNeedUpdate ) {
  14710. setupLights( program, lights );
  14711. _lightsNeedUpdate = false;
  14712. }
  14713. refreshUniformsLights( m_uniforms, _lights );
  14714. }
  14715. if ( material instanceof THREE.MeshBasicMaterial ||
  14716. material instanceof THREE.MeshLambertMaterial ||
  14717. material instanceof THREE.MeshPhongMaterial ) {
  14718. refreshUniformsCommon( m_uniforms, material );
  14719. }
  14720. // refresh single material specific uniforms
  14721. if ( material instanceof THREE.LineBasicMaterial ) {
  14722. refreshUniformsLine( m_uniforms, material );
  14723. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14724. refreshUniformsLine( m_uniforms, material );
  14725. refreshUniformsDash( m_uniforms, material );
  14726. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14727. refreshUniformsParticle( m_uniforms, material );
  14728. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14729. refreshUniformsPhong( m_uniforms, material );
  14730. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14731. refreshUniformsLambert( m_uniforms, material );
  14732. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14733. m_uniforms.mNear.value = camera.near;
  14734. m_uniforms.mFar.value = camera.far;
  14735. m_uniforms.opacity.value = material.opacity;
  14736. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14737. m_uniforms.opacity.value = material.opacity;
  14738. }
  14739. if ( object.receiveShadow && ! material._shadowPass ) {
  14740. refreshUniformsShadow( m_uniforms, lights );
  14741. }
  14742. // load common uniforms
  14743. loadUniformsGeneric( program, material.uniformsList );
  14744. // load material specific uniforms
  14745. // (shader material also gets them for the sake of genericity)
  14746. if ( material instanceof THREE.ShaderMaterial ||
  14747. material instanceof THREE.MeshPhongMaterial ||
  14748. material.envMap ) {
  14749. if ( p_uniforms.cameraPosition !== null ) {
  14750. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14751. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14752. }
  14753. }
  14754. if ( material instanceof THREE.MeshPhongMaterial ||
  14755. material instanceof THREE.MeshLambertMaterial ||
  14756. material instanceof THREE.ShaderMaterial ||
  14757. material.skinning ) {
  14758. if ( p_uniforms.viewMatrix !== null ) {
  14759. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14760. }
  14761. }
  14762. }
  14763. loadUniformsMatrices( p_uniforms, object );
  14764. if ( p_uniforms.modelMatrix !== null ) {
  14765. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14766. }
  14767. return program;
  14768. };
  14769. // Uniforms (refresh uniforms objects)
  14770. function refreshUniformsCommon ( uniforms, material ) {
  14771. uniforms.opacity.value = material.opacity;
  14772. if ( _this.gammaInput ) {
  14773. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14774. } else {
  14775. uniforms.diffuse.value = material.color;
  14776. }
  14777. uniforms.map.value = material.map;
  14778. uniforms.lightMap.value = material.lightMap;
  14779. uniforms.specularMap.value = material.specularMap;
  14780. if ( material.bumpMap ) {
  14781. uniforms.bumpMap.value = material.bumpMap;
  14782. uniforms.bumpScale.value = material.bumpScale;
  14783. }
  14784. if ( material.normalMap ) {
  14785. uniforms.normalMap.value = material.normalMap;
  14786. uniforms.normalScale.value.copy( material.normalScale );
  14787. }
  14788. // uv repeat and offset setting priorities
  14789. // 1. color map
  14790. // 2. specular map
  14791. // 3. normal map
  14792. // 4. bump map
  14793. var uvScaleMap;
  14794. if ( material.map ) {
  14795. uvScaleMap = material.map;
  14796. } else if ( material.specularMap ) {
  14797. uvScaleMap = material.specularMap;
  14798. } else if ( material.normalMap ) {
  14799. uvScaleMap = material.normalMap;
  14800. } else if ( material.bumpMap ) {
  14801. uvScaleMap = material.bumpMap;
  14802. }
  14803. if ( uvScaleMap !== undefined ) {
  14804. var offset = uvScaleMap.offset;
  14805. var repeat = uvScaleMap.repeat;
  14806. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14807. }
  14808. uniforms.envMap.value = material.envMap;
  14809. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14810. if ( _this.gammaInput ) {
  14811. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14812. uniforms.reflectivity.value = material.reflectivity;
  14813. } else {
  14814. uniforms.reflectivity.value = material.reflectivity;
  14815. }
  14816. uniforms.refractionRatio.value = material.refractionRatio;
  14817. uniforms.combine.value = material.combine;
  14818. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14819. };
  14820. function refreshUniformsLine ( uniforms, material ) {
  14821. uniforms.diffuse.value = material.color;
  14822. uniforms.opacity.value = material.opacity;
  14823. };
  14824. function refreshUniformsDash ( uniforms, material ) {
  14825. uniforms.dashSize.value = material.dashSize;
  14826. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14827. uniforms.scale.value = material.scale;
  14828. };
  14829. function refreshUniformsParticle ( uniforms, material ) {
  14830. uniforms.psColor.value = material.color;
  14831. uniforms.opacity.value = material.opacity;
  14832. uniforms.size.value = material.size;
  14833. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14834. uniforms.map.value = material.map;
  14835. };
  14836. function refreshUniformsFog ( uniforms, fog ) {
  14837. uniforms.fogColor.value = fog.color;
  14838. if ( fog instanceof THREE.Fog ) {
  14839. uniforms.fogNear.value = fog.near;
  14840. uniforms.fogFar.value = fog.far;
  14841. } else if ( fog instanceof THREE.FogExp2 ) {
  14842. uniforms.fogDensity.value = fog.density;
  14843. }
  14844. };
  14845. function refreshUniformsPhong ( uniforms, material ) {
  14846. uniforms.shininess.value = material.shininess;
  14847. if ( _this.gammaInput ) {
  14848. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14849. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14850. uniforms.specular.value.copyGammaToLinear( material.specular );
  14851. } else {
  14852. uniforms.ambient.value = material.ambient;
  14853. uniforms.emissive.value = material.emissive;
  14854. uniforms.specular.value = material.specular;
  14855. }
  14856. if ( material.wrapAround ) {
  14857. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14858. }
  14859. };
  14860. function refreshUniformsLambert ( uniforms, material ) {
  14861. if ( _this.gammaInput ) {
  14862. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14863. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14864. } else {
  14865. uniforms.ambient.value = material.ambient;
  14866. uniforms.emissive.value = material.emissive;
  14867. }
  14868. if ( material.wrapAround ) {
  14869. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14870. }
  14871. };
  14872. function refreshUniformsLights ( uniforms, lights ) {
  14873. uniforms.ambientLightColor.value = lights.ambient;
  14874. uniforms.directionalLightColor.value = lights.directional.colors;
  14875. uniforms.directionalLightDirection.value = lights.directional.positions;
  14876. uniforms.pointLightColor.value = lights.point.colors;
  14877. uniforms.pointLightPosition.value = lights.point.positions;
  14878. uniforms.pointLightDistance.value = lights.point.distances;
  14879. uniforms.spotLightColor.value = lights.spot.colors;
  14880. uniforms.spotLightPosition.value = lights.spot.positions;
  14881. uniforms.spotLightDistance.value = lights.spot.distances;
  14882. uniforms.spotLightDirection.value = lights.spot.directions;
  14883. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14884. uniforms.spotLightExponent.value = lights.spot.exponents;
  14885. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14886. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14887. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14888. };
  14889. function refreshUniformsShadow ( uniforms, lights ) {
  14890. if ( uniforms.shadowMatrix ) {
  14891. var j = 0;
  14892. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14893. var light = lights[ i ];
  14894. if ( ! light.castShadow ) continue;
  14895. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14896. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14897. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14898. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14899. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14900. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14901. j ++;
  14902. }
  14903. }
  14904. }
  14905. };
  14906. // Uniforms (load to GPU)
  14907. function loadUniformsMatrices ( uniforms, object ) {
  14908. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14909. if ( uniforms.normalMatrix ) {
  14910. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14911. }
  14912. };
  14913. function getTextureUnit() {
  14914. var textureUnit = _usedTextureUnits;
  14915. if ( textureUnit >= _maxTextures ) {
  14916. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14917. }
  14918. _usedTextureUnits += 1;
  14919. return textureUnit;
  14920. };
  14921. function loadUniformsGeneric ( program, uniforms ) {
  14922. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14923. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14924. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14925. if ( !location ) continue;
  14926. uniform = uniforms[ j ][ 0 ];
  14927. type = uniform.type;
  14928. value = uniform.value;
  14929. if ( type === "i" ) { // single integer
  14930. _gl.uniform1i( location, value );
  14931. } else if ( type === "f" ) { // single float
  14932. _gl.uniform1f( location, value );
  14933. } else if ( type === "v2" ) { // single THREE.Vector2
  14934. _gl.uniform2f( location, value.x, value.y );
  14935. } else if ( type === "v3" ) { // single THREE.Vector3
  14936. _gl.uniform3f( location, value.x, value.y, value.z );
  14937. } else if ( type === "v4" ) { // single THREE.Vector4
  14938. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14939. } else if ( type === "c" ) { // single THREE.Color
  14940. _gl.uniform3f( location, value.r, value.g, value.b );
  14941. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14942. _gl.uniform1iv( location, value );
  14943. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14944. _gl.uniform3iv( location, value );
  14945. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14946. _gl.uniform1fv( location, value );
  14947. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14948. _gl.uniform3fv( location, value );
  14949. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14950. if ( uniform._array === undefined ) {
  14951. uniform._array = new Float32Array( 2 * value.length );
  14952. }
  14953. for ( i = 0, il = value.length; i < il; i ++ ) {
  14954. offset = i * 2;
  14955. uniform._array[ offset ] = value[ i ].x;
  14956. uniform._array[ offset + 1 ] = value[ i ].y;
  14957. }
  14958. _gl.uniform2fv( location, uniform._array );
  14959. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14960. if ( uniform._array === undefined ) {
  14961. uniform._array = new Float32Array( 3 * value.length );
  14962. }
  14963. for ( i = 0, il = value.length; i < il; i ++ ) {
  14964. offset = i * 3;
  14965. uniform._array[ offset ] = value[ i ].x;
  14966. uniform._array[ offset + 1 ] = value[ i ].y;
  14967. uniform._array[ offset + 2 ] = value[ i ].z;
  14968. }
  14969. _gl.uniform3fv( location, uniform._array );
  14970. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14971. if ( uniform._array === undefined ) {
  14972. uniform._array = new Float32Array( 4 * value.length );
  14973. }
  14974. for ( i = 0, il = value.length; i < il; i ++ ) {
  14975. offset = i * 4;
  14976. uniform._array[ offset ] = value[ i ].x;
  14977. uniform._array[ offset + 1 ] = value[ i ].y;
  14978. uniform._array[ offset + 2 ] = value[ i ].z;
  14979. uniform._array[ offset + 3 ] = value[ i ].w;
  14980. }
  14981. _gl.uniform4fv( location, uniform._array );
  14982. } else if ( type === "m4") { // single THREE.Matrix4
  14983. if ( uniform._array === undefined ) {
  14984. uniform._array = new Float32Array( 16 );
  14985. }
  14986. value.flattenToArray( uniform._array );
  14987. _gl.uniformMatrix4fv( location, false, uniform._array );
  14988. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14989. if ( uniform._array === undefined ) {
  14990. uniform._array = new Float32Array( 16 * value.length );
  14991. }
  14992. for ( i = 0, il = value.length; i < il; i ++ ) {
  14993. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14994. }
  14995. _gl.uniformMatrix4fv( location, false, uniform._array );
  14996. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14997. texture = value;
  14998. textureUnit = getTextureUnit();
  14999. _gl.uniform1i( location, textureUnit );
  15000. if ( !texture ) continue;
  15001. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  15002. setCubeTexture( texture, textureUnit );
  15003. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  15004. setCubeTextureDynamic( texture, textureUnit );
  15005. } else {
  15006. _this.setTexture( texture, textureUnit );
  15007. }
  15008. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  15009. if ( uniform._array === undefined ) {
  15010. uniform._array = [];
  15011. }
  15012. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  15013. uniform._array[ i ] = getTextureUnit();
  15014. }
  15015. _gl.uniform1iv( location, uniform._array );
  15016. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  15017. texture = uniform.value[ i ];
  15018. textureUnit = uniform._array[ i ];
  15019. if ( !texture ) continue;
  15020. _this.setTexture( texture, textureUnit );
  15021. }
  15022. } else {
  15023. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  15024. }
  15025. }
  15026. };
  15027. function setupMatrices ( object, camera ) {
  15028. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15029. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  15030. };
  15031. //
  15032. function setColorGamma( array, offset, color, intensitySq ) {
  15033. array[ offset ] = color.r * color.r * intensitySq;
  15034. array[ offset + 1 ] = color.g * color.g * intensitySq;
  15035. array[ offset + 2 ] = color.b * color.b * intensitySq;
  15036. };
  15037. function setColorLinear( array, offset, color, intensity ) {
  15038. array[ offset ] = color.r * intensity;
  15039. array[ offset + 1 ] = color.g * intensity;
  15040. array[ offset + 2 ] = color.b * intensity;
  15041. };
  15042. function setupLights ( program, lights ) {
  15043. var l, ll, light, n,
  15044. r = 0, g = 0, b = 0,
  15045. color, skyColor, groundColor,
  15046. intensity, intensitySq,
  15047. position,
  15048. distance,
  15049. zlights = _lights,
  15050. dirColors = zlights.directional.colors,
  15051. dirPositions = zlights.directional.positions,
  15052. pointColors = zlights.point.colors,
  15053. pointPositions = zlights.point.positions,
  15054. pointDistances = zlights.point.distances,
  15055. spotColors = zlights.spot.colors,
  15056. spotPositions = zlights.spot.positions,
  15057. spotDistances = zlights.spot.distances,
  15058. spotDirections = zlights.spot.directions,
  15059. spotAnglesCos = zlights.spot.anglesCos,
  15060. spotExponents = zlights.spot.exponents,
  15061. hemiSkyColors = zlights.hemi.skyColors,
  15062. hemiGroundColors = zlights.hemi.groundColors,
  15063. hemiPositions = zlights.hemi.positions,
  15064. dirLength = 0,
  15065. pointLength = 0,
  15066. spotLength = 0,
  15067. hemiLength = 0,
  15068. dirCount = 0,
  15069. pointCount = 0,
  15070. spotCount = 0,
  15071. hemiCount = 0,
  15072. dirOffset = 0,
  15073. pointOffset = 0,
  15074. spotOffset = 0,
  15075. hemiOffset = 0;
  15076. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15077. light = lights[ l ];
  15078. if ( light.onlyShadow ) continue;
  15079. color = light.color;
  15080. intensity = light.intensity;
  15081. distance = light.distance;
  15082. if ( light instanceof THREE.AmbientLight ) {
  15083. if ( ! light.visible ) continue;
  15084. if ( _this.gammaInput ) {
  15085. r += color.r * color.r;
  15086. g += color.g * color.g;
  15087. b += color.b * color.b;
  15088. } else {
  15089. r += color.r;
  15090. g += color.g;
  15091. b += color.b;
  15092. }
  15093. } else if ( light instanceof THREE.DirectionalLight ) {
  15094. dirCount += 1;
  15095. if ( ! light.visible ) continue;
  15096. _direction.setFromMatrixPosition( light.matrixWorld );
  15097. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15098. _direction.sub( _vector3 );
  15099. _direction.normalize();
  15100. // skip lights with undefined direction
  15101. // these create troubles in OpenGL (making pixel black)
  15102. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15103. dirOffset = dirLength * 3;
  15104. dirPositions[ dirOffset ] = _direction.x;
  15105. dirPositions[ dirOffset + 1 ] = _direction.y;
  15106. dirPositions[ dirOffset + 2 ] = _direction.z;
  15107. if ( _this.gammaInput ) {
  15108. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  15109. } else {
  15110. setColorLinear( dirColors, dirOffset, color, intensity );
  15111. }
  15112. dirLength += 1;
  15113. } else if ( light instanceof THREE.PointLight ) {
  15114. pointCount += 1;
  15115. if ( ! light.visible ) continue;
  15116. pointOffset = pointLength * 3;
  15117. if ( _this.gammaInput ) {
  15118. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  15119. } else {
  15120. setColorLinear( pointColors, pointOffset, color, intensity );
  15121. }
  15122. _vector3.setFromMatrixPosition( light.matrixWorld );
  15123. pointPositions[ pointOffset ] = _vector3.x;
  15124. pointPositions[ pointOffset + 1 ] = _vector3.y;
  15125. pointPositions[ pointOffset + 2 ] = _vector3.z;
  15126. pointDistances[ pointLength ] = distance;
  15127. pointLength += 1;
  15128. } else if ( light instanceof THREE.SpotLight ) {
  15129. spotCount += 1;
  15130. if ( ! light.visible ) continue;
  15131. spotOffset = spotLength * 3;
  15132. if ( _this.gammaInput ) {
  15133. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  15134. } else {
  15135. setColorLinear( spotColors, spotOffset, color, intensity );
  15136. }
  15137. _vector3.setFromMatrixPosition( light.matrixWorld );
  15138. spotPositions[ spotOffset ] = _vector3.x;
  15139. spotPositions[ spotOffset + 1 ] = _vector3.y;
  15140. spotPositions[ spotOffset + 2 ] = _vector3.z;
  15141. spotDistances[ spotLength ] = distance;
  15142. _direction.copy( _vector3 );
  15143. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15144. _direction.sub( _vector3 );
  15145. _direction.normalize();
  15146. spotDirections[ spotOffset ] = _direction.x;
  15147. spotDirections[ spotOffset + 1 ] = _direction.y;
  15148. spotDirections[ spotOffset + 2 ] = _direction.z;
  15149. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  15150. spotExponents[ spotLength ] = light.exponent;
  15151. spotLength += 1;
  15152. } else if ( light instanceof THREE.HemisphereLight ) {
  15153. hemiCount += 1;
  15154. if ( ! light.visible ) continue;
  15155. _direction.setFromMatrixPosition( light.matrixWorld );
  15156. _direction.normalize();
  15157. // skip lights with undefined direction
  15158. // these create troubles in OpenGL (making pixel black)
  15159. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15160. hemiOffset = hemiLength * 3;
  15161. hemiPositions[ hemiOffset ] = _direction.x;
  15162. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  15163. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  15164. skyColor = light.color;
  15165. groundColor = light.groundColor;
  15166. if ( _this.gammaInput ) {
  15167. intensitySq = intensity * intensity;
  15168. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  15169. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  15170. } else {
  15171. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  15172. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  15173. }
  15174. hemiLength += 1;
  15175. }
  15176. }
  15177. // null eventual remains from removed lights
  15178. // (this is to avoid if in shader)
  15179. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  15180. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  15181. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  15182. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  15183. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  15184. zlights.directional.length = dirLength;
  15185. zlights.point.length = pointLength;
  15186. zlights.spot.length = spotLength;
  15187. zlights.hemi.length = hemiLength;
  15188. zlights.ambient[ 0 ] = r;
  15189. zlights.ambient[ 1 ] = g;
  15190. zlights.ambient[ 2 ] = b;
  15191. };
  15192. // GL state setting
  15193. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15194. if ( cullFace === THREE.CullFaceNone ) {
  15195. _gl.disable( _gl.CULL_FACE );
  15196. } else {
  15197. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  15198. _gl.frontFace( _gl.CW );
  15199. } else {
  15200. _gl.frontFace( _gl.CCW );
  15201. }
  15202. if ( cullFace === THREE.CullFaceBack ) {
  15203. _gl.cullFace( _gl.BACK );
  15204. } else if ( cullFace === THREE.CullFaceFront ) {
  15205. _gl.cullFace( _gl.FRONT );
  15206. } else {
  15207. _gl.cullFace( _gl.FRONT_AND_BACK );
  15208. }
  15209. _gl.enable( _gl.CULL_FACE );
  15210. }
  15211. };
  15212. this.setMaterialFaces = function ( material ) {
  15213. var doubleSided = material.side === THREE.DoubleSide;
  15214. var flipSided = material.side === THREE.BackSide;
  15215. if ( _oldDoubleSided !== doubleSided ) {
  15216. if ( doubleSided ) {
  15217. _gl.disable( _gl.CULL_FACE );
  15218. } else {
  15219. _gl.enable( _gl.CULL_FACE );
  15220. }
  15221. _oldDoubleSided = doubleSided;
  15222. }
  15223. if ( _oldFlipSided !== flipSided ) {
  15224. if ( flipSided ) {
  15225. _gl.frontFace( _gl.CW );
  15226. } else {
  15227. _gl.frontFace( _gl.CCW );
  15228. }
  15229. _oldFlipSided = flipSided;
  15230. }
  15231. };
  15232. this.setDepthTest = function ( depthTest ) {
  15233. if ( _oldDepthTest !== depthTest ) {
  15234. if ( depthTest ) {
  15235. _gl.enable( _gl.DEPTH_TEST );
  15236. } else {
  15237. _gl.disable( _gl.DEPTH_TEST );
  15238. }
  15239. _oldDepthTest = depthTest;
  15240. }
  15241. };
  15242. this.setDepthWrite = function ( depthWrite ) {
  15243. if ( _oldDepthWrite !== depthWrite ) {
  15244. _gl.depthMask( depthWrite );
  15245. _oldDepthWrite = depthWrite;
  15246. }
  15247. };
  15248. function setLineWidth ( width ) {
  15249. if ( width !== _oldLineWidth ) {
  15250. _gl.lineWidth( width );
  15251. _oldLineWidth = width;
  15252. }
  15253. };
  15254. function setPolygonOffset ( polygonoffset, factor, units ) {
  15255. if ( _oldPolygonOffset !== polygonoffset ) {
  15256. if ( polygonoffset ) {
  15257. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15258. } else {
  15259. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15260. }
  15261. _oldPolygonOffset = polygonoffset;
  15262. }
  15263. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15264. _gl.polygonOffset( factor, units );
  15265. _oldPolygonOffsetFactor = factor;
  15266. _oldPolygonOffsetUnits = units;
  15267. }
  15268. };
  15269. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15270. if ( blending !== _oldBlending ) {
  15271. if ( blending === THREE.NoBlending ) {
  15272. _gl.disable( _gl.BLEND );
  15273. } else if ( blending === THREE.AdditiveBlending ) {
  15274. _gl.enable( _gl.BLEND );
  15275. _gl.blendEquation( _gl.FUNC_ADD );
  15276. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15277. } else if ( blending === THREE.SubtractiveBlending ) {
  15278. // TODO: Find blendFuncSeparate() combination
  15279. _gl.enable( _gl.BLEND );
  15280. _gl.blendEquation( _gl.FUNC_ADD );
  15281. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15282. } else if ( blending === THREE.MultiplyBlending ) {
  15283. // TODO: Find blendFuncSeparate() combination
  15284. _gl.enable( _gl.BLEND );
  15285. _gl.blendEquation( _gl.FUNC_ADD );
  15286. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15287. } else if ( blending === THREE.CustomBlending ) {
  15288. _gl.enable( _gl.BLEND );
  15289. } else {
  15290. _gl.enable( _gl.BLEND );
  15291. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15292. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15293. }
  15294. _oldBlending = blending;
  15295. }
  15296. if ( blending === THREE.CustomBlending ) {
  15297. if ( blendEquation !== _oldBlendEquation ) {
  15298. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15299. _oldBlendEquation = blendEquation;
  15300. }
  15301. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15302. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15303. _oldBlendSrc = blendSrc;
  15304. _oldBlendDst = blendDst;
  15305. }
  15306. } else {
  15307. _oldBlendEquation = null;
  15308. _oldBlendSrc = null;
  15309. _oldBlendDst = null;
  15310. }
  15311. };
  15312. // Textures
  15313. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15314. if ( isImagePowerOfTwo ) {
  15315. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15316. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15317. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15318. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15319. } else {
  15320. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15321. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15322. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15323. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15324. }
  15325. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15326. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15327. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15328. texture.__oldAnisotropy = texture.anisotropy;
  15329. }
  15330. }
  15331. };
  15332. this.setTexture = function ( texture, slot ) {
  15333. if ( texture.needsUpdate ) {
  15334. if ( ! texture.__webglInit ) {
  15335. texture.__webglInit = true;
  15336. texture.addEventListener( 'dispose', onTextureDispose );
  15337. texture.__webglTexture = _gl.createTexture();
  15338. _this.info.memory.textures ++;
  15339. }
  15340. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15341. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15342. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15343. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15344. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15345. var image = texture.image,
  15346. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15347. glFormat = paramThreeToGL( texture.format ),
  15348. glType = paramThreeToGL( texture.type );
  15349. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15350. var mipmap, mipmaps = texture.mipmaps;
  15351. if ( texture instanceof THREE.DataTexture ) {
  15352. // use manually created mipmaps if available
  15353. // if there are no manual mipmaps
  15354. // set 0 level mipmap and then use GL to generate other mipmap levels
  15355. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15356. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15357. mipmap = mipmaps[ i ];
  15358. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15359. }
  15360. texture.generateMipmaps = false;
  15361. } else {
  15362. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15363. }
  15364. } else if ( texture instanceof THREE.CompressedTexture ) {
  15365. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15366. mipmap = mipmaps[ i ];
  15367. if ( texture.format!==THREE.RGBAFormat ) {
  15368. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15369. } else {
  15370. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15371. }
  15372. }
  15373. } else { // regular Texture (image, video, canvas)
  15374. // use manually created mipmaps if available
  15375. // if there are no manual mipmaps
  15376. // set 0 level mipmap and then use GL to generate other mipmap levels
  15377. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15378. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15379. mipmap = mipmaps[ i ];
  15380. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15381. }
  15382. texture.generateMipmaps = false;
  15383. } else {
  15384. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15385. }
  15386. }
  15387. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15388. texture.needsUpdate = false;
  15389. if ( texture.onUpdate ) texture.onUpdate();
  15390. } else {
  15391. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15392. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15393. }
  15394. };
  15395. function clampToMaxSize ( image, maxSize ) {
  15396. if ( image.width <= maxSize && image.height <= maxSize ) {
  15397. return image;
  15398. }
  15399. // Warning: Scaling through the canvas will only work with images that use
  15400. // premultiplied alpha.
  15401. var maxDimension = Math.max( image.width, image.height );
  15402. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15403. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15404. var canvas = document.createElement( 'canvas' );
  15405. canvas.width = newWidth;
  15406. canvas.height = newHeight;
  15407. var ctx = canvas.getContext( "2d" );
  15408. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15409. return canvas;
  15410. }
  15411. function setCubeTexture ( texture, slot ) {
  15412. if ( texture.image.length === 6 ) {
  15413. if ( texture.needsUpdate ) {
  15414. if ( ! texture.image.__webglTextureCube ) {
  15415. texture.addEventListener( 'dispose', onTextureDispose );
  15416. texture.image.__webglTextureCube = _gl.createTexture();
  15417. _this.info.memory.textures ++;
  15418. }
  15419. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15420. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15421. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15422. var isCompressed = texture instanceof THREE.CompressedTexture;
  15423. var cubeImage = [];
  15424. for ( var i = 0; i < 6; i ++ ) {
  15425. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15426. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15427. } else {
  15428. cubeImage[ i ] = texture.image[ i ];
  15429. }
  15430. }
  15431. var image = cubeImage[ 0 ],
  15432. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15433. glFormat = paramThreeToGL( texture.format ),
  15434. glType = paramThreeToGL( texture.type );
  15435. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15436. for ( var i = 0; i < 6; i ++ ) {
  15437. if( !isCompressed ) {
  15438. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15439. } else {
  15440. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15441. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15442. mipmap = mipmaps[ j ];
  15443. if ( texture.format!==THREE.RGBAFormat ) {
  15444. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15445. } else {
  15446. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15447. }
  15448. }
  15449. }
  15450. }
  15451. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15452. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15453. }
  15454. texture.needsUpdate = false;
  15455. if ( texture.onUpdate ) texture.onUpdate();
  15456. } else {
  15457. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15458. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15459. }
  15460. }
  15461. };
  15462. function setCubeTextureDynamic ( texture, slot ) {
  15463. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15464. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15465. };
  15466. // Render targets
  15467. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15468. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15469. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15470. };
  15471. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15472. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15473. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15474. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15475. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15476. /* For some reason this is not working. Defaulting to RGBA4.
  15477. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15478. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15479. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15480. */
  15481. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15482. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15483. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15484. } else {
  15485. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15486. }
  15487. };
  15488. this.setRenderTarget = function ( renderTarget ) {
  15489. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15490. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15491. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15492. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15493. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15494. renderTarget.__webglTexture = _gl.createTexture();
  15495. _this.info.memory.textures ++;
  15496. // Setup texture, create render and frame buffers
  15497. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15498. glFormat = paramThreeToGL( renderTarget.format ),
  15499. glType = paramThreeToGL( renderTarget.type );
  15500. if ( isCube ) {
  15501. renderTarget.__webglFramebuffer = [];
  15502. renderTarget.__webglRenderbuffer = [];
  15503. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15504. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15505. for ( var i = 0; i < 6; i ++ ) {
  15506. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15507. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15508. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15509. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15510. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15511. }
  15512. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15513. } else {
  15514. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15515. if ( renderTarget.shareDepthFrom ) {
  15516. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15517. } else {
  15518. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15519. }
  15520. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15521. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15522. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15523. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15524. if ( renderTarget.shareDepthFrom ) {
  15525. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15526. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15527. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15528. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15529. }
  15530. } else {
  15531. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15532. }
  15533. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15534. }
  15535. // Release everything
  15536. if ( isCube ) {
  15537. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15538. } else {
  15539. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15540. }
  15541. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15542. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15543. }
  15544. var framebuffer, width, height, vx, vy;
  15545. if ( renderTarget ) {
  15546. if ( isCube ) {
  15547. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15548. } else {
  15549. framebuffer = renderTarget.__webglFramebuffer;
  15550. }
  15551. width = renderTarget.width;
  15552. height = renderTarget.height;
  15553. vx = 0;
  15554. vy = 0;
  15555. } else {
  15556. framebuffer = null;
  15557. width = _viewportWidth;
  15558. height = _viewportHeight;
  15559. vx = _viewportX;
  15560. vy = _viewportY;
  15561. }
  15562. if ( framebuffer !== _currentFramebuffer ) {
  15563. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15564. _gl.viewport( vx, vy, width, height );
  15565. _currentFramebuffer = framebuffer;
  15566. }
  15567. _currentWidth = width;
  15568. _currentHeight = height;
  15569. };
  15570. function updateRenderTargetMipmap ( renderTarget ) {
  15571. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15572. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15573. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15574. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15575. } else {
  15576. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15577. _gl.generateMipmap( _gl.TEXTURE_2D );
  15578. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15579. }
  15580. };
  15581. // Fallback filters for non-power-of-2 textures
  15582. function filterFallback ( f ) {
  15583. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15584. return _gl.NEAREST;
  15585. }
  15586. return _gl.LINEAR;
  15587. };
  15588. // Map three.js constants to WebGL constants
  15589. function paramThreeToGL ( p ) {
  15590. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15591. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15592. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15593. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15594. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15595. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15596. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15597. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15598. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15599. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15600. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15601. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15602. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15603. if ( p === THREE.ByteType ) return _gl.BYTE;
  15604. if ( p === THREE.ShortType ) return _gl.SHORT;
  15605. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15606. if ( p === THREE.IntType ) return _gl.INT;
  15607. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15608. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15609. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15610. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15611. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15612. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15613. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15614. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15615. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15616. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15617. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15618. if ( p === THREE.OneFactor ) return _gl.ONE;
  15619. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15620. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15621. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15622. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15623. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15624. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15625. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15626. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15627. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15628. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15629. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15630. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15631. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15632. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15633. }
  15634. return 0;
  15635. };
  15636. // Allocations
  15637. function allocateBones ( object ) {
  15638. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15639. return 1024;
  15640. } else {
  15641. // default for when object is not specified
  15642. // ( for example when prebuilding shader
  15643. // to be used with multiple objects )
  15644. //
  15645. // - leave some extra space for other uniforms
  15646. // - limit here is ANGLE's 254 max uniform vectors
  15647. // (up to 54 should be safe)
  15648. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15649. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15650. var maxBones = nVertexMatrices;
  15651. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15652. maxBones = Math.min( object.bones.length, maxBones );
  15653. if ( maxBones < object.bones.length ) {
  15654. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15655. }
  15656. }
  15657. return maxBones;
  15658. }
  15659. };
  15660. function allocateLights( lights ) {
  15661. var dirLights = 0;
  15662. var pointLights = 0;
  15663. var spotLights = 0;
  15664. var hemiLights = 0;
  15665. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15666. var light = lights[ l ];
  15667. if ( light.onlyShadow || light.visible === false ) continue;
  15668. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15669. if ( light instanceof THREE.PointLight ) pointLights ++;
  15670. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15671. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15672. }
  15673. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15674. };
  15675. function allocateShadows( lights ) {
  15676. var maxShadows = 0;
  15677. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15678. var light = lights[ l ];
  15679. if ( ! light.castShadow ) continue;
  15680. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15681. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15682. }
  15683. return maxShadows;
  15684. };
  15685. // Initialization
  15686. function initGL() {
  15687. try {
  15688. var attributes = {
  15689. alpha: _alpha,
  15690. depth: _depth,
  15691. stencil: _stencil,
  15692. antialias: _antialias,
  15693. premultipliedAlpha: _premultipliedAlpha,
  15694. preserveDrawingBuffer: _preserveDrawingBuffer
  15695. };
  15696. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15697. if ( _gl === null ) {
  15698. throw 'Error creating WebGL context.';
  15699. }
  15700. } catch ( error ) {
  15701. console.error( error );
  15702. }
  15703. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15704. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15705. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15706. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15707. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15708. _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' );
  15709. if ( _glExtensionTextureFloat === null ) {
  15710. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15711. }
  15712. if ( _glExtensionStandardDerivatives === null ) {
  15713. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15714. }
  15715. if ( _glExtensionTextureFilterAnisotropic === null ) {
  15716. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15717. }
  15718. if ( _glExtensionCompressedTextureS3TC === null ) {
  15719. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15720. }
  15721. if ( _glExtensionElementIndexUint === null ) {
  15722. console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' );
  15723. }
  15724. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15725. _gl.getShaderPrecisionFormat = function() {
  15726. return {
  15727. "rangeMin" : 1,
  15728. "rangeMax" : 1,
  15729. "precision" : 1
  15730. };
  15731. }
  15732. }
  15733. };
  15734. function setDefaultGLState () {
  15735. _gl.clearColor( 0, 0, 0, 1 );
  15736. _gl.clearDepth( 1 );
  15737. _gl.clearStencil( 0 );
  15738. _gl.enable( _gl.DEPTH_TEST );
  15739. _gl.depthFunc( _gl.LEQUAL );
  15740. _gl.frontFace( _gl.CCW );
  15741. _gl.cullFace( _gl.BACK );
  15742. _gl.enable( _gl.CULL_FACE );
  15743. _gl.enable( _gl.BLEND );
  15744. _gl.blendEquation( _gl.FUNC_ADD );
  15745. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15746. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15747. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15748. };
  15749. // default plugins (order is important)
  15750. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15751. this.addPrePlugin( this.shadowMapPlugin );
  15752. this.addPostPlugin( new THREE.SpritePlugin() );
  15753. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15754. };
  15755. /**
  15756. * @author szimek / https://github.com/szimek/
  15757. * @author alteredq / http://alteredqualia.com/
  15758. */
  15759. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15760. this.width = width;
  15761. this.height = height;
  15762. options = options || {};
  15763. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15764. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15765. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15766. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15767. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15768. this.offset = new THREE.Vector2( 0, 0 );
  15769. this.repeat = new THREE.Vector2( 1, 1 );
  15770. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15771. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15772. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15773. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15774. this.generateMipmaps = true;
  15775. this.shareDepthFrom = null;
  15776. };
  15777. THREE.WebGLRenderTarget.prototype = {
  15778. constructor: THREE.WebGLRenderTarget,
  15779. setSize: function ( width, height ) {
  15780. this.width = width;
  15781. this.height = height;
  15782. },
  15783. clone: function () {
  15784. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15785. tmp.wrapS = this.wrapS;
  15786. tmp.wrapT = this.wrapT;
  15787. tmp.magFilter = this.magFilter;
  15788. tmp.minFilter = this.minFilter;
  15789. tmp.anisotropy = this.anisotropy;
  15790. tmp.offset.copy( this.offset );
  15791. tmp.repeat.copy( this.repeat );
  15792. tmp.format = this.format;
  15793. tmp.type = this.type;
  15794. tmp.depthBuffer = this.depthBuffer;
  15795. tmp.stencilBuffer = this.stencilBuffer;
  15796. tmp.generateMipmaps = this.generateMipmaps;
  15797. tmp.shareDepthFrom = this.shareDepthFrom;
  15798. return tmp;
  15799. },
  15800. dispose: function () {
  15801. this.dispatchEvent( { type: 'dispose' } );
  15802. }
  15803. };
  15804. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15805. /**
  15806. * @author alteredq / http://alteredqualia.com
  15807. */
  15808. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15809. THREE.WebGLRenderTarget.call( this, width, height, options );
  15810. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15811. };
  15812. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15813. THREE.WebGLProgram = ( function () {
  15814. var programIdCount = 0;
  15815. var generateDefines = function ( defines ) {
  15816. var value, chunk, chunks = [];
  15817. for ( var d in defines ) {
  15818. value = defines[ d ];
  15819. if ( value === false ) continue;
  15820. chunk = "#define " + d + " " + value;
  15821. chunks.push( chunk );
  15822. }
  15823. return chunks.join( "\n" );
  15824. };
  15825. var cacheUniformLocations = function ( gl, program, identifiers ) {
  15826. var uniforms = {};
  15827. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15828. var id = identifiers[ i ];
  15829. uniforms[ id ] = gl.getUniformLocation( program, id );
  15830. }
  15831. return uniforms;
  15832. };
  15833. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  15834. var attributes = {};
  15835. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  15836. var id = identifiers[ i ];
  15837. attributes[ id ] = gl.getAttribLocation( program, id );
  15838. }
  15839. return attributes;
  15840. };
  15841. return function ( renderer, code, material, parameters ) {
  15842. var _this = renderer;
  15843. var _gl = _this.context;
  15844. var fragmentShader = material.fragmentShader;
  15845. var vertexShader = material.vertexShader;
  15846. var uniforms = material.uniforms;
  15847. var attributes = material.attributes;
  15848. var defines = material.defines;
  15849. var index0AttributeName = material.index0AttributeName;
  15850. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  15851. // programs with morphTargets displace position out of attribute 0
  15852. index0AttributeName = 'position';
  15853. }
  15854. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15855. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15856. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15857. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15858. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15859. }
  15860. // console.log( "building new program " );
  15861. //
  15862. var customDefines = generateDefines( defines );
  15863. //
  15864. var program = _gl.createProgram();
  15865. var prefix_vertex, prefix_fragment;
  15866. if ( material instanceof THREE.RawShaderMaterial ) {
  15867. prefix_vertex = '';
  15868. prefix_fragment = '';
  15869. } else {
  15870. prefix_vertex = [
  15871. "precision " + parameters.precision + " float;",
  15872. "precision " + parameters.precision + " int;",
  15873. customDefines,
  15874. parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15875. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15876. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15877. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15878. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15879. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15880. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15881. "#define MAX_SHADOWS " + parameters.maxShadows,
  15882. "#define MAX_BONES " + parameters.maxBones,
  15883. parameters.map ? "#define USE_MAP" : "",
  15884. parameters.envMap ? "#define USE_ENVMAP" : "",
  15885. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15886. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15887. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15888. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15889. parameters.vertexColors ? "#define USE_COLOR" : "",
  15890. parameters.skinning ? "#define USE_SKINNING" : "",
  15891. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15892. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15893. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15894. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15895. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15896. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15897. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15898. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15899. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15900. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15901. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15902. "uniform mat4 modelMatrix;",
  15903. "uniform mat4 modelViewMatrix;",
  15904. "uniform mat4 projectionMatrix;",
  15905. "uniform mat4 viewMatrix;",
  15906. "uniform mat3 normalMatrix;",
  15907. "uniform vec3 cameraPosition;",
  15908. "attribute vec3 position;",
  15909. "attribute vec3 normal;",
  15910. "attribute vec2 uv;",
  15911. "attribute vec2 uv2;",
  15912. "#ifdef USE_COLOR",
  15913. " attribute vec3 color;",
  15914. "#endif",
  15915. "#ifdef USE_MORPHTARGETS",
  15916. " attribute vec3 morphTarget0;",
  15917. " attribute vec3 morphTarget1;",
  15918. " attribute vec3 morphTarget2;",
  15919. " attribute vec3 morphTarget3;",
  15920. " #ifdef USE_MORPHNORMALS",
  15921. " attribute vec3 morphNormal0;",
  15922. " attribute vec3 morphNormal1;",
  15923. " attribute vec3 morphNormal2;",
  15924. " attribute vec3 morphNormal3;",
  15925. " #else",
  15926. " attribute vec3 morphTarget4;",
  15927. " attribute vec3 morphTarget5;",
  15928. " attribute vec3 morphTarget6;",
  15929. " attribute vec3 morphTarget7;",
  15930. " #endif",
  15931. "#endif",
  15932. "#ifdef USE_SKINNING",
  15933. " attribute vec4 skinIndex;",
  15934. " attribute vec4 skinWeight;",
  15935. "#endif",
  15936. ""
  15937. ].join( '\n' );
  15938. prefix_fragment = [
  15939. "precision " + parameters.precision + " float;",
  15940. "precision " + parameters.precision + " int;",
  15941. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15942. customDefines,
  15943. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15944. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15945. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15946. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15947. "#define MAX_SHADOWS " + parameters.maxShadows,
  15948. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15949. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15950. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15951. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15952. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15953. parameters.map ? "#define USE_MAP" : "",
  15954. parameters.envMap ? "#define USE_ENVMAP" : "",
  15955. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15956. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15957. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15958. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15959. parameters.vertexColors ? "#define USE_COLOR" : "",
  15960. parameters.metal ? "#define METAL" : "",
  15961. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15962. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15963. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15964. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15965. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15966. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15967. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15968. "uniform mat4 viewMatrix;",
  15969. "uniform vec3 cameraPosition;",
  15970. ""
  15971. ].join( '\n' );
  15972. }
  15973. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  15974. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  15975. _gl.attachShader( program, glVertexShader );
  15976. _gl.attachShader( program, glFragmentShader );
  15977. if ( index0AttributeName !== undefined ) {
  15978. // Force a particular attribute to index 0.
  15979. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15980. // And, color, for example is often automatically bound to index 0 so disabling it
  15981. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15982. }
  15983. _gl.linkProgram( program );
  15984. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  15985. console.error( 'Could not initialise shader' );
  15986. console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
  15987. console.error( 'gl.getError()', _gl.getError() );
  15988. }
  15989. if ( _gl.getProgramInfoLog( program ) !== '' ) {
  15990. console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
  15991. }
  15992. // clean up
  15993. _gl.deleteShader( glVertexShader );
  15994. _gl.deleteShader( glFragmentShader );
  15995. // cache uniform locations
  15996. var identifiers = [
  15997. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15998. 'morphTargetInfluences'
  15999. ];
  16000. if ( parameters.useVertexTexture ) {
  16001. identifiers.push( 'boneTexture' );
  16002. identifiers.push( 'boneTextureWidth' );
  16003. identifiers.push( 'boneTextureHeight' );
  16004. } else {
  16005. identifiers.push( 'boneGlobalMatrices' );
  16006. }
  16007. for ( var u in uniforms ) {
  16008. identifiers.push( u );
  16009. }
  16010. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  16011. // cache attributes locations
  16012. identifiers = [
  16013. "position", "normal", "uv", "uv2", "tangent", "color",
  16014. "skinIndex", "skinWeight", "lineDistance"
  16015. ];
  16016. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  16017. identifiers.push( "morphTarget" + i );
  16018. }
  16019. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  16020. identifiers.push( "morphNormal" + i );
  16021. }
  16022. for ( var a in attributes ) {
  16023. identifiers.push( a );
  16024. }
  16025. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  16026. //
  16027. this.id = programIdCount ++;
  16028. this.code = code;
  16029. this.usedTimes = 1;
  16030. this.program = program;
  16031. this.vertexShader = glVertexShader;
  16032. this.fragmentShader = glFragmentShader;
  16033. return this;
  16034. };
  16035. } )();
  16036. THREE.WebGLShader = ( function () {
  16037. var addLineNumbers = function ( string ) {
  16038. var lines = string.split( '\n' );
  16039. for ( var i = 0; i < lines.length; i ++ ) {
  16040. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  16041. }
  16042. return lines.join( '\n' );
  16043. };
  16044. return function ( gl, type, string ) {
  16045. var shader = gl.createShader( type );
  16046. gl.shaderSource( shader, string );
  16047. gl.compileShader( shader );
  16048. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  16049. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  16050. }
  16051. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  16052. console.error( 'THREE.WebGLShader:', 'gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) );
  16053. console.error( addLineNumbers( string ) );
  16054. }
  16055. return shader;
  16056. };
  16057. } )();
  16058. /**
  16059. * @author mrdoob / http://mrdoob.com/
  16060. */
  16061. THREE.RenderableVertex = function () {
  16062. this.position = new THREE.Vector3();
  16063. this.positionWorld = new THREE.Vector3();
  16064. this.positionScreen = new THREE.Vector4();
  16065. this.visible = true;
  16066. };
  16067. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  16068. this.positionWorld.copy( vertex.positionWorld );
  16069. this.positionScreen.copy( vertex.positionScreen );
  16070. };
  16071. /**
  16072. * @author mrdoob / http://mrdoob.com/
  16073. */
  16074. THREE.RenderableFace = function () {
  16075. this.id = 0;
  16076. this.v1 = new THREE.RenderableVertex();
  16077. this.v2 = new THREE.RenderableVertex();
  16078. this.v3 = new THREE.RenderableVertex();
  16079. this.normalModel = new THREE.Vector3();
  16080. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  16081. this.vertexNormalsLength = 0;
  16082. this.color = null;
  16083. this.material = null;
  16084. this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ];
  16085. this.z = 0;
  16086. };
  16087. /**
  16088. * @author mrdoob / http://mrdoob.com/
  16089. */
  16090. THREE.RenderableObject = function () {
  16091. this.id = 0;
  16092. this.object = null;
  16093. this.z = 0;
  16094. };
  16095. /**
  16096. * @author mrdoob / http://mrdoob.com/
  16097. */
  16098. THREE.RenderableSprite = function () {
  16099. this.id = 0;
  16100. this.object = null;
  16101. this.x = 0;
  16102. this.y = 0;
  16103. this.z = 0;
  16104. this.rotation = 0;
  16105. this.scale = new THREE.Vector2();
  16106. this.material = null;
  16107. };
  16108. /**
  16109. * @author mrdoob / http://mrdoob.com/
  16110. */
  16111. THREE.RenderableLine = function () {
  16112. this.id = 0;
  16113. this.v1 = new THREE.RenderableVertex();
  16114. this.v2 = new THREE.RenderableVertex();
  16115. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  16116. this.material = null;
  16117. this.z = 0;
  16118. };
  16119. /**
  16120. * @author mrdoob / http://mrdoob.com/
  16121. * @author alteredq / http://alteredqualia.com/
  16122. */
  16123. THREE.GeometryUtils = {
  16124. // Merge two geometries or geometry and geometry from object (using object's transform)
  16125. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  16126. var matrix, normalMatrix,
  16127. vertexOffset = geometry1.vertices.length,
  16128. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  16129. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  16130. vertices1 = geometry1.vertices,
  16131. vertices2 = geometry2.vertices,
  16132. faces1 = geometry1.faces,
  16133. faces2 = geometry2.faces,
  16134. uvs1 = geometry1.faceVertexUvs[ 0 ],
  16135. uvs2 = geometry2.faceVertexUvs[ 0 ];
  16136. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  16137. if ( object2 instanceof THREE.Mesh ) {
  16138. object2.matrixAutoUpdate && object2.updateMatrix();
  16139. matrix = object2.matrix;
  16140. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  16141. }
  16142. // vertices
  16143. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  16144. var vertex = vertices2[ i ];
  16145. var vertexCopy = vertex.clone();
  16146. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  16147. vertices1.push( vertexCopy );
  16148. }
  16149. // faces
  16150. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  16151. var face = faces2[ i ], faceCopy, normal, color,
  16152. faceVertexNormals = face.vertexNormals,
  16153. faceVertexColors = face.vertexColors;
  16154. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  16155. faceCopy.normal.copy( face.normal );
  16156. if ( normalMatrix ) {
  16157. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  16158. }
  16159. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  16160. normal = faceVertexNormals[ j ].clone();
  16161. if ( normalMatrix ) {
  16162. normal.applyMatrix3( normalMatrix ).normalize();
  16163. }
  16164. faceCopy.vertexNormals.push( normal );
  16165. }
  16166. faceCopy.color.copy( face.color );
  16167. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  16168. color = faceVertexColors[ j ];
  16169. faceCopy.vertexColors.push( color.clone() );
  16170. }
  16171. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  16172. faces1.push( faceCopy );
  16173. }
  16174. // uvs
  16175. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  16176. var uv = uvs2[ i ], uvCopy = [];
  16177. if ( uv === undefined ) {
  16178. continue;
  16179. }
  16180. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  16181. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  16182. }
  16183. uvs1.push( uvCopy );
  16184. }
  16185. },
  16186. // Get random point in triangle (via barycentric coordinates)
  16187. // (uniform distribution)
  16188. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  16189. randomPointInTriangle: function () {
  16190. var vector = new THREE.Vector3();
  16191. return function ( vectorA, vectorB, vectorC ) {
  16192. var point = new THREE.Vector3();
  16193. var a = THREE.Math.random16();
  16194. var b = THREE.Math.random16();
  16195. if ( ( a + b ) > 1 ) {
  16196. a = 1 - a;
  16197. b = 1 - b;
  16198. }
  16199. var c = 1 - a - b;
  16200. point.copy( vectorA );
  16201. point.multiplyScalar( a );
  16202. vector.copy( vectorB );
  16203. vector.multiplyScalar( b );
  16204. point.add( vector );
  16205. vector.copy( vectorC );
  16206. vector.multiplyScalar( c );
  16207. point.add( vector );
  16208. return point;
  16209. };
  16210. }(),
  16211. // Get random point in face (triangle / quad)
  16212. // (uniform distribution)
  16213. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  16214. var vA, vB, vC, vD;
  16215. vA = geometry.vertices[ face.a ];
  16216. vB = geometry.vertices[ face.b ];
  16217. vC = geometry.vertices[ face.c ];
  16218. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  16219. },
  16220. // Get uniformly distributed random points in mesh
  16221. // - create array with cumulative sums of face areas
  16222. // - pick random number from 0 to total area
  16223. // - find corresponding place in area array by binary search
  16224. // - get random point in face
  16225. randomPointsInGeometry: function ( geometry, n ) {
  16226. var face, i,
  16227. faces = geometry.faces,
  16228. vertices = geometry.vertices,
  16229. il = faces.length,
  16230. totalArea = 0,
  16231. cumulativeAreas = [],
  16232. vA, vB, vC, vD;
  16233. // precompute face areas
  16234. for ( i = 0; i < il; i ++ ) {
  16235. face = faces[ i ];
  16236. vA = vertices[ face.a ];
  16237. vB = vertices[ face.b ];
  16238. vC = vertices[ face.c ];
  16239. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16240. totalArea += face._area;
  16241. cumulativeAreas[ i ] = totalArea;
  16242. }
  16243. // binary search cumulative areas array
  16244. function binarySearchIndices( value ) {
  16245. function binarySearch( start, end ) {
  16246. // return closest larger index
  16247. // if exact number is not found
  16248. if ( end < start )
  16249. return start;
  16250. var mid = start + Math.floor( ( end - start ) / 2 );
  16251. if ( cumulativeAreas[ mid ] > value ) {
  16252. return binarySearch( start, mid - 1 );
  16253. } else if ( cumulativeAreas[ mid ] < value ) {
  16254. return binarySearch( mid + 1, end );
  16255. } else {
  16256. return mid;
  16257. }
  16258. }
  16259. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16260. return result;
  16261. }
  16262. // pick random face weighted by face area
  16263. var r, index,
  16264. result = [];
  16265. var stats = {};
  16266. for ( i = 0; i < n; i ++ ) {
  16267. r = THREE.Math.random16() * totalArea;
  16268. index = binarySearchIndices( r );
  16269. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16270. if ( ! stats[ index ] ) {
  16271. stats[ index ] = 1;
  16272. } else {
  16273. stats[ index ] += 1;
  16274. }
  16275. }
  16276. return result;
  16277. },
  16278. // Get triangle area (half of parallelogram)
  16279. // http://mathworld.wolfram.com/TriangleArea.html
  16280. triangleArea: function () {
  16281. var vector1 = new THREE.Vector3();
  16282. var vector2 = new THREE.Vector3();
  16283. return function ( vectorA, vectorB, vectorC ) {
  16284. vector1.subVectors( vectorB, vectorA );
  16285. vector2.subVectors( vectorC, vectorA );
  16286. vector1.cross( vector2 );
  16287. return 0.5 * vector1.length();
  16288. };
  16289. }(),
  16290. // Center geometry so that 0,0,0 is in center of bounding box
  16291. center: function ( geometry ) {
  16292. geometry.computeBoundingBox();
  16293. var bb = geometry.boundingBox;
  16294. var offset = new THREE.Vector3();
  16295. offset.addVectors( bb.min, bb.max );
  16296. offset.multiplyScalar( -0.5 );
  16297. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16298. geometry.computeBoundingBox();
  16299. return offset;
  16300. }
  16301. };
  16302. /**
  16303. * @author alteredq / http://alteredqualia.com/
  16304. * @author mrdoob / http://mrdoob.com/
  16305. */
  16306. THREE.ImageUtils = {
  16307. crossOrigin: undefined,
  16308. loadTexture: function ( url, mapping, onLoad, onError ) {
  16309. var loader = new THREE.ImageLoader();
  16310. loader.crossOrigin = this.crossOrigin;
  16311. var texture = new THREE.Texture( undefined, mapping );
  16312. var image = loader.load( url, function () {
  16313. texture.needsUpdate = true;
  16314. if ( onLoad ) onLoad( texture );
  16315. } );
  16316. texture.image = image;
  16317. texture.sourceFile = url;
  16318. return texture;
  16319. },
  16320. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16321. var texture = new THREE.CompressedTexture();
  16322. texture.mapping = mapping;
  16323. var request = new XMLHttpRequest();
  16324. request.onload = function () {
  16325. var buffer = request.response;
  16326. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16327. texture.format = dds.format;
  16328. texture.mipmaps = dds.mipmaps;
  16329. texture.image.width = dds.width;
  16330. texture.image.height = dds.height;
  16331. // gl.generateMipmap fails for compressed textures
  16332. // mipmaps must be embedded in the DDS file
  16333. // or texture filters must not use mipmapping
  16334. texture.generateMipmaps = false;
  16335. texture.needsUpdate = true;
  16336. if ( onLoad ) onLoad( texture );
  16337. }
  16338. request.onerror = onError;
  16339. request.open( 'GET', url, true );
  16340. request.responseType = "arraybuffer";
  16341. request.send( null );
  16342. return texture;
  16343. },
  16344. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16345. var images = [];
  16346. images.loadCount = 0;
  16347. var texture = new THREE.Texture();
  16348. texture.image = images;
  16349. if ( mapping !== undefined ) texture.mapping = mapping;
  16350. // no flipping needed for cube textures
  16351. texture.flipY = false;
  16352. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16353. var cubeImage = new Image();
  16354. images[ i ] = cubeImage;
  16355. cubeImage.onload = function () {
  16356. images.loadCount += 1;
  16357. if ( images.loadCount === 6 ) {
  16358. texture.needsUpdate = true;
  16359. if ( onLoad ) onLoad( texture );
  16360. }
  16361. };
  16362. cubeImage.onerror = onError;
  16363. cubeImage.crossOrigin = this.crossOrigin;
  16364. cubeImage.src = array[ i ];
  16365. }
  16366. return texture;
  16367. },
  16368. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16369. var images = [];
  16370. images.loadCount = 0;
  16371. var texture = new THREE.CompressedTexture();
  16372. texture.image = images;
  16373. if ( mapping !== undefined ) texture.mapping = mapping;
  16374. // no flipping for cube textures
  16375. // (also flipping doesn't work for compressed textures )
  16376. texture.flipY = false;
  16377. // can't generate mipmaps for compressed textures
  16378. // mips must be embedded in DDS files
  16379. texture.generateMipmaps = false;
  16380. var generateCubeFaceCallback = function ( rq, img ) {
  16381. return function () {
  16382. var buffer = rq.response;
  16383. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16384. img.format = dds.format;
  16385. img.mipmaps = dds.mipmaps;
  16386. img.width = dds.width;
  16387. img.height = dds.height;
  16388. images.loadCount += 1;
  16389. if ( images.loadCount === 6 ) {
  16390. texture.format = dds.format;
  16391. texture.needsUpdate = true;
  16392. if ( onLoad ) onLoad( texture );
  16393. }
  16394. }
  16395. }
  16396. // compressed cubemap textures as 6 separate DDS files
  16397. if ( array instanceof Array ) {
  16398. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16399. var cubeImage = {};
  16400. images[ i ] = cubeImage;
  16401. var request = new XMLHttpRequest();
  16402. request.onload = generateCubeFaceCallback( request, cubeImage );
  16403. request.onerror = onError;
  16404. var url = array[ i ];
  16405. request.open( 'GET', url, true );
  16406. request.responseType = "arraybuffer";
  16407. request.send( null );
  16408. }
  16409. // compressed cubemap texture stored in a single DDS file
  16410. } else {
  16411. var url = array;
  16412. var request = new XMLHttpRequest();
  16413. request.onload = function( ) {
  16414. var buffer = request.response;
  16415. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16416. if ( dds.isCubemap ) {
  16417. var faces = dds.mipmaps.length / dds.mipmapCount;
  16418. for ( var f = 0; f < faces; f ++ ) {
  16419. images[ f ] = { mipmaps : [] };
  16420. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16421. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16422. images[ f ].format = dds.format;
  16423. images[ f ].width = dds.width;
  16424. images[ f ].height = dds.height;
  16425. }
  16426. }
  16427. texture.format = dds.format;
  16428. texture.needsUpdate = true;
  16429. if ( onLoad ) onLoad( texture );
  16430. }
  16431. }
  16432. request.onerror = onError;
  16433. request.open( 'GET', url, true );
  16434. request.responseType = "arraybuffer";
  16435. request.send( null );
  16436. }
  16437. return texture;
  16438. },
  16439. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  16440. var images = [];
  16441. images.loadCount = 0;
  16442. var texture = new THREE.CompressedTexture();
  16443. texture.image = images;
  16444. if ( mapping !== undefined ) texture.mapping = mapping;
  16445. // no flipping for cube textures
  16446. // (also flipping doesn't work for compressed textures )
  16447. texture.flipY = false;
  16448. // can't generate mipmaps for compressed textures
  16449. // mips must be embedded in DDS files
  16450. texture.generateMipmaps = false;
  16451. {
  16452. var request = new XMLHttpRequest();
  16453. request.onload = function( ) {
  16454. var buffer = request.response;
  16455. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16456. if ( dds.isCubemap ) {
  16457. var faces = dds.mipmaps.length / dds.mipmapCount;
  16458. for ( var f = 0; f < faces; f ++ ) {
  16459. images[ f ] = { mipmaps : [] };
  16460. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16461. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16462. images[ f ].format = dds.format;
  16463. images[ f ].width = dds.width;
  16464. images[ f ].height = dds.height;
  16465. }
  16466. }
  16467. } else {
  16468. texture.image.width = dds.width;
  16469. texture.image.height = dds.height;
  16470. texture.mipmaps = dds.mipmaps;
  16471. }
  16472. texture.format = dds.format;
  16473. texture.needsUpdate = true;
  16474. if ( onLoad ) onLoad( texture );
  16475. }
  16476. request.onerror = onError;
  16477. request.open( 'GET', url, true );
  16478. request.responseType = "arraybuffer";
  16479. request.send( null );
  16480. }
  16481. return texture;
  16482. },
  16483. parseDDS: function ( buffer, loadMipmaps ) {
  16484. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16485. // Adapted from @toji's DDS utils
  16486. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16487. // All values and structures referenced from:
  16488. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16489. var DDS_MAGIC = 0x20534444;
  16490. var DDSD_CAPS = 0x1,
  16491. DDSD_HEIGHT = 0x2,
  16492. DDSD_WIDTH = 0x4,
  16493. DDSD_PITCH = 0x8,
  16494. DDSD_PIXELFORMAT = 0x1000,
  16495. DDSD_MIPMAPCOUNT = 0x20000,
  16496. DDSD_LINEARSIZE = 0x80000,
  16497. DDSD_DEPTH = 0x800000;
  16498. var DDSCAPS_COMPLEX = 0x8,
  16499. DDSCAPS_MIPMAP = 0x400000,
  16500. DDSCAPS_TEXTURE = 0x1000;
  16501. var DDSCAPS2_CUBEMAP = 0x200,
  16502. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16503. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16504. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16505. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16506. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16507. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16508. DDSCAPS2_VOLUME = 0x200000;
  16509. var DDPF_ALPHAPIXELS = 0x1,
  16510. DDPF_ALPHA = 0x2,
  16511. DDPF_FOURCC = 0x4,
  16512. DDPF_RGB = 0x40,
  16513. DDPF_YUV = 0x200,
  16514. DDPF_LUMINANCE = 0x20000;
  16515. function fourCCToInt32( value ) {
  16516. return value.charCodeAt(0) +
  16517. (value.charCodeAt(1) << 8) +
  16518. (value.charCodeAt(2) << 16) +
  16519. (value.charCodeAt(3) << 24);
  16520. }
  16521. function int32ToFourCC( value ) {
  16522. return String.fromCharCode(
  16523. value & 0xff,
  16524. (value >> 8) & 0xff,
  16525. (value >> 16) & 0xff,
  16526. (value >> 24) & 0xff
  16527. );
  16528. }
  16529. function loadARGBMip( buffer, dataOffset, width, height ) {
  16530. var dataLength = width*height*4;
  16531. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  16532. var byteArray = new Uint8Array( dataLength );
  16533. var dst = 0;
  16534. var src = 0;
  16535. for ( var y = 0; y < height; y++ ) {
  16536. for ( var x = 0; x < width; x++ ) {
  16537. var b = srcBuffer[src]; src++;
  16538. var g = srcBuffer[src]; src++;
  16539. var r = srcBuffer[src]; src++;
  16540. var a = srcBuffer[src]; src++;
  16541. byteArray[dst] = r; dst++; //r
  16542. byteArray[dst] = g; dst++; //g
  16543. byteArray[dst] = b; dst++; //b
  16544. byteArray[dst] = a; dst++; //a
  16545. }
  16546. }
  16547. return byteArray;
  16548. }
  16549. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16550. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16551. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16552. var headerLengthInt = 31; // The header length in 32 bit ints
  16553. // Offsets into the header array
  16554. var off_magic = 0;
  16555. var off_size = 1;
  16556. var off_flags = 2;
  16557. var off_height = 3;
  16558. var off_width = 4;
  16559. var off_mipmapCount = 7;
  16560. var off_pfFlags = 20;
  16561. var off_pfFourCC = 21;
  16562. var off_RGBBitCount = 22;
  16563. var off_RBitMask = 23;
  16564. var off_GBitMask = 24;
  16565. var off_BBitMask = 25;
  16566. var off_ABitMask = 26;
  16567. var off_caps = 27;
  16568. var off_caps2 = 28;
  16569. var off_caps3 = 29;
  16570. var off_caps4 = 30;
  16571. // Parse header
  16572. var header = new Int32Array( buffer, 0, headerLengthInt );
  16573. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16574. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16575. return dds;
  16576. }
  16577. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16578. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16579. return dds;
  16580. }
  16581. var blockBytes;
  16582. var fourCC = header[ off_pfFourCC ];
  16583. var isRGBAUncompressed = false;
  16584. switch ( fourCC ) {
  16585. case FOURCC_DXT1:
  16586. blockBytes = 8;
  16587. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16588. break;
  16589. case FOURCC_DXT3:
  16590. blockBytes = 16;
  16591. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16592. break;
  16593. case FOURCC_DXT5:
  16594. blockBytes = 16;
  16595. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16596. break;
  16597. default:
  16598. if( header[off_RGBBitCount] ==32
  16599. && header[off_RBitMask]&0xff0000
  16600. && header[off_GBitMask]&0xff00
  16601. && header[off_BBitMask]&0xff
  16602. && header[off_ABitMask]&0xff000000 ) {
  16603. isRGBAUncompressed = true;
  16604. blockBytes = 64;
  16605. dds.format = THREE.RGBAFormat;
  16606. } else {
  16607. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16608. return dds;
  16609. }
  16610. }
  16611. dds.mipmapCount = 1;
  16612. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16613. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16614. }
  16615. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16616. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16617. dds.width = header[ off_width ];
  16618. dds.height = header[ off_height ];
  16619. var dataOffset = header[ off_size ] + 4;
  16620. // Extract mipmaps buffers
  16621. var width = dds.width;
  16622. var height = dds.height;
  16623. var faces = dds.isCubemap ? 6 : 1;
  16624. for ( var face = 0; face < faces; face ++ ) {
  16625. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16626. if( isRGBAUncompressed ) {
  16627. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16628. var dataLength = byteArray.length;
  16629. } else {
  16630. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16631. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16632. }
  16633. var mipmap = { "data": byteArray, "width": width, "height": height };
  16634. dds.mipmaps.push( mipmap );
  16635. dataOffset += dataLength;
  16636. width = Math.max( width * 0.5, 1 );
  16637. height = Math.max( height * 0.5, 1 );
  16638. }
  16639. width = dds.width;
  16640. height = dds.height;
  16641. }
  16642. return dds;
  16643. },
  16644. getNormalMap: function ( image, depth ) {
  16645. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16646. var cross = function ( a, b ) {
  16647. 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 ] ];
  16648. }
  16649. var subtract = function ( a, b ) {
  16650. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16651. }
  16652. var normalize = function ( a ) {
  16653. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16654. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16655. }
  16656. depth = depth | 1;
  16657. var width = image.width;
  16658. var height = image.height;
  16659. var canvas = document.createElement( 'canvas' );
  16660. canvas.width = width;
  16661. canvas.height = height;
  16662. var context = canvas.getContext( '2d' );
  16663. context.drawImage( image, 0, 0 );
  16664. var data = context.getImageData( 0, 0, width, height ).data;
  16665. var imageData = context.createImageData( width, height );
  16666. var output = imageData.data;
  16667. for ( var x = 0; x < width; x ++ ) {
  16668. for ( var y = 0; y < height; y ++ ) {
  16669. var ly = y - 1 < 0 ? 0 : y - 1;
  16670. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16671. var lx = x - 1 < 0 ? 0 : x - 1;
  16672. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16673. var points = [];
  16674. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16675. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16676. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16677. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16678. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16679. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16680. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16681. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16682. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16683. var normals = [];
  16684. var num_points = points.length;
  16685. for ( var i = 0; i < num_points; i ++ ) {
  16686. var v1 = points[ i ];
  16687. var v2 = points[ ( i + 1 ) % num_points ];
  16688. v1 = subtract( v1, origin );
  16689. v2 = subtract( v2, origin );
  16690. normals.push( normalize( cross( v1, v2 ) ) );
  16691. }
  16692. var normal = [ 0, 0, 0 ];
  16693. for ( var i = 0; i < normals.length; i ++ ) {
  16694. normal[ 0 ] += normals[ i ][ 0 ];
  16695. normal[ 1 ] += normals[ i ][ 1 ];
  16696. normal[ 2 ] += normals[ i ][ 2 ];
  16697. }
  16698. normal[ 0 ] /= normals.length;
  16699. normal[ 1 ] /= normals.length;
  16700. normal[ 2 ] /= normals.length;
  16701. var idx = ( y * width + x ) * 4;
  16702. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16703. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16704. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16705. output[ idx + 3 ] = 255;
  16706. }
  16707. }
  16708. context.putImageData( imageData, 0, 0 );
  16709. return canvas;
  16710. },
  16711. generateDataTexture: function ( width, height, color ) {
  16712. var size = width * height;
  16713. var data = new Uint8Array( 3 * size );
  16714. var r = Math.floor( color.r * 255 );
  16715. var g = Math.floor( color.g * 255 );
  16716. var b = Math.floor( color.b * 255 );
  16717. for ( var i = 0; i < size; i ++ ) {
  16718. data[ i * 3 ] = r;
  16719. data[ i * 3 + 1 ] = g;
  16720. data[ i * 3 + 2 ] = b;
  16721. }
  16722. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16723. texture.needsUpdate = true;
  16724. return texture;
  16725. }
  16726. };
  16727. /**
  16728. * @author alteredq / http://alteredqualia.com/
  16729. */
  16730. THREE.SceneUtils = {
  16731. createMultiMaterialObject: function ( geometry, materials ) {
  16732. var group = new THREE.Object3D();
  16733. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16734. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16735. }
  16736. return group;
  16737. },
  16738. detach : function ( child, parent, scene ) {
  16739. child.applyMatrix( parent.matrixWorld );
  16740. parent.remove( child );
  16741. scene.add( child );
  16742. },
  16743. attach: function ( child, scene, parent ) {
  16744. var matrixWorldInverse = new THREE.Matrix4();
  16745. matrixWorldInverse.getInverse( parent.matrixWorld );
  16746. child.applyMatrix( matrixWorldInverse );
  16747. scene.remove( child );
  16748. parent.add( child );
  16749. }
  16750. };
  16751. /**
  16752. * @author zz85 / http://www.lab4games.net/zz85/blog
  16753. * @author alteredq / http://alteredqualia.com/
  16754. *
  16755. * For Text operations in three.js (See TextGeometry)
  16756. *
  16757. * It uses techniques used in:
  16758. *
  16759. * typeface.js and canvastext
  16760. * For converting fonts and rendering with javascript
  16761. * http://typeface.neocracy.org
  16762. *
  16763. * Triangulation ported from AS3
  16764. * Simple Polygon Triangulation
  16765. * http://actionsnippet.com/?p=1462
  16766. *
  16767. * A Method to triangulate shapes with holes
  16768. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16769. *
  16770. */
  16771. THREE.FontUtils = {
  16772. faces : {},
  16773. // Just for now. face[weight][style]
  16774. face : "helvetiker",
  16775. weight: "normal",
  16776. style : "normal",
  16777. size : 150,
  16778. divisions : 10,
  16779. getFace : function() {
  16780. return this.faces[ this.face ][ this.weight ][ this.style ];
  16781. },
  16782. loadFace : function( data ) {
  16783. var family = data.familyName.toLowerCase();
  16784. var ThreeFont = this;
  16785. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16786. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16787. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16788. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16789. return data;
  16790. },
  16791. drawText : function( text ) {
  16792. var characterPts = [], allPts = [];
  16793. // RenderText
  16794. var i, p,
  16795. face = this.getFace(),
  16796. scale = this.size / face.resolution,
  16797. offset = 0,
  16798. chars = String( text ).split( '' ),
  16799. length = chars.length;
  16800. var fontPaths = [];
  16801. for ( i = 0; i < length; i ++ ) {
  16802. var path = new THREE.Path();
  16803. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16804. offset += ret.offset;
  16805. fontPaths.push( ret.path );
  16806. }
  16807. // get the width
  16808. var width = offset / 2;
  16809. //
  16810. // for ( p = 0; p < allPts.length; p++ ) {
  16811. //
  16812. // allPts[ p ].x -= width;
  16813. //
  16814. // }
  16815. //var extract = this.extractPoints( allPts, characterPts );
  16816. //extract.contour = allPts;
  16817. //extract.paths = fontPaths;
  16818. //extract.offset = width;
  16819. return { paths : fontPaths, offset : width };
  16820. },
  16821. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16822. var pts = [];
  16823. var i, i2, divisions,
  16824. outline, action, length,
  16825. scaleX, scaleY,
  16826. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16827. laste,
  16828. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16829. if ( !glyph ) return;
  16830. if ( glyph.o ) {
  16831. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16832. length = outline.length;
  16833. scaleX = scale;
  16834. scaleY = scale;
  16835. for ( i = 0; i < length; ) {
  16836. action = outline[ i ++ ];
  16837. //console.log( action );
  16838. switch( action ) {
  16839. case 'm':
  16840. // Move To
  16841. x = outline[ i++ ] * scaleX + offset;
  16842. y = outline[ i++ ] * scaleY;
  16843. path.moveTo( x, y );
  16844. break;
  16845. case 'l':
  16846. // Line To
  16847. x = outline[ i++ ] * scaleX + offset;
  16848. y = outline[ i++ ] * scaleY;
  16849. path.lineTo(x,y);
  16850. break;
  16851. case 'q':
  16852. // QuadraticCurveTo
  16853. cpx = outline[ i++ ] * scaleX + offset;
  16854. cpy = outline[ i++ ] * scaleY;
  16855. cpx1 = outline[ i++ ] * scaleX + offset;
  16856. cpy1 = outline[ i++ ] * scaleY;
  16857. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16858. laste = pts[ pts.length - 1 ];
  16859. if ( laste ) {
  16860. cpx0 = laste.x;
  16861. cpy0 = laste.y;
  16862. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16863. var t = i2 / divisions;
  16864. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16865. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16866. }
  16867. }
  16868. break;
  16869. case 'b':
  16870. // Cubic Bezier Curve
  16871. cpx = outline[ i++ ] * scaleX + offset;
  16872. cpy = outline[ i++ ] * scaleY;
  16873. cpx1 = outline[ i++ ] * scaleX + offset;
  16874. cpy1 = outline[ i++ ] * -scaleY;
  16875. cpx2 = outline[ i++ ] * scaleX + offset;
  16876. cpy2 = outline[ i++ ] * -scaleY;
  16877. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16878. laste = pts[ pts.length - 1 ];
  16879. if ( laste ) {
  16880. cpx0 = laste.x;
  16881. cpy0 = laste.y;
  16882. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16883. var t = i2 / divisions;
  16884. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16885. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16886. }
  16887. }
  16888. break;
  16889. }
  16890. }
  16891. }
  16892. return { offset: glyph.ha*scale, path:path};
  16893. }
  16894. };
  16895. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16896. // Parameters
  16897. parameters = parameters || {};
  16898. var size = parameters.size !== undefined ? parameters.size : 100;
  16899. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16900. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16901. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16902. var style = parameters.style !== undefined ? parameters.style : "normal";
  16903. THREE.FontUtils.size = size;
  16904. THREE.FontUtils.divisions = curveSegments;
  16905. THREE.FontUtils.face = font;
  16906. THREE.FontUtils.weight = weight;
  16907. THREE.FontUtils.style = style;
  16908. // Get a Font data json object
  16909. var data = THREE.FontUtils.drawText( text );
  16910. var paths = data.paths;
  16911. var shapes = [];
  16912. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16913. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16914. }
  16915. return shapes;
  16916. };
  16917. /**
  16918. * This code is a quick port of code written in C++ which was submitted to
  16919. * flipcode.com by John W. Ratcliff // July 22, 2000
  16920. * See original code and more information here:
  16921. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16922. *
  16923. * ported to actionscript by Zevan Rosser
  16924. * www.actionsnippet.com
  16925. *
  16926. * ported to javascript by Joshua Koo
  16927. * http://www.lab4games.net/zz85/blog
  16928. *
  16929. */
  16930. ( function( namespace ) {
  16931. var EPSILON = 0.0000000001;
  16932. // takes in an contour array and returns
  16933. var process = function( contour, indices ) {
  16934. var n = contour.length;
  16935. if ( n < 3 ) return null;
  16936. var result = [],
  16937. verts = [],
  16938. vertIndices = [];
  16939. /* we want a counter-clockwise polygon in verts */
  16940. var u, v, w;
  16941. if ( area( contour ) > 0.0 ) {
  16942. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16943. } else {
  16944. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16945. }
  16946. var nv = n;
  16947. /* remove nv - 2 vertices, creating 1 triangle every time */
  16948. var count = 2 * nv; /* error detection */
  16949. for( v = nv - 1; nv > 2; ) {
  16950. /* if we loop, it is probably a non-simple polygon */
  16951. if ( ( count-- ) <= 0 ) {
  16952. //** Triangulate: ERROR - probable bad polygon!
  16953. //throw ( "Warning, unable to triangulate polygon!" );
  16954. //return null;
  16955. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16956. console.log( "Warning, unable to triangulate polygon!" );
  16957. if ( indices ) return vertIndices;
  16958. return result;
  16959. }
  16960. /* three consecutive vertices in current polygon, <u,v,w> */
  16961. u = v; if ( nv <= u ) u = 0; /* previous */
  16962. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16963. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16964. if ( snip( contour, u, v, w, nv, verts ) ) {
  16965. var a, b, c, s, t;
  16966. /* true names of the vertices */
  16967. a = verts[ u ];
  16968. b = verts[ v ];
  16969. c = verts[ w ];
  16970. /* output Triangle */
  16971. result.push( [ contour[ a ],
  16972. contour[ b ],
  16973. contour[ c ] ] );
  16974. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16975. /* remove v from the remaining polygon */
  16976. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16977. verts[ s ] = verts[ t ];
  16978. }
  16979. nv--;
  16980. /* reset error detection counter */
  16981. count = 2 * nv;
  16982. }
  16983. }
  16984. if ( indices ) return vertIndices;
  16985. return result;
  16986. };
  16987. // calculate area of the contour polygon
  16988. var area = function ( contour ) {
  16989. var n = contour.length;
  16990. var a = 0.0;
  16991. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16992. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16993. }
  16994. return a * 0.5;
  16995. };
  16996. var snip = function ( contour, u, v, w, n, verts ) {
  16997. var p;
  16998. var ax, ay, bx, by;
  16999. var cx, cy, px, py;
  17000. ax = contour[ verts[ u ] ].x;
  17001. ay = contour[ verts[ u ] ].y;
  17002. bx = contour[ verts[ v ] ].x;
  17003. by = contour[ verts[ v ] ].y;
  17004. cx = contour[ verts[ w ] ].x;
  17005. cy = contour[ verts[ w ] ].y;
  17006. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  17007. var aX, aY, bX, bY, cX, cY;
  17008. var apx, apy, bpx, bpy, cpx, cpy;
  17009. var cCROSSap, bCROSScp, aCROSSbp;
  17010. aX = cx - bx; aY = cy - by;
  17011. bX = ax - cx; bY = ay - cy;
  17012. cX = bx - ax; cY = by - ay;
  17013. for ( p = 0; p < n; p++ ) {
  17014. px = contour[ verts[ p ] ].x
  17015. py = contour[ verts[ p ] ].y
  17016. if ( ( (px === ax) && (py === ay) ) ||
  17017. ( (px === bx) && (py === by) ) ||
  17018. ( (px === cx) && (py === cy) ) ) continue;
  17019. apx = px - ax; apy = py - ay;
  17020. bpx = px - bx; bpy = py - by;
  17021. cpx = px - cx; cpy = py - cy;
  17022. // see if p is inside triangle abc
  17023. aCROSSbp = aX*bpy - aY*bpx;
  17024. cCROSSap = cX*apy - cY*apx;
  17025. bCROSScp = bX*cpy - bY*cpx;
  17026. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  17027. }
  17028. return true;
  17029. };
  17030. namespace.Triangulate = process;
  17031. namespace.Triangulate.area = area;
  17032. return namespace;
  17033. })(THREE.FontUtils);
  17034. // To use the typeface.js face files, hook up the API
  17035. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  17036. THREE.typeface_js = self._typeface_js;
  17037. /**
  17038. * @author zz85 / http://www.lab4games.net/zz85/blog
  17039. * Extensible curve object
  17040. *
  17041. * Some common of Curve methods
  17042. * .getPoint(t), getTangent(t)
  17043. * .getPointAt(u), getTagentAt(u)
  17044. * .getPoints(), .getSpacedPoints()
  17045. * .getLength()
  17046. * .updateArcLengths()
  17047. *
  17048. * This following classes subclasses THREE.Curve:
  17049. *
  17050. * -- 2d classes --
  17051. * THREE.LineCurve
  17052. * THREE.QuadraticBezierCurve
  17053. * THREE.CubicBezierCurve
  17054. * THREE.SplineCurve
  17055. * THREE.ArcCurve
  17056. * THREE.EllipseCurve
  17057. *
  17058. * -- 3d classes --
  17059. * THREE.LineCurve3
  17060. * THREE.QuadraticBezierCurve3
  17061. * THREE.CubicBezierCurve3
  17062. * THREE.SplineCurve3
  17063. * THREE.ClosedSplineCurve3
  17064. *
  17065. * A series of curves can be represented as a THREE.CurvePath
  17066. *
  17067. **/
  17068. /**************************************************************
  17069. * Abstract Curve base class
  17070. **************************************************************/
  17071. THREE.Curve = function () {
  17072. };
  17073. // Virtual base class method to overwrite and implement in subclasses
  17074. // - t [0 .. 1]
  17075. THREE.Curve.prototype.getPoint = function ( t ) {
  17076. console.log( "Warning, getPoint() not implemented!" );
  17077. return null;
  17078. };
  17079. // Get point at relative position in curve according to arc length
  17080. // - u [0 .. 1]
  17081. THREE.Curve.prototype.getPointAt = function ( u ) {
  17082. var t = this.getUtoTmapping( u );
  17083. return this.getPoint( t );
  17084. };
  17085. // Get sequence of points using getPoint( t )
  17086. THREE.Curve.prototype.getPoints = function ( divisions ) {
  17087. if ( !divisions ) divisions = 5;
  17088. var d, pts = [];
  17089. for ( d = 0; d <= divisions; d ++ ) {
  17090. pts.push( this.getPoint( d / divisions ) );
  17091. }
  17092. return pts;
  17093. };
  17094. // Get sequence of points using getPointAt( u )
  17095. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  17096. if ( !divisions ) divisions = 5;
  17097. var d, pts = [];
  17098. for ( d = 0; d <= divisions; d ++ ) {
  17099. pts.push( this.getPointAt( d / divisions ) );
  17100. }
  17101. return pts;
  17102. };
  17103. // Get total curve arc length
  17104. THREE.Curve.prototype.getLength = function () {
  17105. var lengths = this.getLengths();
  17106. return lengths[ lengths.length - 1 ];
  17107. };
  17108. // Get list of cumulative segment lengths
  17109. THREE.Curve.prototype.getLengths = function ( divisions ) {
  17110. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  17111. if ( this.cacheArcLengths
  17112. && ( this.cacheArcLengths.length == divisions + 1 )
  17113. && !this.needsUpdate) {
  17114. //console.log( "cached", this.cacheArcLengths );
  17115. return this.cacheArcLengths;
  17116. }
  17117. this.needsUpdate = false;
  17118. var cache = [];
  17119. var current, last = this.getPoint( 0 );
  17120. var p, sum = 0;
  17121. cache.push( 0 );
  17122. for ( p = 1; p <= divisions; p ++ ) {
  17123. current = this.getPoint ( p / divisions );
  17124. sum += current.distanceTo( last );
  17125. cache.push( sum );
  17126. last = current;
  17127. }
  17128. this.cacheArcLengths = cache;
  17129. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  17130. };
  17131. THREE.Curve.prototype.updateArcLengths = function() {
  17132. this.needsUpdate = true;
  17133. this.getLengths();
  17134. };
  17135. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  17136. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  17137. var arcLengths = this.getLengths();
  17138. var i = 0, il = arcLengths.length;
  17139. var targetArcLength; // The targeted u distance value to get
  17140. if ( distance ) {
  17141. targetArcLength = distance;
  17142. } else {
  17143. targetArcLength = u * arcLengths[ il - 1 ];
  17144. }
  17145. //var time = Date.now();
  17146. // binary search for the index with largest value smaller than target u distance
  17147. var low = 0, high = il - 1, comparison;
  17148. while ( low <= high ) {
  17149. 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
  17150. comparison = arcLengths[ i ] - targetArcLength;
  17151. if ( comparison < 0 ) {
  17152. low = i + 1;
  17153. continue;
  17154. } else if ( comparison > 0 ) {
  17155. high = i - 1;
  17156. continue;
  17157. } else {
  17158. high = i;
  17159. break;
  17160. // DONE
  17161. }
  17162. }
  17163. i = high;
  17164. //console.log('b' , i, low, high, Date.now()- time);
  17165. if ( arcLengths[ i ] == targetArcLength ) {
  17166. var t = i / ( il - 1 );
  17167. return t;
  17168. }
  17169. // we could get finer grain at lengths, or use simple interpolatation between two points
  17170. var lengthBefore = arcLengths[ i ];
  17171. var lengthAfter = arcLengths[ i + 1 ];
  17172. var segmentLength = lengthAfter - lengthBefore;
  17173. // determine where we are between the 'before' and 'after' points
  17174. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17175. // add that fractional amount to t
  17176. var t = ( i + segmentFraction ) / ( il -1 );
  17177. return t;
  17178. };
  17179. // Returns a unit vector tangent at t
  17180. // In case any sub curve does not implement its tangent derivation,
  17181. // 2 points a small delta apart will be used to find its gradient
  17182. // which seems to give a reasonable approximation
  17183. THREE.Curve.prototype.getTangent = function( t ) {
  17184. var delta = 0.0001;
  17185. var t1 = t - delta;
  17186. var t2 = t + delta;
  17187. // Capping in case of danger
  17188. if ( t1 < 0 ) t1 = 0;
  17189. if ( t2 > 1 ) t2 = 1;
  17190. var pt1 = this.getPoint( t1 );
  17191. var pt2 = this.getPoint( t2 );
  17192. var vec = pt2.clone().sub(pt1);
  17193. return vec.normalize();
  17194. };
  17195. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17196. var t = this.getUtoTmapping( u );
  17197. return this.getTangent( t );
  17198. };
  17199. /**************************************************************
  17200. * Utils
  17201. **************************************************************/
  17202. THREE.Curve.Utils = {
  17203. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17204. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17205. },
  17206. // Puay Bing, thanks for helping with this derivative!
  17207. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17208. return -3 * p0 * (1 - t) * (1 - t) +
  17209. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17210. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17211. 3 * t * t * p3;
  17212. },
  17213. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17214. // To check if my formulas are correct
  17215. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17216. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17217. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17218. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17219. return h00 + h10 + h01 + h11;
  17220. },
  17221. // Catmull-Rom
  17222. interpolate: function( p0, p1, p2, p3, t ) {
  17223. var v0 = ( p2 - p0 ) * 0.5;
  17224. var v1 = ( p3 - p1 ) * 0.5;
  17225. var t2 = t * t;
  17226. var t3 = t * t2;
  17227. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17228. }
  17229. };
  17230. // TODO: Transformation for Curves?
  17231. /**************************************************************
  17232. * 3D Curves
  17233. **************************************************************/
  17234. // A Factory method for creating new curve subclasses
  17235. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17236. constructor.prototype = Object.create( THREE.Curve.prototype );
  17237. constructor.prototype.getPoint = getPointFunc;
  17238. return constructor;
  17239. };
  17240. /**
  17241. * @author zz85 / http://www.lab4games.net/zz85/blog
  17242. *
  17243. **/
  17244. /**************************************************************
  17245. * Curved Path - a curve path is simply a array of connected
  17246. * curves, but retains the api of a curve
  17247. **************************************************************/
  17248. THREE.CurvePath = function () {
  17249. this.curves = [];
  17250. this.bends = [];
  17251. this.autoClose = false; // Automatically closes the path
  17252. };
  17253. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17254. THREE.CurvePath.prototype.add = function ( curve ) {
  17255. this.curves.push( curve );
  17256. };
  17257. THREE.CurvePath.prototype.checkConnection = function() {
  17258. // TODO
  17259. // If the ending of curve is not connected to the starting
  17260. // or the next curve, then, this is not a real path
  17261. };
  17262. THREE.CurvePath.prototype.closePath = function() {
  17263. // TODO Test
  17264. // and verify for vector3 (needs to implement equals)
  17265. // Add a line curve if start and end of lines are not connected
  17266. var startPoint = this.curves[0].getPoint(0);
  17267. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17268. if (!startPoint.equals(endPoint)) {
  17269. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17270. }
  17271. };
  17272. // To get accurate point with reference to
  17273. // entire path distance at time t,
  17274. // following has to be done:
  17275. // 1. Length of each sub path have to be known
  17276. // 2. Locate and identify type of curve
  17277. // 3. Get t for the curve
  17278. // 4. Return curve.getPointAt(t')
  17279. THREE.CurvePath.prototype.getPoint = function( t ) {
  17280. var d = t * this.getLength();
  17281. var curveLengths = this.getCurveLengths();
  17282. var i = 0, diff, curve;
  17283. // To think about boundaries points.
  17284. while ( i < curveLengths.length ) {
  17285. if ( curveLengths[ i ] >= d ) {
  17286. diff = curveLengths[ i ] - d;
  17287. curve = this.curves[ i ];
  17288. var u = 1 - diff / curve.getLength();
  17289. return curve.getPointAt( u );
  17290. break;
  17291. }
  17292. i ++;
  17293. }
  17294. return null;
  17295. // loop where sum != 0, sum > d , sum+1 <d
  17296. };
  17297. /*
  17298. THREE.CurvePath.prototype.getTangent = function( t ) {
  17299. };*/
  17300. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17301. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17302. // getPoint() depends on getLength
  17303. THREE.CurvePath.prototype.getLength = function() {
  17304. var lens = this.getCurveLengths();
  17305. return lens[ lens.length - 1 ];
  17306. };
  17307. // Compute lengths and cache them
  17308. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17309. THREE.CurvePath.prototype.getCurveLengths = function() {
  17310. // We use cache values if curves and cache array are same length
  17311. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17312. return this.cacheLengths;
  17313. };
  17314. // Get length of subsurve
  17315. // Push sums into cached array
  17316. var lengths = [], sums = 0;
  17317. var i, il = this.curves.length;
  17318. for ( i = 0; i < il; i ++ ) {
  17319. sums += this.curves[ i ].getLength();
  17320. lengths.push( sums );
  17321. }
  17322. this.cacheLengths = lengths;
  17323. return lengths;
  17324. };
  17325. // Returns min and max coordinates
  17326. THREE.CurvePath.prototype.getBoundingBox = function () {
  17327. var points = this.getPoints();
  17328. var maxX, maxY, maxZ;
  17329. var minX, minY, minZ;
  17330. maxX = maxY = Number.NEGATIVE_INFINITY;
  17331. minX = minY = Number.POSITIVE_INFINITY;
  17332. var p, i, il, sum;
  17333. var v3 = points[0] instanceof THREE.Vector3;
  17334. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17335. for ( i = 0, il = points.length; i < il; i ++ ) {
  17336. p = points[ i ];
  17337. if ( p.x > maxX ) maxX = p.x;
  17338. else if ( p.x < minX ) minX = p.x;
  17339. if ( p.y > maxY ) maxY = p.y;
  17340. else if ( p.y < minY ) minY = p.y;
  17341. if ( v3 ) {
  17342. if ( p.z > maxZ ) maxZ = p.z;
  17343. else if ( p.z < minZ ) minZ = p.z;
  17344. }
  17345. sum.add( p );
  17346. }
  17347. var ret = {
  17348. minX: minX,
  17349. minY: minY,
  17350. maxX: maxX,
  17351. maxY: maxY
  17352. };
  17353. if ( v3 ) {
  17354. ret.maxZ = maxZ;
  17355. ret.minZ = minZ;
  17356. }
  17357. return ret;
  17358. };
  17359. /**************************************************************
  17360. * Create Geometries Helpers
  17361. **************************************************************/
  17362. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17363. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17364. var pts = this.getPoints( divisions, true );
  17365. return this.createGeometry( pts );
  17366. };
  17367. // Generate geometry from equidistance sampling along the path
  17368. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17369. var pts = this.getSpacedPoints( divisions, true );
  17370. return this.createGeometry( pts );
  17371. };
  17372. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17373. var geometry = new THREE.Geometry();
  17374. for ( var i = 0; i < points.length; i ++ ) {
  17375. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17376. }
  17377. return geometry;
  17378. };
  17379. /**************************************************************
  17380. * Bend / Wrap Helper Methods
  17381. **************************************************************/
  17382. // Wrap path / Bend modifiers?
  17383. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17384. this.bends.push( bendpath );
  17385. };
  17386. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17387. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17388. var i, il;
  17389. if ( !bends ) {
  17390. bends = this.bends;
  17391. }
  17392. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17393. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17394. }
  17395. return oldPts;
  17396. };
  17397. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17398. var oldPts = this.getSpacedPoints( segments );
  17399. var i, il;
  17400. if ( !bends ) {
  17401. bends = this.bends;
  17402. }
  17403. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17404. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17405. }
  17406. return oldPts;
  17407. };
  17408. // This returns getPoints() bend/wrapped around the contour of a path.
  17409. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17410. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17411. var bounds = this.getBoundingBox();
  17412. var i, il, p, oldX, oldY, xNorm;
  17413. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17414. p = oldPts[ i ];
  17415. oldX = p.x;
  17416. oldY = p.y;
  17417. xNorm = oldX / bounds.maxX;
  17418. // If using actual distance, for length > path, requires line extrusions
  17419. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17420. xNorm = path.getUtoTmapping( xNorm, oldX );
  17421. // check for out of bounds?
  17422. var pathPt = path.getPoint( xNorm );
  17423. var normal = path.getTangent( xNorm );
  17424. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  17425. p.x = pathPt.x + normal.x;
  17426. p.y = pathPt.y + normal.y;
  17427. }
  17428. return oldPts;
  17429. };
  17430. /**
  17431. * @author alteredq / http://alteredqualia.com/
  17432. */
  17433. THREE.Gyroscope = function () {
  17434. THREE.Object3D.call( this );
  17435. };
  17436. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17437. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17438. this.matrixAutoUpdate && this.updateMatrix();
  17439. // update matrixWorld
  17440. if ( this.matrixWorldNeedsUpdate || force ) {
  17441. if ( this.parent ) {
  17442. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17443. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17444. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17445. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17446. } else {
  17447. this.matrixWorld.copy( this.matrix );
  17448. }
  17449. this.matrixWorldNeedsUpdate = false;
  17450. force = true;
  17451. }
  17452. // update children
  17453. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17454. this.children[ i ].updateMatrixWorld( force );
  17455. }
  17456. };
  17457. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17458. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17459. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17460. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17461. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17462. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17463. /**
  17464. * @author zz85 / http://www.lab4games.net/zz85/blog
  17465. * Creates free form 2d path using series of points, lines or curves.
  17466. *
  17467. **/
  17468. THREE.Path = function ( points ) {
  17469. THREE.CurvePath.call(this);
  17470. this.actions = [];
  17471. if ( points ) {
  17472. this.fromPoints( points );
  17473. }
  17474. };
  17475. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17476. THREE.PathActions = {
  17477. MOVE_TO: 'moveTo',
  17478. LINE_TO: 'lineTo',
  17479. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17480. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17481. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17482. ARC: 'arc', // Circle
  17483. ELLIPSE: 'ellipse'
  17484. };
  17485. // TODO Clean up PATH API
  17486. // Create path using straight lines to connect all points
  17487. // - vectors: array of Vector2
  17488. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17489. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17490. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17491. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17492. };
  17493. };
  17494. // startPath() endPath()?
  17495. THREE.Path.prototype.moveTo = function ( x, y ) {
  17496. var args = Array.prototype.slice.call( arguments );
  17497. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17498. };
  17499. THREE.Path.prototype.lineTo = function ( x, y ) {
  17500. var args = Array.prototype.slice.call( arguments );
  17501. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17502. var x0 = lastargs[ lastargs.length - 2 ];
  17503. var y0 = lastargs[ lastargs.length - 1 ];
  17504. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17505. this.curves.push( curve );
  17506. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17507. };
  17508. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17509. var args = Array.prototype.slice.call( arguments );
  17510. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17511. var x0 = lastargs[ lastargs.length - 2 ];
  17512. var y0 = lastargs[ lastargs.length - 1 ];
  17513. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17514. new THREE.Vector2( aCPx, aCPy ),
  17515. new THREE.Vector2( aX, aY ) );
  17516. this.curves.push( curve );
  17517. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17518. };
  17519. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17520. aCP2x, aCP2y,
  17521. aX, aY ) {
  17522. var args = Array.prototype.slice.call( arguments );
  17523. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17524. var x0 = lastargs[ lastargs.length - 2 ];
  17525. var y0 = lastargs[ lastargs.length - 1 ];
  17526. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17527. new THREE.Vector2( aCP1x, aCP1y ),
  17528. new THREE.Vector2( aCP2x, aCP2y ),
  17529. new THREE.Vector2( aX, aY ) );
  17530. this.curves.push( curve );
  17531. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17532. };
  17533. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17534. var args = Array.prototype.slice.call( arguments );
  17535. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17536. var x0 = lastargs[ lastargs.length - 2 ];
  17537. var y0 = lastargs[ lastargs.length - 1 ];
  17538. //---
  17539. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17540. Array.prototype.push.apply( npts, pts );
  17541. var curve = new THREE.SplineCurve( npts );
  17542. this.curves.push( curve );
  17543. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17544. };
  17545. // FUTURE: Change the API or follow canvas API?
  17546. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17547. aStartAngle, aEndAngle, aClockwise ) {
  17548. var lastargs = this.actions[ this.actions.length - 1].args;
  17549. var x0 = lastargs[ lastargs.length - 2 ];
  17550. var y0 = lastargs[ lastargs.length - 1 ];
  17551. this.absarc(aX + x0, aY + y0, aRadius,
  17552. aStartAngle, aEndAngle, aClockwise );
  17553. };
  17554. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17555. aStartAngle, aEndAngle, aClockwise ) {
  17556. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17557. };
  17558. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17559. aStartAngle, aEndAngle, aClockwise ) {
  17560. var lastargs = this.actions[ this.actions.length - 1].args;
  17561. var x0 = lastargs[ lastargs.length - 2 ];
  17562. var y0 = lastargs[ lastargs.length - 1 ];
  17563. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17564. aStartAngle, aEndAngle, aClockwise );
  17565. };
  17566. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17567. aStartAngle, aEndAngle, aClockwise ) {
  17568. var args = Array.prototype.slice.call( arguments );
  17569. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17570. aStartAngle, aEndAngle, aClockwise );
  17571. this.curves.push( curve );
  17572. var lastPoint = curve.getPoint(1);
  17573. args.push(lastPoint.x);
  17574. args.push(lastPoint.y);
  17575. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17576. };
  17577. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17578. if ( ! divisions ) divisions = 40;
  17579. var points = [];
  17580. for ( var i = 0; i < divisions; i ++ ) {
  17581. points.push( this.getPoint( i / divisions ) );
  17582. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17583. }
  17584. // if ( closedPath ) {
  17585. //
  17586. // points.push( points[ 0 ] );
  17587. //
  17588. // }
  17589. return points;
  17590. };
  17591. /* Return an array of vectors based on contour of the path */
  17592. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17593. if (this.useSpacedPoints) {
  17594. console.log('tata');
  17595. return this.getSpacedPoints( divisions, closedPath );
  17596. }
  17597. divisions = divisions || 12;
  17598. var points = [];
  17599. var i, il, item, action, args;
  17600. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17601. laste, j,
  17602. t, tx, ty;
  17603. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17604. item = this.actions[ i ];
  17605. action = item.action;
  17606. args = item.args;
  17607. switch( action ) {
  17608. case THREE.PathActions.MOVE_TO:
  17609. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17610. break;
  17611. case THREE.PathActions.LINE_TO:
  17612. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17613. break;
  17614. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17615. cpx = args[ 2 ];
  17616. cpy = args[ 3 ];
  17617. cpx1 = args[ 0 ];
  17618. cpy1 = args[ 1 ];
  17619. if ( points.length > 0 ) {
  17620. laste = points[ points.length - 1 ];
  17621. cpx0 = laste.x;
  17622. cpy0 = laste.y;
  17623. } else {
  17624. laste = this.actions[ i - 1 ].args;
  17625. cpx0 = laste[ laste.length - 2 ];
  17626. cpy0 = laste[ laste.length - 1 ];
  17627. }
  17628. for ( j = 1; j <= divisions; j ++ ) {
  17629. t = j / divisions;
  17630. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17631. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17632. points.push( new THREE.Vector2( tx, ty ) );
  17633. }
  17634. break;
  17635. case THREE.PathActions.BEZIER_CURVE_TO:
  17636. cpx = args[ 4 ];
  17637. cpy = args[ 5 ];
  17638. cpx1 = args[ 0 ];
  17639. cpy1 = args[ 1 ];
  17640. cpx2 = args[ 2 ];
  17641. cpy2 = args[ 3 ];
  17642. if ( points.length > 0 ) {
  17643. laste = points[ points.length - 1 ];
  17644. cpx0 = laste.x;
  17645. cpy0 = laste.y;
  17646. } else {
  17647. laste = this.actions[ i - 1 ].args;
  17648. cpx0 = laste[ laste.length - 2 ];
  17649. cpy0 = laste[ laste.length - 1 ];
  17650. }
  17651. for ( j = 1; j <= divisions; j ++ ) {
  17652. t = j / divisions;
  17653. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17654. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17655. points.push( new THREE.Vector2( tx, ty ) );
  17656. }
  17657. break;
  17658. case THREE.PathActions.CSPLINE_THRU:
  17659. laste = this.actions[ i - 1 ].args;
  17660. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17661. var spts = [ last ];
  17662. var n = divisions * args[ 0 ].length;
  17663. spts = spts.concat( args[ 0 ] );
  17664. var spline = new THREE.SplineCurve( spts );
  17665. for ( j = 1; j <= n; j ++ ) {
  17666. points.push( spline.getPointAt( j / n ) ) ;
  17667. }
  17668. break;
  17669. case THREE.PathActions.ARC:
  17670. var aX = args[ 0 ], aY = args[ 1 ],
  17671. aRadius = args[ 2 ],
  17672. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17673. aClockwise = !!args[ 5 ];
  17674. var deltaAngle = aEndAngle - aStartAngle;
  17675. var angle;
  17676. var tdivisions = divisions * 2;
  17677. for ( j = 1; j <= tdivisions; j ++ ) {
  17678. t = j / tdivisions;
  17679. if ( ! aClockwise ) {
  17680. t = 1 - t;
  17681. }
  17682. angle = aStartAngle + t * deltaAngle;
  17683. tx = aX + aRadius * Math.cos( angle );
  17684. ty = aY + aRadius * Math.sin( angle );
  17685. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17686. points.push( new THREE.Vector2( tx, ty ) );
  17687. }
  17688. //console.log(points);
  17689. break;
  17690. case THREE.PathActions.ELLIPSE:
  17691. var aX = args[ 0 ], aY = args[ 1 ],
  17692. xRadius = args[ 2 ],
  17693. yRadius = args[ 3 ],
  17694. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17695. aClockwise = !!args[ 6 ];
  17696. var deltaAngle = aEndAngle - aStartAngle;
  17697. var angle;
  17698. var tdivisions = divisions * 2;
  17699. for ( j = 1; j <= tdivisions; j ++ ) {
  17700. t = j / tdivisions;
  17701. if ( ! aClockwise ) {
  17702. t = 1 - t;
  17703. }
  17704. angle = aStartAngle + t * deltaAngle;
  17705. tx = aX + xRadius * Math.cos( angle );
  17706. ty = aY + yRadius * Math.sin( angle );
  17707. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17708. points.push( new THREE.Vector2( tx, ty ) );
  17709. }
  17710. //console.log(points);
  17711. break;
  17712. } // end switch
  17713. }
  17714. // Normalize to remove the closing point by default.
  17715. var lastPoint = points[ points.length - 1];
  17716. var EPSILON = 0.0000000001;
  17717. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17718. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17719. points.splice( points.length - 1, 1);
  17720. if ( closedPath ) {
  17721. points.push( points[ 0 ] );
  17722. }
  17723. return points;
  17724. };
  17725. // Breaks path into shapes
  17726. THREE.Path.prototype.toShapes = function( isCCW ) {
  17727. function isPointInsidePolygon( inPt, inPolygon ) {
  17728. var EPSILON = 0.0000000001;
  17729. var polyLen = inPolygon.length;
  17730. // inPt on polygon contour => immediate success or
  17731. // toggling of inside/outside at every single! intersection point of an edge
  17732. // with the horizontal line through inPt, left of inPt
  17733. // not counting lowerY endpoints of edges and whole edges on that line
  17734. var inside = false;
  17735. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  17736. var edgeLowPt = inPolygon[ p ];
  17737. var edgeHighPt = inPolygon[ q ];
  17738. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  17739. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  17740. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  17741. if ( edgeDy < 0 ) {
  17742. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  17743. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  17744. }
  17745. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  17746. if ( inPt.y == edgeLowPt.y ) {
  17747. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  17748. // continue; // no intersection or edgeLowPt => doesn't count !!!
  17749. } else {
  17750. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  17751. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  17752. if ( perpEdge < 0 ) continue;
  17753. inside = !inside; // true intersection left of inPt
  17754. }
  17755. } else { // parallel or colinear
  17756. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  17757. // egde lies on the same horizontal line as inPt
  17758. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  17759. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  17760. // continue;
  17761. }
  17762. }
  17763. return inside;
  17764. }
  17765. var i, il, item, action, args;
  17766. var subPaths = [], lastPath = new THREE.Path();
  17767. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17768. item = this.actions[ i ];
  17769. args = item.args;
  17770. action = item.action;
  17771. if ( action == THREE.PathActions.MOVE_TO ) {
  17772. if ( lastPath.actions.length != 0 ) {
  17773. subPaths.push( lastPath );
  17774. lastPath = new THREE.Path();
  17775. }
  17776. }
  17777. lastPath[ action ].apply( lastPath, args );
  17778. }
  17779. if ( lastPath.actions.length != 0 ) {
  17780. subPaths.push( lastPath );
  17781. }
  17782. // console.log(subPaths);
  17783. if ( subPaths.length == 0 ) return [];
  17784. var solid, tmpPath, tmpShape, shapes = [];
  17785. if ( subPaths.length == 1) {
  17786. tmpPath = subPaths[0];
  17787. tmpShape = new THREE.Shape();
  17788. tmpShape.actions = tmpPath.actions;
  17789. tmpShape.curves = tmpPath.curves;
  17790. shapes.push( tmpShape );
  17791. return shapes;
  17792. }
  17793. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17794. holesFirst = isCCW ? !holesFirst : holesFirst;
  17795. // console.log("Holes first", holesFirst);
  17796. var betterShapeHoles = [];
  17797. var newShapes = [];
  17798. var newShapeHoles = [];
  17799. var mainIdx = 0;
  17800. var tmpPoints;
  17801. newShapes[mainIdx] = undefined;
  17802. newShapeHoles[mainIdx] = [];
  17803. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17804. tmpPath = subPaths[ i ];
  17805. tmpPoints = tmpPath.getPoints();
  17806. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  17807. solid = isCCW ? !solid : solid;
  17808. if ( solid ) {
  17809. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  17810. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  17811. newShapes[mainIdx].s.actions = tmpPath.actions;
  17812. newShapes[mainIdx].s.curves = tmpPath.curves;
  17813. if ( holesFirst ) mainIdx++;
  17814. newShapeHoles[mainIdx] = [];
  17815. //console.log('cw', i);
  17816. } else {
  17817. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  17818. //console.log('ccw', i);
  17819. }
  17820. }
  17821. if ( newShapes.length > 1 ) {
  17822. var ambigious = false;
  17823. var toChange = [];
  17824. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17825. betterShapeHoles[sIdx] = [];
  17826. }
  17827. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  17828. var sh = newShapes[sIdx];
  17829. var sho = newShapeHoles[sIdx];
  17830. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  17831. var ho = sho[hIdx];
  17832. var hole_unassigned = true;
  17833. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  17834. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  17835. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  17836. if ( hole_unassigned ) {
  17837. hole_unassigned = false;
  17838. betterShapeHoles[s2Idx].push( ho );
  17839. } else {
  17840. ambigious = true;
  17841. }
  17842. }
  17843. }
  17844. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  17845. }
  17846. }
  17847. // console.log("ambigious: ", ambigious);
  17848. if ( toChange.length > 0 ) {
  17849. // console.log("to change: ", toChange);
  17850. if (! ambigious) newShapeHoles = betterShapeHoles;
  17851. }
  17852. }
  17853. var tmpHoles, j, jl;
  17854. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  17855. tmpShape = newShapes[i].s;
  17856. shapes.push( tmpShape );
  17857. tmpHoles = newShapeHoles[i];
  17858. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  17859. tmpShape.holes.push( tmpHoles[j].h );
  17860. }
  17861. }
  17862. //console.log("shape", shapes);
  17863. return shapes;
  17864. };
  17865. /**
  17866. * @author zz85 / http://www.lab4games.net/zz85/blog
  17867. * Defines a 2d shape plane using paths.
  17868. **/
  17869. // STEP 1 Create a path.
  17870. // STEP 2 Turn path into shape.
  17871. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17872. // STEP 3a - Extract points from each shape, turn to vertices
  17873. // STEP 3b - Triangulate each shape, add faces.
  17874. THREE.Shape = function () {
  17875. THREE.Path.apply( this, arguments );
  17876. this.holes = [];
  17877. };
  17878. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17879. // Convenience method to return ExtrudeGeometry
  17880. THREE.Shape.prototype.extrude = function ( options ) {
  17881. var extruded = new THREE.ExtrudeGeometry( this, options );
  17882. return extruded;
  17883. };
  17884. // Convenience method to return ShapeGeometry
  17885. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17886. var geometry = new THREE.ShapeGeometry( this, options );
  17887. return geometry;
  17888. };
  17889. // Get points of holes
  17890. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17891. var i, il = this.holes.length, holesPts = [];
  17892. for ( i = 0; i < il; i ++ ) {
  17893. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17894. }
  17895. return holesPts;
  17896. };
  17897. // Get points of holes (spaced by regular distance)
  17898. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17899. var i, il = this.holes.length, holesPts = [];
  17900. for ( i = 0; i < il; i ++ ) {
  17901. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17902. }
  17903. return holesPts;
  17904. };
  17905. // Get points of shape and holes (keypoints based on segments parameter)
  17906. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17907. return {
  17908. shape: this.getTransformedPoints( divisions ),
  17909. holes: this.getPointsHoles( divisions )
  17910. };
  17911. };
  17912. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17913. if (this.useSpacedPoints) {
  17914. return this.extractAllSpacedPoints(divisions);
  17915. }
  17916. return this.extractAllPoints(divisions);
  17917. };
  17918. //
  17919. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17920. //
  17921. // return {
  17922. //
  17923. // shape: this.transform( bend, divisions ),
  17924. // holes: this.getPointsHoles( divisions, bend )
  17925. //
  17926. // };
  17927. //
  17928. // };
  17929. // Get points of shape and holes (spaced by regular distance)
  17930. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17931. return {
  17932. shape: this.getTransformedSpacedPoints( divisions ),
  17933. holes: this.getSpacedPointsHoles( divisions )
  17934. };
  17935. };
  17936. /**************************************************************
  17937. * Utils
  17938. **************************************************************/
  17939. THREE.Shape.Utils = {
  17940. triangulateShape: function ( contour, holes ) {
  17941. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  17942. // inOtherPt needs to be colinear to the inSegment
  17943. if ( inSegPt1.x != inSegPt2.x ) {
  17944. if ( inSegPt1.x < inSegPt2.x ) {
  17945. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17946. } else {
  17947. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17948. }
  17949. } else {
  17950. if ( inSegPt1.y < inSegPt2.y ) {
  17951. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17952. } else {
  17953. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17954. }
  17955. }
  17956. }
  17957. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17958. var EPSILON = 0.0000000001;
  17959. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17960. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17961. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17962. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17963. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17964. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17965. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17966. var perpSeg2;
  17967. if ( limit > 0 ) {
  17968. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17969. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17970. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17971. } else {
  17972. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17973. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17974. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17975. }
  17976. // i.e. to reduce rounding errors
  17977. // intersection at endpoint of segment#1?
  17978. if ( perpSeg2 == 0 ) {
  17979. if ( ( inExcludeAdjacentSegs ) &&
  17980. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17981. return [ inSeg1Pt1 ];
  17982. }
  17983. if ( perpSeg2 == limit ) {
  17984. if ( ( inExcludeAdjacentSegs ) &&
  17985. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17986. return [ inSeg1Pt2 ];
  17987. }
  17988. // intersection at endpoint of segment#2?
  17989. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  17990. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  17991. // return real intersection point
  17992. var factorSeg1 = perpSeg2 / limit;
  17993. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17994. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17995. } else { // parallel or colinear
  17996. if ( ( perpSeg1 != 0 ) ||
  17997. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  17998. // they are collinear or degenerate
  17999. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  18000. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  18001. // both segments are points
  18002. if ( seg1Pt && seg2Pt ) {
  18003. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  18004. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  18005. return [ inSeg1Pt1 ]; // they are the same point
  18006. }
  18007. // segment#1 is a single point
  18008. if ( seg1Pt ) {
  18009. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  18010. return [ inSeg1Pt1 ];
  18011. }
  18012. // segment#2 is a single point
  18013. if ( seg2Pt ) {
  18014. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  18015. return [ inSeg2Pt1 ];
  18016. }
  18017. // they are collinear segments, which might overlap
  18018. var seg1min, seg1max, seg1minVal, seg1maxVal;
  18019. var seg2min, seg2max, seg2minVal, seg2maxVal;
  18020. if (seg1dx != 0) { // the segments are NOT on a vertical line
  18021. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  18022. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  18023. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  18024. } else {
  18025. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  18026. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  18027. }
  18028. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  18029. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  18030. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  18031. } else {
  18032. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  18033. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  18034. }
  18035. } else { // the segments are on a vertical line
  18036. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  18037. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  18038. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  18039. } else {
  18040. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  18041. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  18042. }
  18043. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  18044. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  18045. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  18046. } else {
  18047. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  18048. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  18049. }
  18050. }
  18051. if ( seg1minVal <= seg2minVal ) {
  18052. if ( seg1maxVal < seg2minVal ) return [];
  18053. if ( seg1maxVal == seg2minVal ) {
  18054. if ( inExcludeAdjacentSegs ) return [];
  18055. return [ seg2min ];
  18056. }
  18057. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  18058. return [ seg2min, seg2max ];
  18059. } else {
  18060. if ( seg1minVal > seg2maxVal ) return [];
  18061. if ( seg1minVal == seg2maxVal ) {
  18062. if ( inExcludeAdjacentSegs ) return [];
  18063. return [ seg1min ];
  18064. }
  18065. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  18066. return [ seg1min, seg2max ];
  18067. }
  18068. }
  18069. }
  18070. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  18071. // The order of legs is important
  18072. var EPSILON = 0.0000000001;
  18073. // translation of all points, so that Vertex is at (0,0)
  18074. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  18075. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  18076. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  18077. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  18078. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  18079. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  18080. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  18081. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  18082. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  18083. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  18084. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  18085. } else { // main angle > 180 deg.
  18086. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  18087. }
  18088. } else { // angle == 180 deg.
  18089. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  18090. return ( from2otherAngle > 0 );
  18091. }
  18092. }
  18093. function removeHoles( contour, holes ) {
  18094. var shape = contour.concat(); // work on this shape
  18095. var hole;
  18096. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  18097. // Check if hole point lies within angle around shape point
  18098. var lastShapeIdx = shape.length - 1;
  18099. var prevShapeIdx = inShapeIdx - 1;
  18100. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  18101. var nextShapeIdx = inShapeIdx + 1;
  18102. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  18103. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  18104. if (! insideAngle ) {
  18105. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  18106. return false;
  18107. }
  18108. // Check if shape point lies within angle around hole point
  18109. var lastHoleIdx = hole.length - 1;
  18110. var prevHoleIdx = inHoleIdx - 1;
  18111. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  18112. var nextHoleIdx = inHoleIdx + 1;
  18113. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  18114. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  18115. if (! insideAngle ) {
  18116. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  18117. return false;
  18118. }
  18119. return true;
  18120. }
  18121. function intersectsShapeEdge( inShapePt, inHolePt ) {
  18122. // checks for intersections with shape edges
  18123. var sIdx, nextIdx, intersection;
  18124. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  18125. nextIdx = sIdx+1; nextIdx %= shape.length;
  18126. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  18127. if ( intersection.length > 0 ) return true;
  18128. }
  18129. return false;
  18130. }
  18131. var indepHoles = [];
  18132. function intersectsHoleEdge( inShapePt, inHolePt ) {
  18133. // checks for intersections with hole edges
  18134. var ihIdx, chkHole,
  18135. hIdx, nextIdx, intersection;
  18136. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  18137. chkHole = holes[indepHoles[ihIdx]];
  18138. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  18139. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  18140. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  18141. if ( intersection.length > 0 ) return true;
  18142. }
  18143. }
  18144. return false;
  18145. }
  18146. var holeIndex, shapeIndex,
  18147. shapePt, holePt,
  18148. holeIdx, cutKey, failedCuts = [],
  18149. tmpShape1, tmpShape2,
  18150. tmpHole1, tmpHole2;
  18151. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18152. indepHoles.push( h );
  18153. }
  18154. var counter = indepHoles.length * 2;
  18155. while ( indepHoles.length > 0 ) {
  18156. counter --;
  18157. if ( counter < 0 ) {
  18158. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  18159. break;
  18160. }
  18161. // search for shape-vertex and hole-vertex,
  18162. // which can be connected without intersections
  18163. for ( shapeIndex = 0; shapeIndex < shape.length; shapeIndex++ ) {
  18164. shapePt = shape[ shapeIndex ];
  18165. holeIndex = -1;
  18166. // search for hole which can be reached without intersections
  18167. for ( var h = 0; h < indepHoles.length; h ++ ) {
  18168. holeIdx = indepHoles[h];
  18169. // prevent multiple checks
  18170. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  18171. if ( failedCuts[cutKey] !== undefined ) continue;
  18172. hole = holes[holeIdx];
  18173. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  18174. holePt = hole[ h2 ];
  18175. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  18176. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  18177. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  18178. holeIndex = h2;
  18179. indepHoles.splice(h,1);
  18180. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  18181. tmpShape2 = shape.slice( shapeIndex );
  18182. tmpHole1 = hole.slice( holeIndex );
  18183. tmpHole2 = hole.slice( 0, holeIndex+1 );
  18184. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  18185. // Debug only, to show the selected cuts
  18186. // glob_CutLines.push( [ shapePt, holePt ] );
  18187. break;
  18188. }
  18189. if ( holeIndex >= 0 ) break; // hole-vertex found
  18190. failedCuts[cutKey] = true; // remember failure
  18191. }
  18192. if ( holeIndex >= 0 ) break; // hole-vertex found
  18193. }
  18194. }
  18195. return shape; /* shape with no holes */
  18196. }
  18197. var i, il, f, face,
  18198. key, index,
  18199. allPointsMap = {};
  18200. // 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.
  18201. var allpoints = contour.concat();
  18202. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18203. Array.prototype.push.apply( allpoints, holes[h] );
  18204. }
  18205. //console.log( "allpoints",allpoints, allpoints.length );
  18206. // prepare all points map
  18207. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  18208. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  18209. if ( allPointsMap[ key ] !== undefined ) {
  18210. console.log( "Duplicate point", key );
  18211. }
  18212. allPointsMap[ key ] = i;
  18213. }
  18214. // remove holes by cutting paths to holes and adding them to the shape
  18215. var shapeWithoutHoles = removeHoles( contour, holes );
  18216. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  18217. //console.log( "triangles",triangles, triangles.length );
  18218. // check all face vertices against all points map
  18219. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  18220. face = triangles[ i ];
  18221. for ( f = 0; f < 3; f ++ ) {
  18222. key = face[ f ].x + ":" + face[ f ].y;
  18223. index = allPointsMap[ key ];
  18224. if ( index !== undefined ) {
  18225. face[ f ] = index;
  18226. }
  18227. }
  18228. }
  18229. return triangles.concat();
  18230. },
  18231. isClockWise: function ( pts ) {
  18232. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  18233. },
  18234. // Bezier Curves formulas obtained from
  18235. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18236. // Quad Bezier Functions
  18237. b2p0: function ( t, p ) {
  18238. var k = 1 - t;
  18239. return k * k * p;
  18240. },
  18241. b2p1: function ( t, p ) {
  18242. return 2 * ( 1 - t ) * t * p;
  18243. },
  18244. b2p2: function ( t, p ) {
  18245. return t * t * p;
  18246. },
  18247. b2: function ( t, p0, p1, p2 ) {
  18248. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  18249. },
  18250. // Cubic Bezier Functions
  18251. b3p0: function ( t, p ) {
  18252. var k = 1 - t;
  18253. return k * k * k * p;
  18254. },
  18255. b3p1: function ( t, p ) {
  18256. var k = 1 - t;
  18257. return 3 * k * k * t * p;
  18258. },
  18259. b3p2: function ( t, p ) {
  18260. var k = 1 - t;
  18261. return 3 * k * t * t * p;
  18262. },
  18263. b3p3: function ( t, p ) {
  18264. return t * t * t * p;
  18265. },
  18266. b3: function ( t, p0, p1, p2, p3 ) {
  18267. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  18268. }
  18269. };
  18270. /**************************************************************
  18271. * Line
  18272. **************************************************************/
  18273. THREE.LineCurve = function ( v1, v2 ) {
  18274. this.v1 = v1;
  18275. this.v2 = v2;
  18276. };
  18277. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  18278. THREE.LineCurve.prototype.getPoint = function ( t ) {
  18279. var point = this.v2.clone().sub(this.v1);
  18280. point.multiplyScalar( t ).add( this.v1 );
  18281. return point;
  18282. };
  18283. // Line curve is linear, so we can overwrite default getPointAt
  18284. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  18285. return this.getPoint( u );
  18286. };
  18287. THREE.LineCurve.prototype.getTangent = function( t ) {
  18288. var tangent = this.v2.clone().sub(this.v1);
  18289. return tangent.normalize();
  18290. };
  18291. /**************************************************************
  18292. * Quadratic Bezier curve
  18293. **************************************************************/
  18294. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  18295. this.v0 = v0;
  18296. this.v1 = v1;
  18297. this.v2 = v2;
  18298. };
  18299. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18300. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18301. var tx, ty;
  18302. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18303. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18304. return new THREE.Vector2( tx, ty );
  18305. };
  18306. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18307. var tx, ty;
  18308. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  18309. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  18310. // returns unit vector
  18311. var tangent = new THREE.Vector2( tx, ty );
  18312. tangent.normalize();
  18313. return tangent;
  18314. };
  18315. /**************************************************************
  18316. * Cubic Bezier curve
  18317. **************************************************************/
  18318. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  18319. this.v0 = v0;
  18320. this.v1 = v1;
  18321. this.v2 = v2;
  18322. this.v3 = v3;
  18323. };
  18324. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18325. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  18326. var tx, ty;
  18327. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18328. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18329. return new THREE.Vector2( tx, ty );
  18330. };
  18331. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18332. var tx, ty;
  18333. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18334. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18335. var tangent = new THREE.Vector2( tx, ty );
  18336. tangent.normalize();
  18337. return tangent;
  18338. };
  18339. /**************************************************************
  18340. * Spline curve
  18341. **************************************************************/
  18342. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18343. this.points = (points == undefined) ? [] : points;
  18344. };
  18345. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18346. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18347. var v = new THREE.Vector2();
  18348. var c = [];
  18349. var points = this.points, point, intPoint, weight;
  18350. point = ( points.length - 1 ) * t;
  18351. intPoint = Math.floor( point );
  18352. weight = point - intPoint;
  18353. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18354. c[ 1 ] = intPoint;
  18355. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18356. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18357. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18358. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18359. return v;
  18360. };
  18361. /**************************************************************
  18362. * Ellipse curve
  18363. **************************************************************/
  18364. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  18365. this.aX = aX;
  18366. this.aY = aY;
  18367. this.xRadius = xRadius;
  18368. this.yRadius = yRadius;
  18369. this.aStartAngle = aStartAngle;
  18370. this.aEndAngle = aEndAngle;
  18371. this.aClockwise = aClockwise;
  18372. };
  18373. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18374. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18375. var angle;
  18376. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18377. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  18378. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  18379. if ( this.aClockwise === true ) {
  18380. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  18381. } else {
  18382. angle = this.aStartAngle + t * deltaAngle;
  18383. }
  18384. var tx = this.aX + this.xRadius * Math.cos( angle );
  18385. var ty = this.aY + this.yRadius * Math.sin( angle );
  18386. return new THREE.Vector2( tx, ty );
  18387. };
  18388. /**************************************************************
  18389. * Arc curve
  18390. **************************************************************/
  18391. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18392. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18393. };
  18394. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18395. /**************************************************************
  18396. * Line3D
  18397. **************************************************************/
  18398. THREE.LineCurve3 = THREE.Curve.create(
  18399. function ( v1, v2 ) {
  18400. this.v1 = v1;
  18401. this.v2 = v2;
  18402. },
  18403. function ( t ) {
  18404. var r = new THREE.Vector3();
  18405. r.subVectors( this.v2, this.v1 ); // diff
  18406. r.multiplyScalar( t );
  18407. r.add( this.v1 );
  18408. return r;
  18409. }
  18410. );
  18411. /**************************************************************
  18412. * Quadratic Bezier 3D curve
  18413. **************************************************************/
  18414. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18415. function ( v0, v1, v2 ) {
  18416. this.v0 = v0;
  18417. this.v1 = v1;
  18418. this.v2 = v2;
  18419. },
  18420. function ( t ) {
  18421. var tx, ty, tz;
  18422. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18423. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18424. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18425. return new THREE.Vector3( tx, ty, tz );
  18426. }
  18427. );
  18428. /**************************************************************
  18429. * Cubic Bezier 3D curve
  18430. **************************************************************/
  18431. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18432. function ( v0, v1, v2, v3 ) {
  18433. this.v0 = v0;
  18434. this.v1 = v1;
  18435. this.v2 = v2;
  18436. this.v3 = v3;
  18437. },
  18438. function ( t ) {
  18439. var tx, ty, tz;
  18440. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18441. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18442. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18443. return new THREE.Vector3( tx, ty, tz );
  18444. }
  18445. );
  18446. /**************************************************************
  18447. * Spline 3D curve
  18448. **************************************************************/
  18449. THREE.SplineCurve3 = THREE.Curve.create(
  18450. function ( points /* array of Vector3 */) {
  18451. this.points = (points == undefined) ? [] : points;
  18452. },
  18453. function ( t ) {
  18454. var v = new THREE.Vector3();
  18455. var c = [];
  18456. var points = this.points, point, intPoint, weight;
  18457. point = ( points.length - 1 ) * t;
  18458. intPoint = Math.floor( point );
  18459. weight = point - intPoint;
  18460. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18461. c[ 1 ] = intPoint;
  18462. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18463. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18464. var pt0 = points[ c[0] ],
  18465. pt1 = points[ c[1] ],
  18466. pt2 = points[ c[2] ],
  18467. pt3 = points[ c[3] ];
  18468. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18469. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18470. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18471. return v;
  18472. }
  18473. );
  18474. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18475. // var v = new THREE.Vector3();
  18476. // var c = [];
  18477. // var points = this.points, point, intPoint, weight;
  18478. // point = ( points.length - 1 ) * t;
  18479. // intPoint = Math.floor( point );
  18480. // weight = point - intPoint;
  18481. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18482. // c[ 1 ] = intPoint;
  18483. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18484. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18485. // var pt0 = points[ c[0] ],
  18486. // pt1 = points[ c[1] ],
  18487. // pt2 = points[ c[2] ],
  18488. // pt3 = points[ c[3] ];
  18489. // // t = weight;
  18490. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18491. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18492. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18493. // return v;
  18494. // }
  18495. /**************************************************************
  18496. * Closed Spline 3D curve
  18497. **************************************************************/
  18498. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18499. function ( points /* array of Vector3 */) {
  18500. this.points = (points == undefined) ? [] : points;
  18501. },
  18502. function ( t ) {
  18503. var v = new THREE.Vector3();
  18504. var c = [];
  18505. var points = this.points, point, intPoint, weight;
  18506. point = ( points.length - 0 ) * t;
  18507. // This needs to be from 0-length +1
  18508. intPoint = Math.floor( point );
  18509. weight = point - intPoint;
  18510. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18511. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18512. c[ 1 ] = ( intPoint ) % points.length;
  18513. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18514. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18515. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18516. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18517. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18518. return v;
  18519. }
  18520. );
  18521. /**
  18522. * @author mikael emtinger / http://gomo.se/
  18523. */
  18524. THREE.AnimationHandler = ( function () {
  18525. var playing = [];
  18526. var library = {};
  18527. var that = {};
  18528. that.update = function ( deltaTimeMS ) {
  18529. for ( var i = 0; i < playing.length; i ++ ) {
  18530. playing[ i ].update( deltaTimeMS );
  18531. }
  18532. };
  18533. that.addToUpdate = function ( animation ) {
  18534. if ( playing.indexOf( animation ) === -1 ) {
  18535. playing.push( animation );
  18536. }
  18537. };
  18538. that.removeFromUpdate = function ( animation ) {
  18539. var index = playing.indexOf( animation );
  18540. if ( index !== -1 ) {
  18541. playing.splice( index, 1 );
  18542. }
  18543. };
  18544. that.add = function ( data ) {
  18545. if ( library[ data.name ] !== undefined ) {
  18546. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18547. }
  18548. library[ data.name ] = data;
  18549. initData( data );
  18550. };
  18551. that.remove = function ( name ) {
  18552. if ( library[ name ] === undefined ) {
  18553. console.log( "THREE.AnimationHandler.add: Warning! " + name + " doesn't exists in library. Doing nothing." );
  18554. }
  18555. library[ name ] = undefined;
  18556. };
  18557. that.get = function ( name ) {
  18558. if ( typeof name === "string" ) {
  18559. if ( library[ name ] ) {
  18560. return library[ name ];
  18561. } else {
  18562. return null;
  18563. }
  18564. } else {
  18565. // todo: add simple tween library
  18566. }
  18567. };
  18568. that.parse = function ( root ) {
  18569. // setup hierarchy
  18570. var hierarchy = [];
  18571. if ( root instanceof THREE.SkinnedMesh ) {
  18572. for ( var b = 0; b < root.bones.length; b++ ) {
  18573. hierarchy.push( root.bones[ b ] );
  18574. }
  18575. } else {
  18576. parseRecurseHierarchy( root, hierarchy );
  18577. }
  18578. return hierarchy;
  18579. };
  18580. var parseRecurseHierarchy = function ( root, hierarchy ) {
  18581. hierarchy.push( root );
  18582. for ( var c = 0; c < root.children.length; c++ )
  18583. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18584. }
  18585. var initData = function ( data ) {
  18586. if ( data.initialized === true )
  18587. return;
  18588. // loop through all keys
  18589. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  18590. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18591. // remove minus times
  18592. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  18593. data.hierarchy[ h ].keys[ k ].time = 0;
  18594. }
  18595. // create quaternions
  18596. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18597. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18598. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18599. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  18600. }
  18601. }
  18602. // prepare morph target keys
  18603. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18604. // get all used
  18605. var usedMorphTargets = {};
  18606. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18607. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18608. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18609. usedMorphTargets[ morphTargetName ] = -1;
  18610. }
  18611. }
  18612. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18613. // set all used on all frames
  18614. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18615. var influences = {};
  18616. for ( var morphTargetName in usedMorphTargets ) {
  18617. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18618. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18619. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18620. break;
  18621. }
  18622. }
  18623. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18624. influences[ morphTargetName ] = 0;
  18625. }
  18626. }
  18627. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18628. }
  18629. }
  18630. // remove all keys that are on the same time
  18631. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18632. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18633. data.hierarchy[ h ].keys.splice( k, 1 );
  18634. k --;
  18635. }
  18636. }
  18637. // set index
  18638. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18639. data.hierarchy[ h ].keys[ k ].index = k;
  18640. }
  18641. }
  18642. data.initialized = true;
  18643. };
  18644. // interpolation types
  18645. that.LINEAR = 0;
  18646. that.CATMULLROM = 1;
  18647. that.CATMULLROM_FORWARD = 2;
  18648. return that;
  18649. }() );
  18650. /**
  18651. * @author mikael emtinger / http://gomo.se/
  18652. * @author mrdoob / http://mrdoob.com/
  18653. * @author alteredq / http://alteredqualia.com/
  18654. */
  18655. THREE.Animation = function ( root, name ) {
  18656. this.root = root;
  18657. this.data = THREE.AnimationHandler.get( name );
  18658. this.hierarchy = THREE.AnimationHandler.parse( root );
  18659. this.currentTime = 0;
  18660. this.timeScale = 1;
  18661. this.isPlaying = false;
  18662. this.isPaused = true;
  18663. this.loop = true;
  18664. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18665. };
  18666. THREE.Animation.prototype.play = function ( startTime ) {
  18667. this.currentTime = startTime !== undefined ? startTime : 0;
  18668. if ( this.isPlaying === false ) {
  18669. this.isPlaying = true;
  18670. this.reset();
  18671. this.update( 0 );
  18672. }
  18673. this.isPaused = false;
  18674. THREE.AnimationHandler.addToUpdate( this );
  18675. };
  18676. THREE.Animation.prototype.pause = function() {
  18677. if ( this.isPaused === true ) {
  18678. THREE.AnimationHandler.addToUpdate( this );
  18679. } else {
  18680. THREE.AnimationHandler.removeFromUpdate( this );
  18681. }
  18682. this.isPaused = !this.isPaused;
  18683. };
  18684. THREE.Animation.prototype.stop = function() {
  18685. this.isPlaying = false;
  18686. this.isPaused = false;
  18687. THREE.AnimationHandler.removeFromUpdate( this );
  18688. };
  18689. THREE.Animation.prototype.reset = function () {
  18690. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18691. var object = this.hierarchy[ h ];
  18692. object.matrixAutoUpdate = true;
  18693. if ( object.animationCache === undefined ) {
  18694. object.animationCache = {};
  18695. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18696. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18697. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18698. }
  18699. var prevKey = object.animationCache.prevKey;
  18700. var nextKey = object.animationCache.nextKey;
  18701. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18702. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18703. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18704. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18705. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18706. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18707. }
  18708. };
  18709. THREE.Animation.prototype.update = (function(){
  18710. var points = [];
  18711. var target = new THREE.Vector3();
  18712. // Catmull-Rom spline
  18713. var interpolateCatmullRom = function ( points, scale ) {
  18714. var c = [], v3 = [],
  18715. point, intPoint, weight, w2, w3,
  18716. pa, pb, pc, pd;
  18717. point = ( points.length - 1 ) * scale;
  18718. intPoint = Math.floor( point );
  18719. weight = point - intPoint;
  18720. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18721. c[ 1 ] = intPoint;
  18722. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18723. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18724. pa = points[ c[ 0 ] ];
  18725. pb = points[ c[ 1 ] ];
  18726. pc = points[ c[ 2 ] ];
  18727. pd = points[ c[ 3 ] ];
  18728. w2 = weight * weight;
  18729. w3 = weight * w2;
  18730. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18731. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18732. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18733. return v3;
  18734. };
  18735. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18736. var v0 = ( p2 - p0 ) * 0.5,
  18737. v1 = ( p3 - p1 ) * 0.5;
  18738. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18739. };
  18740. return function ( delta ) {
  18741. if ( this.isPlaying === false ) return;
  18742. this.currentTime += delta * this.timeScale;
  18743. //
  18744. var vector;
  18745. var types = [ "pos", "rot", "scl" ];
  18746. var duration = this.data.length;
  18747. if ( this.loop === true && this.currentTime > duration ) {
  18748. this.currentTime %= duration;
  18749. this.reset();
  18750. } else if ( this.loop === false && this.currentTime > duration ) {
  18751. this.stop();
  18752. return;
  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 animationCache = object.animationCache;
  18758. // loop through pos/rot/scl
  18759. for ( var t = 0; t < 3; t ++ ) {
  18760. // get keys
  18761. var type = types[ t ];
  18762. var prevKey = animationCache.prevKey[ type ];
  18763. var nextKey = animationCache.nextKey[ type ];
  18764. if ( nextKey.time <= this.currentTime ) {
  18765. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18766. nextKey = this.getNextKeyWith( type, h, 1 );
  18767. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18768. prevKey = nextKey;
  18769. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18770. }
  18771. animationCache.prevKey[ type ] = prevKey;
  18772. animationCache.nextKey[ type ] = nextKey;
  18773. }
  18774. object.matrixAutoUpdate = true;
  18775. object.matrixWorldNeedsUpdate = true;
  18776. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18777. var prevXYZ = prevKey[ type ];
  18778. var nextXYZ = nextKey[ type ];
  18779. if ( scale < 0 ) scale = 0;
  18780. if ( scale > 1 ) scale = 1;
  18781. // interpolate
  18782. if ( type === "pos" ) {
  18783. vector = object.position;
  18784. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18785. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18786. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18787. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18788. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18789. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18790. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18791. points[ 1 ] = prevXYZ;
  18792. points[ 2 ] = nextXYZ;
  18793. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18794. scale = scale * 0.33 + 0.33;
  18795. var currentPoint = interpolateCatmullRom( points, scale );
  18796. vector.x = currentPoint[ 0 ];
  18797. vector.y = currentPoint[ 1 ];
  18798. vector.z = currentPoint[ 2 ];
  18799. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18800. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  18801. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18802. target.sub( vector );
  18803. target.y = 0;
  18804. target.normalize();
  18805. var angle = Math.atan2( target.x, target.z );
  18806. object.rotation.set( 0, angle, 0 );
  18807. }
  18808. }
  18809. } else if ( type === "rot" ) {
  18810. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18811. } else if ( type === "scl" ) {
  18812. vector = object.scale;
  18813. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18814. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18815. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18816. }
  18817. }
  18818. }
  18819. };
  18820. })();
  18821. // Get next key with
  18822. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18823. var keys = this.data.hierarchy[ h ].keys;
  18824. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18825. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18826. key = key < keys.length - 1 ? key : keys.length - 1;
  18827. } else {
  18828. key = key % keys.length;
  18829. }
  18830. for ( ; key < keys.length; key++ ) {
  18831. if ( keys[ key ][ type ] !== undefined ) {
  18832. return keys[ key ];
  18833. }
  18834. }
  18835. return this.data.hierarchy[ h ].keys[ 0 ];
  18836. };
  18837. // Get previous key with
  18838. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18839. var keys = this.data.hierarchy[ h ].keys;
  18840. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18841. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18842. key = key > 0 ? key : 0;
  18843. } else {
  18844. key = key >= 0 ? key : key + keys.length;
  18845. }
  18846. for ( ; key >= 0; key -- ) {
  18847. if ( keys[ key ][ type ] !== undefined ) {
  18848. return keys[ key ];
  18849. }
  18850. }
  18851. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18852. };
  18853. /**
  18854. * @author mikael emtinger / http://gomo.se/
  18855. * @author mrdoob / http://mrdoob.com/
  18856. * @author alteredq / http://alteredqualia.com/
  18857. * @author khang duong
  18858. * @author erik kitson
  18859. */
  18860. THREE.KeyFrameAnimation = function ( root, data ) {
  18861. this.root = root;
  18862. this.data = THREE.AnimationHandler.get( data );
  18863. this.hierarchy = THREE.AnimationHandler.parse( root );
  18864. this.currentTime = 0;
  18865. this.timeScale = 0.001;
  18866. this.isPlaying = false;
  18867. this.isPaused = true;
  18868. this.loop = true;
  18869. // initialize to first keyframes
  18870. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18871. var keys = this.data.hierarchy[h].keys,
  18872. sids = this.data.hierarchy[h].sids,
  18873. obj = this.hierarchy[h];
  18874. if ( keys.length && sids ) {
  18875. for ( var s = 0; s < sids.length; s++ ) {
  18876. var sid = sids[ s ],
  18877. next = this.getNextKeyWith( sid, h, 0 );
  18878. if ( next ) {
  18879. next.apply( sid );
  18880. }
  18881. }
  18882. obj.matrixAutoUpdate = false;
  18883. this.data.hierarchy[h].node.updateMatrix();
  18884. obj.matrixWorldNeedsUpdate = true;
  18885. }
  18886. }
  18887. };
  18888. // Play
  18889. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  18890. this.currentTime = startTime !== undefined ? startTime : 0;
  18891. if ( this.isPlaying === false ) {
  18892. this.isPlaying = true;
  18893. // reset key cache
  18894. var h, hl = this.hierarchy.length,
  18895. object,
  18896. node;
  18897. for ( h = 0; h < hl; h++ ) {
  18898. object = this.hierarchy[ h ];
  18899. node = this.data.hierarchy[ h ];
  18900. if ( node.animationCache === undefined ) {
  18901. node.animationCache = {};
  18902. node.animationCache.prevKey = null;
  18903. node.animationCache.nextKey = null;
  18904. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18905. }
  18906. var keys = this.data.hierarchy[h].keys;
  18907. if (keys.length) {
  18908. node.animationCache.prevKey = keys[ 0 ];
  18909. node.animationCache.nextKey = keys[ 1 ];
  18910. this.startTime = Math.min( keys[0].time, this.startTime );
  18911. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18912. }
  18913. }
  18914. this.update( 0 );
  18915. }
  18916. this.isPaused = false;
  18917. THREE.AnimationHandler.addToUpdate( this );
  18918. };
  18919. // Pause
  18920. THREE.KeyFrameAnimation.prototype.pause = function() {
  18921. if( this.isPaused ) {
  18922. THREE.AnimationHandler.addToUpdate( this );
  18923. } else {
  18924. THREE.AnimationHandler.removeFromUpdate( this );
  18925. }
  18926. this.isPaused = !this.isPaused;
  18927. };
  18928. // Stop
  18929. THREE.KeyFrameAnimation.prototype.stop = function() {
  18930. this.isPlaying = false;
  18931. this.isPaused = false;
  18932. THREE.AnimationHandler.removeFromUpdate( this );
  18933. // reset JIT matrix and remove cache
  18934. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18935. var obj = this.hierarchy[ h ];
  18936. var node = this.data.hierarchy[ h ];
  18937. if ( node.animationCache !== undefined ) {
  18938. var original = node.animationCache.originalMatrix;
  18939. if( obj instanceof THREE.Bone ) {
  18940. original.copy( obj.skinMatrix );
  18941. obj.skinMatrix = original;
  18942. } else {
  18943. original.copy( obj.matrix );
  18944. obj.matrix = original;
  18945. }
  18946. delete node.animationCache;
  18947. }
  18948. }
  18949. };
  18950. // Update
  18951. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  18952. if ( this.isPlaying === false ) return;
  18953. this.currentTime += delta * this.timeScale;
  18954. //
  18955. var duration = this.data.length;
  18956. if ( this.loop === true && this.currentTime > duration ) {
  18957. this.currentTime %= duration;
  18958. }
  18959. this.currentTime = Math.min( this.currentTime, duration );
  18960. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18961. var object = this.hierarchy[ h ];
  18962. var node = this.data.hierarchy[ h ];
  18963. var keys = node.keys,
  18964. animationCache = node.animationCache;
  18965. if ( keys.length ) {
  18966. var prevKey = animationCache.prevKey;
  18967. var nextKey = animationCache.nextKey;
  18968. if ( nextKey.time <= this.currentTime ) {
  18969. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18970. prevKey = nextKey;
  18971. nextKey = keys[ prevKey.index + 1 ];
  18972. }
  18973. animationCache.prevKey = prevKey;
  18974. animationCache.nextKey = nextKey;
  18975. }
  18976. if ( nextKey.time >= this.currentTime ) {
  18977. prevKey.interpolate( nextKey, this.currentTime );
  18978. } else {
  18979. prevKey.interpolate( nextKey, nextKey.time );
  18980. }
  18981. this.data.hierarchy[ h ].node.updateMatrix();
  18982. object.matrixWorldNeedsUpdate = true;
  18983. }
  18984. }
  18985. };
  18986. // Get next key with
  18987. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18988. var keys = this.data.hierarchy[ h ].keys;
  18989. key = key % keys.length;
  18990. for ( ; key < keys.length; key++ ) {
  18991. if ( keys[ key ].hasTarget( sid ) ) {
  18992. return keys[ key ];
  18993. }
  18994. }
  18995. return keys[ 0 ];
  18996. };
  18997. // Get previous key with
  18998. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18999. var keys = this.data.hierarchy[ h ].keys;
  19000. key = key >= 0 ? key : key + keys.length;
  19001. for ( ; key >= 0; key-- ) {
  19002. if ( keys[ key ].hasTarget( sid ) ) {
  19003. return keys[ key ];
  19004. }
  19005. }
  19006. return keys[ keys.length - 1 ];
  19007. };
  19008. /**
  19009. * @author mrdoob / http://mrdoob.com
  19010. */
  19011. THREE.MorphAnimation = function ( mesh ) {
  19012. this.mesh = mesh;
  19013. this.frames = mesh.morphTargetInfluences.length;
  19014. this.currentTime = 0;
  19015. this.duration = 1000;
  19016. this.loop = true;
  19017. this.isPlaying = false;
  19018. };
  19019. THREE.MorphAnimation.prototype = {
  19020. play: function () {
  19021. this.isPlaying = true;
  19022. },
  19023. pause: function () {
  19024. this.isPlaying = false;
  19025. },
  19026. update: ( function () {
  19027. var lastFrame = 0;
  19028. var currentFrame = 0;
  19029. return function ( delta ) {
  19030. if ( this.isPlaying === false ) return;
  19031. this.currentTime += delta;
  19032. if ( this.loop === true && this.currentTime > this.duration ) {
  19033. this.currentTime %= this.duration;
  19034. }
  19035. this.currentTime = Math.min( this.currentTime, this.duration );
  19036. var interpolation = this.duration / this.frames;
  19037. var frame = Math.floor( this.currentTime / interpolation );
  19038. if ( frame != currentFrame ) {
  19039. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  19040. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  19041. this.mesh.morphTargetInfluences[ frame ] = 0;
  19042. lastFrame = currentFrame;
  19043. currentFrame = frame;
  19044. }
  19045. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  19046. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  19047. }
  19048. } )()
  19049. };
  19050. /**
  19051. * Camera for rendering cube maps
  19052. * - renders scene into axis-aligned cube
  19053. *
  19054. * @author alteredq / http://alteredqualia.com/
  19055. */
  19056. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  19057. THREE.Object3D.call( this );
  19058. var fov = 90, aspect = 1;
  19059. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19060. cameraPX.up.set( 0, -1, 0 );
  19061. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  19062. this.add( cameraPX );
  19063. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19064. cameraNX.up.set( 0, -1, 0 );
  19065. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  19066. this.add( cameraNX );
  19067. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19068. cameraPY.up.set( 0, 0, 1 );
  19069. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  19070. this.add( cameraPY );
  19071. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19072. cameraNY.up.set( 0, 0, -1 );
  19073. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  19074. this.add( cameraNY );
  19075. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19076. cameraPZ.up.set( 0, -1, 0 );
  19077. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  19078. this.add( cameraPZ );
  19079. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19080. cameraNZ.up.set( 0, -1, 0 );
  19081. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  19082. this.add( cameraNZ );
  19083. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  19084. this.updateCubeMap = function ( renderer, scene ) {
  19085. var renderTarget = this.renderTarget;
  19086. var generateMipmaps = renderTarget.generateMipmaps;
  19087. renderTarget.generateMipmaps = false;
  19088. renderTarget.activeCubeFace = 0;
  19089. renderer.render( scene, cameraPX, renderTarget );
  19090. renderTarget.activeCubeFace = 1;
  19091. renderer.render( scene, cameraNX, renderTarget );
  19092. renderTarget.activeCubeFace = 2;
  19093. renderer.render( scene, cameraPY, renderTarget );
  19094. renderTarget.activeCubeFace = 3;
  19095. renderer.render( scene, cameraNY, renderTarget );
  19096. renderTarget.activeCubeFace = 4;
  19097. renderer.render( scene, cameraPZ, renderTarget );
  19098. renderTarget.generateMipmaps = generateMipmaps;
  19099. renderTarget.activeCubeFace = 5;
  19100. renderer.render( scene, cameraNZ, renderTarget );
  19101. };
  19102. };
  19103. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  19104. /**
  19105. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19106. *
  19107. * A general perpose camera, for setting FOV, Lens Focal Length,
  19108. * and switching between perspective and orthographic views easily.
  19109. * Use this only if you do not wish to manage
  19110. * both a Orthographic and Perspective Camera
  19111. *
  19112. */
  19113. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  19114. THREE.Camera.call( this );
  19115. this.fov = fov;
  19116. this.left = -width / 2;
  19117. this.right = width / 2
  19118. this.top = height / 2;
  19119. this.bottom = -height / 2;
  19120. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  19121. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  19122. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  19123. this.zoom = 1;
  19124. this.toPerspective();
  19125. var aspect = width/height;
  19126. };
  19127. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  19128. THREE.CombinedCamera.prototype.toPerspective = function () {
  19129. // Switches to the Perspective Camera
  19130. this.near = this.cameraP.near;
  19131. this.far = this.cameraP.far;
  19132. this.cameraP.fov = this.fov / this.zoom ;
  19133. this.cameraP.updateProjectionMatrix();
  19134. this.projectionMatrix = this.cameraP.projectionMatrix;
  19135. this.inPerspectiveMode = true;
  19136. this.inOrthographicMode = false;
  19137. };
  19138. THREE.CombinedCamera.prototype.toOrthographic = function () {
  19139. // Switches to the Orthographic camera estimating viewport from Perspective
  19140. var fov = this.fov;
  19141. var aspect = this.cameraP.aspect;
  19142. var near = this.cameraP.near;
  19143. var far = this.cameraP.far;
  19144. // The size that we set is the mid plane of the viewing frustum
  19145. var hyperfocus = ( near + far ) / 2;
  19146. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  19147. var planeHeight = 2 * halfHeight;
  19148. var planeWidth = planeHeight * aspect;
  19149. var halfWidth = planeWidth / 2;
  19150. halfHeight /= this.zoom;
  19151. halfWidth /= this.zoom;
  19152. this.cameraO.left = -halfWidth;
  19153. this.cameraO.right = halfWidth;
  19154. this.cameraO.top = halfHeight;
  19155. this.cameraO.bottom = -halfHeight;
  19156. // this.cameraO.left = -farHalfWidth;
  19157. // this.cameraO.right = farHalfWidth;
  19158. // this.cameraO.top = farHalfHeight;
  19159. // this.cameraO.bottom = -farHalfHeight;
  19160. // this.cameraO.left = this.left / this.zoom;
  19161. // this.cameraO.right = this.right / this.zoom;
  19162. // this.cameraO.top = this.top / this.zoom;
  19163. // this.cameraO.bottom = this.bottom / this.zoom;
  19164. this.cameraO.updateProjectionMatrix();
  19165. this.near = this.cameraO.near;
  19166. this.far = this.cameraO.far;
  19167. this.projectionMatrix = this.cameraO.projectionMatrix;
  19168. this.inPerspectiveMode = false;
  19169. this.inOrthographicMode = true;
  19170. };
  19171. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  19172. this.cameraP.aspect = width / height;
  19173. this.left = -width / 2;
  19174. this.right = width / 2
  19175. this.top = height / 2;
  19176. this.bottom = -height / 2;
  19177. };
  19178. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  19179. this.fov = fov;
  19180. if ( this.inPerspectiveMode ) {
  19181. this.toPerspective();
  19182. } else {
  19183. this.toOrthographic();
  19184. }
  19185. };
  19186. // For mantaining similar API with PerspectiveCamera
  19187. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  19188. if ( this.inPerspectiveMode ) {
  19189. this.toPerspective();
  19190. } else {
  19191. this.toPerspective();
  19192. this.toOrthographic();
  19193. }
  19194. };
  19195. /*
  19196. * Uses Focal Length (in mm) to estimate and set FOV
  19197. * 35mm (fullframe) camera is used if frame size is not specified;
  19198. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  19199. */
  19200. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  19201. if ( frameHeight === undefined ) frameHeight = 24;
  19202. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  19203. this.setFov( fov );
  19204. return fov;
  19205. };
  19206. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  19207. this.zoom = zoom;
  19208. if ( this.inPerspectiveMode ) {
  19209. this.toPerspective();
  19210. } else {
  19211. this.toOrthographic();
  19212. }
  19213. };
  19214. THREE.CombinedCamera.prototype.toFrontView = function() {
  19215. this.rotation.x = 0;
  19216. this.rotation.y = 0;
  19217. this.rotation.z = 0;
  19218. // should we be modifing the matrix instead?
  19219. this.rotationAutoUpdate = false;
  19220. };
  19221. THREE.CombinedCamera.prototype.toBackView = function() {
  19222. this.rotation.x = 0;
  19223. this.rotation.y = Math.PI;
  19224. this.rotation.z = 0;
  19225. this.rotationAutoUpdate = false;
  19226. };
  19227. THREE.CombinedCamera.prototype.toLeftView = function() {
  19228. this.rotation.x = 0;
  19229. this.rotation.y = - Math.PI / 2;
  19230. this.rotation.z = 0;
  19231. this.rotationAutoUpdate = false;
  19232. };
  19233. THREE.CombinedCamera.prototype.toRightView = function() {
  19234. this.rotation.x = 0;
  19235. this.rotation.y = Math.PI / 2;
  19236. this.rotation.z = 0;
  19237. this.rotationAutoUpdate = false;
  19238. };
  19239. THREE.CombinedCamera.prototype.toTopView = function() {
  19240. this.rotation.x = - Math.PI / 2;
  19241. this.rotation.y = 0;
  19242. this.rotation.z = 0;
  19243. this.rotationAutoUpdate = false;
  19244. };
  19245. THREE.CombinedCamera.prototype.toBottomView = function() {
  19246. this.rotation.x = Math.PI / 2;
  19247. this.rotation.y = 0;
  19248. this.rotation.z = 0;
  19249. this.rotationAutoUpdate = false;
  19250. };
  19251. /**
  19252. * @author mrdoob / http://mrdoob.com/
  19253. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19254. */
  19255. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19256. THREE.Geometry.call( this );
  19257. this.parameters = {
  19258. width: width,
  19259. height: height,
  19260. depth: depth,
  19261. widthSegments: widthSegments,
  19262. heightSegments: heightSegments,
  19263. depthSegments: depthSegments
  19264. };
  19265. this.widthSegments = widthSegments || 1;
  19266. this.heightSegments = heightSegments || 1;
  19267. this.depthSegments = depthSegments || 1;
  19268. var scope = this;
  19269. var width_half = width / 2;
  19270. var height_half = height / 2;
  19271. var depth_half = depth / 2;
  19272. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  19273. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  19274. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  19275. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  19276. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  19277. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  19278. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19279. var w, ix, iy,
  19280. gridX = scope.widthSegments,
  19281. gridY = scope.heightSegments,
  19282. width_half = width / 2,
  19283. height_half = height / 2,
  19284. offset = scope.vertices.length;
  19285. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19286. w = 'z';
  19287. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19288. w = 'y';
  19289. gridY = scope.depthSegments;
  19290. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19291. w = 'x';
  19292. gridX = scope.depthSegments;
  19293. }
  19294. var gridX1 = gridX + 1,
  19295. gridY1 = gridY + 1,
  19296. segment_width = width / gridX,
  19297. segment_height = height / gridY,
  19298. normal = new THREE.Vector3();
  19299. normal[ w ] = depth > 0 ? 1 : - 1;
  19300. for ( iy = 0; iy < gridY1; iy ++ ) {
  19301. for ( ix = 0; ix < gridX1; ix ++ ) {
  19302. var vector = new THREE.Vector3();
  19303. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19304. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19305. vector[ w ] = depth;
  19306. scope.vertices.push( vector );
  19307. }
  19308. }
  19309. for ( iy = 0; iy < gridY; iy++ ) {
  19310. for ( ix = 0; ix < gridX; ix++ ) {
  19311. var a = ix + gridX1 * iy;
  19312. var b = ix + gridX1 * ( iy + 1 );
  19313. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19314. var d = ( ix + 1 ) + gridX1 * iy;
  19315. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  19316. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  19317. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  19318. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  19319. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  19320. face.normal.copy( normal );
  19321. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19322. face.materialIndex = materialIndex;
  19323. scope.faces.push( face );
  19324. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19325. face = new THREE.Face3( b + offset, c + offset, d + offset );
  19326. face.normal.copy( normal );
  19327. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19328. face.materialIndex = materialIndex;
  19329. scope.faces.push( face );
  19330. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19331. }
  19332. }
  19333. }
  19334. this.mergeVertices();
  19335. };
  19336. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19337. /**
  19338. * @author hughes
  19339. */
  19340. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  19341. THREE.BufferGeometry.call( this );
  19342. this.parameters = {
  19343. radius: radius,
  19344. segments: segments,
  19345. thetaStart: thetaStart,
  19346. thetaLength: thetaLength
  19347. };
  19348. radius = radius || 50;
  19349. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19350. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19351. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19352. //
  19353. var length = segments + 2;
  19354. var indices = new Uint16Array( ( segments + 1 ) * 3 );
  19355. var vertices = new Float32Array( length * 3 );
  19356. var normals = new Float32Array( length * 3 );
  19357. var uvs = new Float32Array( length * 2 );
  19358. normals[ 2 ] = 1;
  19359. uvs[ 0 ] = 0.5;
  19360. uvs[ 1 ] = 0.5;
  19361. var offset = 3, offset2 = 2;
  19362. for ( var i = 0; i <= segments; i ++ ) {
  19363. indices[ offset ] = i + 1;
  19364. indices[ offset + 1 ] = i + 2;
  19365. indices[ offset + 2 ] = 0;
  19366. var segment = thetaStart + i / segments * thetaLength;
  19367. var x = radius * Math.cos( segment );
  19368. var y = radius * Math.sin( segment );
  19369. vertices[ offset ] = x;
  19370. vertices[ offset + 1 ] = y;
  19371. normals[ offset + 2 ] = 1;
  19372. uvs[ offset2 ] = ( x / radius + 1 ) / 2;
  19373. uvs[ offset2 + 1 ] = ( y / radius + 1 ) / 2;
  19374. offset += 3;
  19375. offset2 += 2;
  19376. }
  19377. for ( var i = 1; i <= segments; i ++ ) {
  19378. indices[ offset ] = i;
  19379. indices[ offset + 1 ] = i + 1;
  19380. indices[ offset + 2 ] = 0;
  19381. }
  19382. this.attributes[ 'index' ] = { array: indices, itemSize: 1 };
  19383. this.attributes[ 'position' ] = { array: vertices, itemSize: 3 };
  19384. this.attributes[ 'normal' ] = { array: normals, itemSize: 3 };
  19385. this.attributes[ 'uv' ] = { array: uvs, itemSize: 2 };
  19386. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19387. };
  19388. THREE.CircleGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19389. // DEPRECATED
  19390. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19391. console.warn( 'DEPRECATED: THREE.CubeGeometry is deprecated. Use THREE.BoxGeometry instead.' );
  19392. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  19393. };
  19394. /**
  19395. * @author mrdoob / http://mrdoob.com/
  19396. */
  19397. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19398. THREE.Geometry.call( this );
  19399. this.parameters = {
  19400. radiusTop: radiusTop,
  19401. radiusBottom: radiusBottom,
  19402. height: height,
  19403. radialSegments: radialSegments,
  19404. heightSegments: heightSegments,
  19405. openEnded: openEnded
  19406. };
  19407. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19408. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19409. height = height !== undefined ? height : 100;
  19410. radialSegments = radialSegments || 8;
  19411. heightSegments = heightSegments || 1;
  19412. openEnded = openEnded !== undefined ? openEnded : false;
  19413. var heightHalf = height / 2;
  19414. var x, y, vertices = [], uvs = [];
  19415. for ( y = 0; y <= heightSegments; y ++ ) {
  19416. var verticesRow = [];
  19417. var uvsRow = [];
  19418. var v = y / heightSegments;
  19419. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19420. for ( x = 0; x <= radialSegments; x ++ ) {
  19421. var u = x / radialSegments;
  19422. var vertex = new THREE.Vector3();
  19423. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19424. vertex.y = - v * height + heightHalf;
  19425. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19426. this.vertices.push( vertex );
  19427. verticesRow.push( this.vertices.length - 1 );
  19428. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19429. }
  19430. vertices.push( verticesRow );
  19431. uvs.push( uvsRow );
  19432. }
  19433. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19434. var na, nb;
  19435. for ( x = 0; x < radialSegments; x ++ ) {
  19436. if ( radiusTop !== 0 ) {
  19437. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19438. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19439. } else {
  19440. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19441. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19442. }
  19443. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19444. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19445. for ( y = 0; y < heightSegments; y ++ ) {
  19446. var v1 = vertices[ y ][ x ];
  19447. var v2 = vertices[ y + 1 ][ x ];
  19448. var v3 = vertices[ y + 1 ][ x + 1 ];
  19449. var v4 = vertices[ y ][ x + 1 ];
  19450. var n1 = na.clone();
  19451. var n2 = na.clone();
  19452. var n3 = nb.clone();
  19453. var n4 = nb.clone();
  19454. var uv1 = uvs[ y ][ x ].clone();
  19455. var uv2 = uvs[ y + 1 ][ x ].clone();
  19456. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19457. var uv4 = uvs[ y ][ x + 1 ].clone();
  19458. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19459. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19460. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19461. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19462. }
  19463. }
  19464. // top cap
  19465. if ( openEnded === false && radiusTop > 0 ) {
  19466. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19467. for ( x = 0; x < radialSegments; x ++ ) {
  19468. var v1 = vertices[ 0 ][ x ];
  19469. var v2 = vertices[ 0 ][ x + 1 ];
  19470. var v3 = this.vertices.length - 1;
  19471. var n1 = new THREE.Vector3( 0, 1, 0 );
  19472. var n2 = new THREE.Vector3( 0, 1, 0 );
  19473. var n3 = new THREE.Vector3( 0, 1, 0 );
  19474. var uv1 = uvs[ 0 ][ x ].clone();
  19475. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19476. var uv3 = new THREE.Vector2( uv2.x, 0 );
  19477. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19478. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19479. }
  19480. }
  19481. // bottom cap
  19482. if ( openEnded === false && radiusBottom > 0 ) {
  19483. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19484. for ( x = 0; x < radialSegments; x ++ ) {
  19485. var v1 = vertices[ y ][ x + 1 ];
  19486. var v2 = vertices[ y ][ x ];
  19487. var v3 = this.vertices.length - 1;
  19488. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19489. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19490. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19491. var uv1 = uvs[ y ][ x + 1 ].clone();
  19492. var uv2 = uvs[ y ][ x ].clone();
  19493. var uv3 = new THREE.Vector2( uv2.x, 1 );
  19494. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19495. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19496. }
  19497. }
  19498. this.computeFaceNormals();
  19499. }
  19500. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19501. /**
  19502. * @author zz85 / http://www.lab4games.net/zz85/blog
  19503. *
  19504. * Creates extruded geometry from a path shape.
  19505. *
  19506. * parameters = {
  19507. *
  19508. * curveSegments: <int>, // number of points on the curves
  19509. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19510. * amount: <int>, // Depth to extrude the shape
  19511. *
  19512. * bevelEnabled: <bool>, // turn on bevel
  19513. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19514. * bevelSize: <float>, // how far from shape outline is bevel
  19515. * bevelSegments: <int>, // number of bevel layers
  19516. *
  19517. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19518. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19519. *
  19520. * material: <int> // material index for front and back faces
  19521. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19522. * uvGenerator: <Object> // object that provides UV generator functions
  19523. *
  19524. * }
  19525. **/
  19526. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19527. if ( typeof( shapes ) === "undefined" ) {
  19528. shapes = [];
  19529. return;
  19530. }
  19531. THREE.Geometry.call( this );
  19532. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19533. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19534. this.addShapeList( shapes, options );
  19535. this.computeFaceNormals();
  19536. // can't really use automatic vertex normals
  19537. // as then front and back sides get smoothed too
  19538. // should do separate smoothing just for sides
  19539. //this.computeVertexNormals();
  19540. //console.log( "took", ( Date.now() - startTime ) );
  19541. };
  19542. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19543. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19544. var sl = shapes.length;
  19545. for ( var s = 0; s < sl; s ++ ) {
  19546. var shape = shapes[ s ];
  19547. this.addShape( shape, options );
  19548. }
  19549. };
  19550. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19551. var amount = options.amount !== undefined ? options.amount : 100;
  19552. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19553. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19554. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19555. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19556. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19557. var steps = options.steps !== undefined ? options.steps : 1;
  19558. var extrudePath = options.extrudePath;
  19559. var extrudePts, extrudeByPath = false;
  19560. var material = options.material;
  19561. var extrudeMaterial = options.extrudeMaterial;
  19562. // Use default WorldUVGenerator if no UV generators are specified.
  19563. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19564. var shapebb = this.shapebb;
  19565. //shapebb = shape.getBoundingBox();
  19566. var splineTube, binormal, normal, position2;
  19567. if ( extrudePath ) {
  19568. extrudePts = extrudePath.getSpacedPoints( steps );
  19569. extrudeByPath = true;
  19570. bevelEnabled = false; // bevels not supported for path extrusion
  19571. // SETUP TNB variables
  19572. // Reuse TNB from TubeGeomtry for now.
  19573. // TODO1 - have a .isClosed in spline?
  19574. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19575. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19576. binormal = new THREE.Vector3();
  19577. normal = new THREE.Vector3();
  19578. position2 = new THREE.Vector3();
  19579. }
  19580. // Safeguards if bevels are not enabled
  19581. if ( ! bevelEnabled ) {
  19582. bevelSegments = 0;
  19583. bevelThickness = 0;
  19584. bevelSize = 0;
  19585. }
  19586. // Variables initalization
  19587. var ahole, h, hl; // looping of holes
  19588. var scope = this;
  19589. var bevelPoints = [];
  19590. var shapesOffset = this.vertices.length;
  19591. var shapePoints = shape.extractPoints( curveSegments );
  19592. var vertices = shapePoints.shape;
  19593. var holes = shapePoints.holes;
  19594. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19595. if ( reverse ) {
  19596. vertices = vertices.reverse();
  19597. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19598. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19599. ahole = holes[ h ];
  19600. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19601. holes[ h ] = ahole.reverse();
  19602. }
  19603. }
  19604. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19605. }
  19606. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19607. /* Vertices */
  19608. var contour = vertices; // vertices has all points but contour has only points of circumference
  19609. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19610. ahole = holes[ h ];
  19611. vertices = vertices.concat( ahole );
  19612. }
  19613. function scalePt2 ( pt, vec, size ) {
  19614. if ( !vec ) console.log( "die" );
  19615. return vec.clone().multiplyScalar( size ).add( pt );
  19616. }
  19617. var b, bs, t, z,
  19618. vert, vlen = vertices.length,
  19619. face, flen = faces.length,
  19620. cont, clen = contour.length;
  19621. // Find directions for point movement
  19622. var RAD_TO_DEGREES = 180 / Math.PI;
  19623. function getBevelVec( inPt, inPrev, inNext ) {
  19624. var EPSILON = 0.0000000001;
  19625. var sign = THREE.Math.sign;
  19626. // computes for inPt the corresponding point inPt' on a new contour
  19627. // shiftet by 1 unit (length of normalized vector) to the left
  19628. // if we walk along contour clockwise, this new contour is outside the old one
  19629. //
  19630. // inPt' is the intersection of the two lines parallel to the two
  19631. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19632. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19633. // good reading for geometry algorithms (here: line-line intersection)
  19634. // http://geomalgorithms.com/a05-_intersect-1.html
  19635. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19636. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19637. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19638. // check for colinear edges
  19639. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19640. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  19641. // length of vectors for normalizing
  19642. var v_prev_len = Math.sqrt( v_prev_lensq );
  19643. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19644. // shift adjacent points by unit vectors to the left
  19645. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19646. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19647. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19648. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19649. // scaling factor for v_prev to intersection point
  19650. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19651. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19652. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19653. // vector from inPt to intersection point
  19654. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19655. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19656. // Don't normalize!, otherwise sharp corners become ugly
  19657. // but prevent crazy spikes
  19658. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  19659. if ( v_trans_lensq <= 2 ) {
  19660. return new THREE.Vector2( v_trans_x, v_trans_y );
  19661. } else {
  19662. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19663. }
  19664. } else { // handle special case of colinear edges
  19665. var direction_eq = false; // assumes: opposite
  19666. if ( v_prev_x > EPSILON ) {
  19667. if ( v_next_x > EPSILON ) { direction_eq = true; }
  19668. } else {
  19669. if ( v_prev_x < -EPSILON ) {
  19670. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  19671. } else {
  19672. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  19673. }
  19674. }
  19675. if ( direction_eq ) {
  19676. // console.log("Warning: lines are a straight sequence");
  19677. v_trans_x = -v_prev_y;
  19678. v_trans_y = v_prev_x;
  19679. shrink_by = Math.sqrt( v_prev_lensq );
  19680. } else {
  19681. // console.log("Warning: lines are a straight spike");
  19682. v_trans_x = v_prev_x;
  19683. v_trans_y = v_prev_y;
  19684. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19685. }
  19686. }
  19687. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19688. }
  19689. var contourMovements = [];
  19690. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19691. if ( j === il ) j = 0;
  19692. if ( k === il ) k = 0;
  19693. // (j)---(i)---(k)
  19694. // console.log('i,j,k', i, j , k)
  19695. var pt_i = contour[ i ];
  19696. var pt_j = contour[ j ];
  19697. var pt_k = contour[ k ];
  19698. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19699. }
  19700. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19701. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19702. ahole = holes[ h ];
  19703. oneHoleMovements = [];
  19704. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19705. if ( j === il ) j = 0;
  19706. if ( k === il ) k = 0;
  19707. // (j)---(i)---(k)
  19708. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19709. }
  19710. holesMovements.push( oneHoleMovements );
  19711. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19712. }
  19713. // Loop bevelSegments, 1 for the front, 1 for the back
  19714. for ( b = 0; b < bevelSegments; b ++ ) {
  19715. //for ( b = bevelSegments; b > 0; b -- ) {
  19716. t = b / bevelSegments;
  19717. z = bevelThickness * ( 1 - t );
  19718. //z = bevelThickness * t;
  19719. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19720. //bs = bevelSize * t ; // linear
  19721. // contract shape
  19722. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19723. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19724. v( vert.x, vert.y, - z );
  19725. }
  19726. // expand holes
  19727. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19728. ahole = holes[ h ];
  19729. oneHoleMovements = holesMovements[ h ];
  19730. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19731. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19732. v( vert.x, vert.y, -z );
  19733. }
  19734. }
  19735. }
  19736. bs = bevelSize;
  19737. // Back facing vertices
  19738. for ( i = 0; i < vlen; i ++ ) {
  19739. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19740. if ( !extrudeByPath ) {
  19741. v( vert.x, vert.y, 0 );
  19742. } else {
  19743. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19744. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19745. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19746. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19747. v( position2.x, position2.y, position2.z );
  19748. }
  19749. }
  19750. // Add stepped vertices...
  19751. // Including front facing vertices
  19752. var s;
  19753. for ( s = 1; s <= steps; s ++ ) {
  19754. for ( i = 0; i < vlen; i ++ ) {
  19755. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19756. if ( !extrudeByPath ) {
  19757. v( vert.x, vert.y, amount / steps * s );
  19758. } else {
  19759. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19760. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19761. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19762. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19763. v( position2.x, position2.y, position2.z );
  19764. }
  19765. }
  19766. }
  19767. // Add bevel segments planes
  19768. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19769. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19770. t = b / bevelSegments;
  19771. z = bevelThickness * ( 1 - t );
  19772. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19773. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19774. // contract shape
  19775. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19776. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19777. v( vert.x, vert.y, amount + z );
  19778. }
  19779. // expand holes
  19780. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19781. ahole = holes[ h ];
  19782. oneHoleMovements = holesMovements[ h ];
  19783. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19784. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19785. if ( !extrudeByPath ) {
  19786. v( vert.x, vert.y, amount + z );
  19787. } else {
  19788. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19789. }
  19790. }
  19791. }
  19792. }
  19793. /* Faces */
  19794. // Top and bottom faces
  19795. buildLidFaces();
  19796. // Sides faces
  19797. buildSideFaces();
  19798. ///// Internal functions
  19799. function buildLidFaces() {
  19800. if ( bevelEnabled ) {
  19801. var layer = 0 ; // steps + 1
  19802. var offset = vlen * layer;
  19803. // Bottom faces
  19804. for ( i = 0; i < flen; i ++ ) {
  19805. face = faces[ i ];
  19806. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19807. }
  19808. layer = steps + bevelSegments * 2;
  19809. offset = vlen * layer;
  19810. // Top faces
  19811. for ( i = 0; i < flen; i ++ ) {
  19812. face = faces[ i ];
  19813. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19814. }
  19815. } else {
  19816. // Bottom faces
  19817. for ( i = 0; i < flen; i++ ) {
  19818. face = faces[ i ];
  19819. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19820. }
  19821. // Top faces
  19822. for ( i = 0; i < flen; i ++ ) {
  19823. face = faces[ i ];
  19824. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19825. }
  19826. }
  19827. }
  19828. // Create faces for the z-sides of the shape
  19829. function buildSideFaces() {
  19830. var layeroffset = 0;
  19831. sidewalls( contour, layeroffset );
  19832. layeroffset += contour.length;
  19833. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19834. ahole = holes[ h ];
  19835. sidewalls( ahole, layeroffset );
  19836. //, true
  19837. layeroffset += ahole.length;
  19838. }
  19839. }
  19840. function sidewalls( contour, layeroffset ) {
  19841. var j, k;
  19842. i = contour.length;
  19843. while ( --i >= 0 ) {
  19844. j = i;
  19845. k = i - 1;
  19846. if ( k < 0 ) k = contour.length - 1;
  19847. //console.log('b', i,j, i-1, k,vertices.length);
  19848. var s = 0, sl = steps + bevelSegments * 2;
  19849. for ( s = 0; s < sl; s ++ ) {
  19850. var slen1 = vlen * s;
  19851. var slen2 = vlen * ( s + 1 );
  19852. var a = layeroffset + j + slen1,
  19853. b = layeroffset + k + slen1,
  19854. c = layeroffset + k + slen2,
  19855. d = layeroffset + j + slen2;
  19856. f4( a, b, c, d, contour, s, sl, j, k );
  19857. }
  19858. }
  19859. }
  19860. function v( x, y, z ) {
  19861. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19862. }
  19863. function f3( a, b, c, isBottom ) {
  19864. a += shapesOffset;
  19865. b += shapesOffset;
  19866. c += shapesOffset;
  19867. // normal, color, material
  19868. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19869. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19870. scope.faceVertexUvs[ 0 ].push( uvs );
  19871. }
  19872. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19873. a += shapesOffset;
  19874. b += shapesOffset;
  19875. c += shapesOffset;
  19876. d += shapesOffset;
  19877. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19878. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19879. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19880. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19881. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19882. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19883. }
  19884. };
  19885. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19886. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19887. var ax = geometry.vertices[ indexA ].x,
  19888. ay = geometry.vertices[ indexA ].y,
  19889. bx = geometry.vertices[ indexB ].x,
  19890. by = geometry.vertices[ indexB ].y,
  19891. cx = geometry.vertices[ indexC ].x,
  19892. cy = geometry.vertices[ indexC ].y;
  19893. return [
  19894. new THREE.Vector2( ax, ay ),
  19895. new THREE.Vector2( bx, by ),
  19896. new THREE.Vector2( cx, cy )
  19897. ];
  19898. },
  19899. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19900. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19901. },
  19902. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19903. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19904. contourIndex1, contourIndex2 ) {
  19905. var ax = geometry.vertices[ indexA ].x,
  19906. ay = geometry.vertices[ indexA ].y,
  19907. az = geometry.vertices[ indexA ].z,
  19908. bx = geometry.vertices[ indexB ].x,
  19909. by = geometry.vertices[ indexB ].y,
  19910. bz = geometry.vertices[ indexB ].z,
  19911. cx = geometry.vertices[ indexC ].x,
  19912. cy = geometry.vertices[ indexC ].y,
  19913. cz = geometry.vertices[ indexC ].z,
  19914. dx = geometry.vertices[ indexD ].x,
  19915. dy = geometry.vertices[ indexD ].y,
  19916. dz = geometry.vertices[ indexD ].z;
  19917. if ( Math.abs( ay - by ) < 0.01 ) {
  19918. return [
  19919. new THREE.Vector2( ax, 1 - az ),
  19920. new THREE.Vector2( bx, 1 - bz ),
  19921. new THREE.Vector2( cx, 1 - cz ),
  19922. new THREE.Vector2( dx, 1 - dz )
  19923. ];
  19924. } else {
  19925. return [
  19926. new THREE.Vector2( ay, 1 - az ),
  19927. new THREE.Vector2( by, 1 - bz ),
  19928. new THREE.Vector2( cy, 1 - cz ),
  19929. new THREE.Vector2( dy, 1 - dz )
  19930. ];
  19931. }
  19932. }
  19933. };
  19934. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19935. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19936. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19937. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19938. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19939. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19940. /**
  19941. * @author jonobr1 / http://jonobr1.com
  19942. *
  19943. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19944. * ExtrudeGeometry.
  19945. *
  19946. * parameters = {
  19947. *
  19948. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19949. *
  19950. * material: <int> // material index for front and back faces
  19951. * uvGenerator: <Object> // object that provides UV generator functions
  19952. *
  19953. * }
  19954. **/
  19955. THREE.ShapeGeometry = function ( shapes, options ) {
  19956. THREE.Geometry.call( this );
  19957. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19958. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19959. this.addShapeList( shapes, options );
  19960. this.computeFaceNormals();
  19961. };
  19962. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19963. /**
  19964. * Add an array of shapes to THREE.ShapeGeometry.
  19965. */
  19966. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19967. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19968. this.addShape( shapes[ i ], options );
  19969. }
  19970. return this;
  19971. };
  19972. /**
  19973. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19974. */
  19975. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19976. if ( options === undefined ) options = {};
  19977. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19978. var material = options.material;
  19979. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19980. var shapebb = this.shapebb;
  19981. //
  19982. var i, l, hole, s;
  19983. var shapesOffset = this.vertices.length;
  19984. var shapePoints = shape.extractPoints( curveSegments );
  19985. var vertices = shapePoints.shape;
  19986. var holes = shapePoints.holes;
  19987. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19988. if ( reverse ) {
  19989. vertices = vertices.reverse();
  19990. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19991. for ( i = 0, l = holes.length; i < l; i++ ) {
  19992. hole = holes[ i ];
  19993. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19994. holes[ i ] = hole.reverse();
  19995. }
  19996. }
  19997. reverse = false;
  19998. }
  19999. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  20000. // Vertices
  20001. var contour = vertices;
  20002. for ( i = 0, l = holes.length; i < l; i++ ) {
  20003. hole = holes[ i ];
  20004. vertices = vertices.concat( hole );
  20005. }
  20006. //
  20007. var vert, vlen = vertices.length;
  20008. var face, flen = faces.length;
  20009. var cont, clen = contour.length;
  20010. for ( i = 0; i < vlen; i++ ) {
  20011. vert = vertices[ i ];
  20012. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  20013. }
  20014. for ( i = 0; i < flen; i++ ) {
  20015. face = faces[ i ];
  20016. var a = face[ 0 ] + shapesOffset;
  20017. var b = face[ 1 ] + shapesOffset;
  20018. var c = face[ 2 ] + shapesOffset;
  20019. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  20020. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  20021. }
  20022. };
  20023. /**
  20024. * @author astrodud / http://astrodud.isgreat.org/
  20025. * @author zz85 / https://github.com/zz85
  20026. * @author bhouston / http://exocortex.com
  20027. */
  20028. // points - to create a closed torus, one must use a set of points
  20029. // like so: [ a, b, c, d, a ], see first is the same as last.
  20030. // segments - the number of circumference segments to create
  20031. // phiStart - the starting radian
  20032. // phiLength - the radian (0 to 2*PI) range of the lathed section
  20033. // 2*pi is a closed lathe, less than 2PI is a portion.
  20034. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  20035. THREE.Geometry.call( this );
  20036. segments = segments || 12;
  20037. phiStart = phiStart || 0;
  20038. phiLength = phiLength || 2 * Math.PI;
  20039. var inversePointLength = 1.0 / ( points.length - 1 );
  20040. var inverseSegments = 1.0 / segments;
  20041. for ( var i = 0, il = segments; i <= il; i ++ ) {
  20042. var phi = phiStart + i * inverseSegments * phiLength;
  20043. var c = Math.cos( phi ),
  20044. s = Math.sin( phi );
  20045. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  20046. var pt = points[ j ];
  20047. var vertex = new THREE.Vector3();
  20048. vertex.x = c * pt.x - s * pt.y;
  20049. vertex.y = s * pt.x + c * pt.y;
  20050. vertex.z = pt.z;
  20051. this.vertices.push( vertex );
  20052. }
  20053. }
  20054. var np = points.length;
  20055. for ( var i = 0, il = segments; i < il; i ++ ) {
  20056. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  20057. var base = j + np * i;
  20058. var a = base;
  20059. var b = base + np;
  20060. var c = base + 1 + np;
  20061. var d = base + 1;
  20062. var u0 = i * inverseSegments;
  20063. var v0 = j * inversePointLength;
  20064. var u1 = u0 + inverseSegments;
  20065. var v1 = v0 + inversePointLength;
  20066. this.faces.push( new THREE.Face3( a, b, d ) );
  20067. this.faceVertexUvs[ 0 ].push( [
  20068. new THREE.Vector2( u0, v0 ),
  20069. new THREE.Vector2( u1, v0 ),
  20070. new THREE.Vector2( u0, v1 )
  20071. ] );
  20072. this.faces.push( new THREE.Face3( b, c, d ) );
  20073. this.faceVertexUvs[ 0 ].push( [
  20074. new THREE.Vector2( u1, v0 ),
  20075. new THREE.Vector2( u1, v1 ),
  20076. new THREE.Vector2( u0, v1 )
  20077. ] );
  20078. }
  20079. }
  20080. this.mergeVertices();
  20081. this.computeFaceNormals();
  20082. this.computeVertexNormals();
  20083. };
  20084. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20085. /**
  20086. * @author mrdoob / http://mrdoob.com/
  20087. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  20088. */
  20089. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  20090. THREE.BufferGeometry.call( this );
  20091. this.parameters = {
  20092. width: width,
  20093. height: height,
  20094. widthSegments: widthSegments,
  20095. heightSegments: heightSegments
  20096. };
  20097. var width_half = width / 2;
  20098. var height_half = height / 2;
  20099. var gridX = widthSegments || 1;
  20100. var gridY = heightSegments || 1;
  20101. var gridX1 = gridX + 1;
  20102. var gridY1 = gridY + 1;
  20103. var segment_width = width / gridX;
  20104. var segment_height = height / gridY;
  20105. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  20106. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  20107. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  20108. var offset = 0;
  20109. var offset2 = 0;
  20110. for ( var iy = 0; iy < gridY1; iy ++ ) {
  20111. var y = iy * segment_height - height_half;
  20112. for ( var ix = 0; ix < gridX1; ix ++ ) {
  20113. var x = ix * segment_width - width_half;
  20114. vertices[ offset ] = x;
  20115. vertices[ offset + 1 ] = - y;
  20116. normals[ offset + 2 ] = 1;
  20117. uvs[ offset2 ] = ix / gridX;
  20118. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  20119. offset += 3;
  20120. offset2 += 2;
  20121. }
  20122. }
  20123. offset = 0;
  20124. var indices = new Uint16Array( gridX * gridY * 6 );
  20125. for ( var iy = 0; iy < gridY; iy ++ ) {
  20126. for ( var ix = 0; ix < gridX; ix ++ ) {
  20127. var a = ix + gridX1 * iy;
  20128. var b = ix + gridX1 * ( iy + 1 );
  20129. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  20130. var d = ( ix + 1 ) + gridX1 * iy;
  20131. indices[ offset ] = a;
  20132. indices[ offset + 1 ] = b;
  20133. indices[ offset + 2 ] = d;
  20134. indices[ offset + 3 ] = b;
  20135. indices[ offset + 4 ] = c;
  20136. indices[ offset + 5 ] = d;
  20137. offset += 6;
  20138. }
  20139. }
  20140. this.attributes[ 'index' ] = { array: indices, itemSize: 1 };
  20141. this.attributes[ 'position' ] = { array: vertices, itemSize: 3 };
  20142. this.attributes[ 'normal' ] = { array: normals, itemSize: 3 };
  20143. this.attributes[ 'uv' ] = { array: uvs, itemSize: 2 };
  20144. };
  20145. THREE.PlaneGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  20146. /**
  20147. * @author Kaleb Murphy
  20148. */
  20149. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20150. THREE.Geometry.call( this );
  20151. innerRadius = innerRadius || 0;
  20152. outerRadius = outerRadius || 50;
  20153. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20154. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20155. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  20156. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  20157. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20158. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  20159. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20160. var vertex = new THREE.Vector3();
  20161. var segment = thetaStart + o / thetaSegments * thetaLength;
  20162. vertex.x = radius * Math.cos( segment );
  20163. vertex.y = radius * Math.sin( segment );
  20164. this.vertices.push( vertex );
  20165. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  20166. }
  20167. radius += radiusStep;
  20168. }
  20169. var n = new THREE.Vector3( 0, 0, 1 );
  20170. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  20171. var thetaSegment = i * thetaSegments;
  20172. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20173. var segment = o + thetaSegment;
  20174. var v1 = segment + i;
  20175. var v2 = segment + thetaSegments + i;
  20176. var v3 = segment + thetaSegments + 1 + i;
  20177. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  20178. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  20179. v1 = segment + i;
  20180. v2 = segment + thetaSegments + 1 + i;
  20181. v3 = segment + 1 + i;
  20182. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  20183. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  20184. }
  20185. }
  20186. this.computeFaceNormals();
  20187. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20188. };
  20189. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20190. /**
  20191. * @author mrdoob / http://mrdoob.com/
  20192. */
  20193. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20194. THREE.Geometry.call( this );
  20195. this.parameters = {
  20196. radius: radius,
  20197. widthSegments: widthSegments,
  20198. heightSegments: heightSegments,
  20199. phiStart: phiStart,
  20200. phiLength: phiLength,
  20201. thetaStart: thetaStart,
  20202. thetaLength: thetaLength
  20203. };
  20204. radius = radius || 50;
  20205. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  20206. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  20207. phiStart = phiStart !== undefined ? phiStart : 0;
  20208. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  20209. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20210. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  20211. var x, y, vertices = [], uvs = [];
  20212. for ( y = 0; y <= heightSegments; y ++ ) {
  20213. var verticesRow = [];
  20214. var uvsRow = [];
  20215. for ( x = 0; x <= widthSegments; x ++ ) {
  20216. var u = x / widthSegments;
  20217. var v = y / heightSegments;
  20218. var vertex = new THREE.Vector3();
  20219. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20220. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20221. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20222. this.vertices.push( vertex );
  20223. verticesRow.push( this.vertices.length - 1 );
  20224. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  20225. }
  20226. vertices.push( verticesRow );
  20227. uvs.push( uvsRow );
  20228. }
  20229. for ( y = 0; y < heightSegments; y ++ ) {
  20230. for ( x = 0; x < widthSegments; x ++ ) {
  20231. var v1 = vertices[ y ][ x + 1 ];
  20232. var v2 = vertices[ y ][ x ];
  20233. var v3 = vertices[ y + 1 ][ x ];
  20234. var v4 = vertices[ y + 1 ][ x + 1 ];
  20235. var n1 = this.vertices[ v1 ].clone().normalize();
  20236. var n2 = this.vertices[ v2 ].clone().normalize();
  20237. var n3 = this.vertices[ v3 ].clone().normalize();
  20238. var n4 = this.vertices[ v4 ].clone().normalize();
  20239. var uv1 = uvs[ y ][ x + 1 ].clone();
  20240. var uv2 = uvs[ y ][ x ].clone();
  20241. var uv3 = uvs[ y + 1 ][ x ].clone();
  20242. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  20243. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  20244. uv1.x = ( uv1.x + uv2.x ) / 2;
  20245. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  20246. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  20247. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  20248. uv3.x = ( uv3.x + uv4.x ) / 2;
  20249. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  20250. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  20251. } else {
  20252. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  20253. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  20254. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  20255. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  20256. }
  20257. }
  20258. }
  20259. this.computeFaceNormals();
  20260. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20261. };
  20262. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20263. /**
  20264. * @author zz85 / http://www.lab4games.net/zz85/blog
  20265. * @author alteredq / http://alteredqualia.com/
  20266. *
  20267. * For creating 3D text geometry in three.js
  20268. *
  20269. * Text = 3D Text
  20270. *
  20271. * parameters = {
  20272. * size: <float>, // size of the text
  20273. * height: <float>, // thickness to extrude text
  20274. * curveSegments: <int>, // number of points on the curves
  20275. *
  20276. * font: <string>, // font name
  20277. * weight: <string>, // font weight (normal, bold)
  20278. * style: <string>, // font style (normal, italics)
  20279. *
  20280. * bevelEnabled: <bool>, // turn on bevel
  20281. * bevelThickness: <float>, // how deep into text bevel goes
  20282. * bevelSize: <float>, // how far from text outline is bevel
  20283. * }
  20284. *
  20285. */
  20286. /* Usage Examples
  20287. // TextGeometry wrapper
  20288. var text3d = new TextGeometry( text, options );
  20289. // Complete manner
  20290. var textShapes = THREE.FontUtils.generateShapes( text, options );
  20291. var text3d = new ExtrudeGeometry( textShapes, options );
  20292. */
  20293. THREE.TextGeometry = function ( text, parameters ) {
  20294. parameters = parameters || {};
  20295. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  20296. // translate parameters to ExtrudeGeometry API
  20297. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20298. // defaults
  20299. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20300. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20301. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20302. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  20303. };
  20304. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  20305. /**
  20306. * @author oosmoxiecode
  20307. * @author mrdoob / http://mrdoob.com/
  20308. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  20309. */
  20310. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  20311. THREE.Geometry.call( this );
  20312. this.parameters = {
  20313. radius: radius,
  20314. tube: tube,
  20315. radialSegments: radialSegments,
  20316. tubularSegments: tubularSegments,
  20317. arc: arc
  20318. };
  20319. radius = radius || 100;
  20320. tube = tube || 40;
  20321. radialSegments = radialSegments || 8;
  20322. tubularSegments = tubularSegments || 6;
  20323. arc = arc || Math.PI * 2;
  20324. var center = new THREE.Vector3(), uvs = [], normals = [];
  20325. for ( var j = 0; j <= radialSegments; j ++ ) {
  20326. for ( var i = 0; i <= tubularSegments; i ++ ) {
  20327. var u = i / tubularSegments * arc;
  20328. var v = j / radialSegments * Math.PI * 2;
  20329. center.x = radius * Math.cos( u );
  20330. center.y = radius * Math.sin( u );
  20331. var vertex = new THREE.Vector3();
  20332. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20333. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20334. vertex.z = tube * Math.sin( v );
  20335. this.vertices.push( vertex );
  20336. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  20337. normals.push( vertex.clone().sub( center ).normalize() );
  20338. }
  20339. }
  20340. for ( var j = 1; j <= radialSegments; j ++ ) {
  20341. for ( var i = 1; i <= tubularSegments; i ++ ) {
  20342. var a = ( tubularSegments + 1 ) * j + i - 1;
  20343. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20344. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20345. var d = ( tubularSegments + 1 ) * j + i;
  20346. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  20347. this.faces.push( face );
  20348. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  20349. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  20350. this.faces.push( face );
  20351. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20352. }
  20353. }
  20354. this.computeFaceNormals();
  20355. };
  20356. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20357. /**
  20358. * @author oosmoxiecode
  20359. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20360. */
  20361. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20362. THREE.Geometry.call( this );
  20363. this.parameters = {
  20364. radius: radius,
  20365. tube: tube,
  20366. radialSegments: radialSegments,
  20367. tubularSegments: tubularSegments,
  20368. p: p,
  20369. q: q,
  20370. heightScale: heightScale
  20371. };
  20372. radius = radius || 100;
  20373. tube = tube || 40;
  20374. radialSegments = radialSegments || 64;
  20375. tubularSegments = tubularSegments || 8;
  20376. p = p || 2;
  20377. q = q || 3;
  20378. heightScale = heightScale || 1;
  20379. var grid = new Array( radialSegments );
  20380. var tang = new THREE.Vector3();
  20381. var n = new THREE.Vector3();
  20382. var bitan = new THREE.Vector3();
  20383. for ( var i = 0; i < radialSegments; ++ i ) {
  20384. grid[ i ] = new Array( tubularSegments );
  20385. var u = i / radialSegments * 2 * p * Math.PI;
  20386. var p1 = getPos( u, q, p, radius, heightScale );
  20387. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  20388. tang.subVectors( p2, p1 );
  20389. n.addVectors( p2, p1 );
  20390. bitan.crossVectors( tang, n );
  20391. n.crossVectors( bitan, tang );
  20392. bitan.normalize();
  20393. n.normalize();
  20394. for ( var j = 0; j < tubularSegments; ++ j ) {
  20395. var v = j / tubularSegments * 2 * Math.PI;
  20396. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20397. var cy = tube * Math.sin( v );
  20398. var pos = new THREE.Vector3();
  20399. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20400. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20401. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20402. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  20403. }
  20404. }
  20405. for ( var i = 0; i < radialSegments; ++ i ) {
  20406. for ( var j = 0; j < tubularSegments; ++ j ) {
  20407. var ip = ( i + 1 ) % radialSegments;
  20408. var jp = ( j + 1 ) % tubularSegments;
  20409. var a = grid[ i ][ j ];
  20410. var b = grid[ ip ][ j ];
  20411. var c = grid[ ip ][ jp ];
  20412. var d = grid[ i ][ jp ];
  20413. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  20414. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  20415. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  20416. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  20417. this.faces.push( new THREE.Face3( a, b, d ) );
  20418. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20419. this.faces.push( new THREE.Face3( b, c, d ) );
  20420. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20421. }
  20422. }
  20423. this.computeFaceNormals();
  20424. this.computeVertexNormals();
  20425. function getPos( u, in_q, in_p, radius, heightScale ) {
  20426. var cu = Math.cos( u );
  20427. var su = Math.sin( u );
  20428. var quOverP = in_q / in_p * u;
  20429. var cs = Math.cos( quOverP );
  20430. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20431. var ty = radius * ( 2 + cs ) * su * 0.5;
  20432. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20433. return new THREE.Vector3( tx, ty, tz );
  20434. }
  20435. };
  20436. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20437. /**
  20438. * @author WestLangley / https://github.com/WestLangley
  20439. * @author zz85 / https://github.com/zz85
  20440. * @author miningold / https://github.com/miningold
  20441. *
  20442. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20443. *
  20444. * Creates a tube which extrudes along a 3d spline
  20445. *
  20446. * Uses parallel transport frames as described in
  20447. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20448. */
  20449. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) {
  20450. THREE.Geometry.call( this );
  20451. this.parameters = {
  20452. path: path,
  20453. segments: segments,
  20454. radius: radius,
  20455. radialSegments: radialSegments,
  20456. closed: closed
  20457. };
  20458. segments = segments || 64;
  20459. radius = radius || 1;
  20460. radialSegments = radialSegments || 8;
  20461. closed = closed || false;
  20462. var grid = [];
  20463. var scope = this,
  20464. tangent,
  20465. normal,
  20466. binormal,
  20467. numpoints = segments + 1,
  20468. x, y, z,
  20469. tx, ty, tz,
  20470. u, v,
  20471. cx, cy,
  20472. pos, pos2 = new THREE.Vector3(),
  20473. i, j,
  20474. ip, jp,
  20475. a, b, c, d,
  20476. uva, uvb, uvc, uvd;
  20477. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  20478. tangents = frames.tangents,
  20479. normals = frames.normals,
  20480. binormals = frames.binormals;
  20481. // proxy internals
  20482. this.tangents = tangents;
  20483. this.normals = normals;
  20484. this.binormals = binormals;
  20485. function vert( x, y, z ) {
  20486. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20487. }
  20488. // consruct the grid
  20489. for ( i = 0; i < numpoints; i++ ) {
  20490. grid[ i ] = [];
  20491. u = i / ( numpoints - 1 );
  20492. pos = path.getPointAt( u );
  20493. tangent = tangents[ i ];
  20494. normal = normals[ i ];
  20495. binormal = binormals[ i ];
  20496. for ( j = 0; j < radialSegments; j++ ) {
  20497. v = j / radialSegments * 2 * Math.PI;
  20498. cx = -radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20499. cy = radius * Math.sin( v );
  20500. pos2.copy( pos );
  20501. pos2.x += cx * normal.x + cy * binormal.x;
  20502. pos2.y += cx * normal.y + cy * binormal.y;
  20503. pos2.z += cx * normal.z + cy * binormal.z;
  20504. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20505. }
  20506. }
  20507. // construct the mesh
  20508. for ( i = 0; i < segments; i++ ) {
  20509. for ( j = 0; j < radialSegments; j++ ) {
  20510. ip = ( closed ) ? (i + 1) % segments : i + 1;
  20511. jp = (j + 1) % radialSegments;
  20512. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20513. b = grid[ ip ][ j ];
  20514. c = grid[ ip ][ jp ];
  20515. d = grid[ i ][ jp ];
  20516. uva = new THREE.Vector2( i / segments, j / radialSegments );
  20517. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  20518. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  20519. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  20520. this.faces.push( new THREE.Face3( a, b, d ) );
  20521. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20522. this.faces.push( new THREE.Face3( b, c, d ) );
  20523. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20524. }
  20525. }
  20526. this.computeFaceNormals();
  20527. this.computeVertexNormals();
  20528. };
  20529. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20530. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20531. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  20532. var tangent = new THREE.Vector3(),
  20533. normal = new THREE.Vector3(),
  20534. binormal = new THREE.Vector3(),
  20535. tangents = [],
  20536. normals = [],
  20537. binormals = [],
  20538. vec = new THREE.Vector3(),
  20539. mat = new THREE.Matrix4(),
  20540. numpoints = segments + 1,
  20541. theta,
  20542. epsilon = 0.0001,
  20543. smallest,
  20544. tx, ty, tz,
  20545. i, u, v;
  20546. // expose internals
  20547. this.tangents = tangents;
  20548. this.normals = normals;
  20549. this.binormals = binormals;
  20550. // compute the tangent vectors for each segment on the path
  20551. for ( i = 0; i < numpoints; i++ ) {
  20552. u = i / ( numpoints - 1 );
  20553. tangents[ i ] = path.getTangentAt( u );
  20554. tangents[ i ].normalize();
  20555. }
  20556. initialNormal3();
  20557. function initialNormal1(lastBinormal) {
  20558. // fixed start binormal. Has dangers of 0 vectors
  20559. normals[ 0 ] = new THREE.Vector3();
  20560. binormals[ 0 ] = new THREE.Vector3();
  20561. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20562. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20563. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20564. }
  20565. function initialNormal2() {
  20566. // This uses the Frenet-Serret formula for deriving binormal
  20567. var t2 = path.getTangentAt( epsilon );
  20568. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20569. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20570. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20571. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20572. }
  20573. function initialNormal3() {
  20574. // select an initial normal vector perpenicular to the first tangent vector,
  20575. // and in the direction of the smallest tangent xyz component
  20576. normals[ 0 ] = new THREE.Vector3();
  20577. binormals[ 0 ] = new THREE.Vector3();
  20578. smallest = Number.MAX_VALUE;
  20579. tx = Math.abs( tangents[ 0 ].x );
  20580. ty = Math.abs( tangents[ 0 ].y );
  20581. tz = Math.abs( tangents[ 0 ].z );
  20582. if ( tx <= smallest ) {
  20583. smallest = tx;
  20584. normal.set( 1, 0, 0 );
  20585. }
  20586. if ( ty <= smallest ) {
  20587. smallest = ty;
  20588. normal.set( 0, 1, 0 );
  20589. }
  20590. if ( tz <= smallest ) {
  20591. normal.set( 0, 0, 1 );
  20592. }
  20593. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20594. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20595. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20596. }
  20597. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20598. for ( i = 1; i < numpoints; i++ ) {
  20599. normals[ i ] = normals[ i-1 ].clone();
  20600. binormals[ i ] = binormals[ i-1 ].clone();
  20601. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20602. if ( vec.length() > epsilon ) {
  20603. vec.normalize();
  20604. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20605. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20606. }
  20607. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20608. }
  20609. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20610. if ( closed ) {
  20611. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20612. theta /= ( numpoints - 1 );
  20613. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20614. theta = -theta;
  20615. }
  20616. for ( i = 1; i < numpoints; i++ ) {
  20617. // twist a little...
  20618. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20619. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20620. }
  20621. }
  20622. };
  20623. /**
  20624. * @author clockworkgeek / https://github.com/clockworkgeek
  20625. * @author timothypratley / https://github.com/timothypratley
  20626. * @author WestLangley / http://github.com/WestLangley
  20627. */
  20628. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20629. THREE.Geometry.call( this );
  20630. radius = radius || 1;
  20631. detail = detail || 0;
  20632. var that = this;
  20633. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20634. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20635. }
  20636. var midpoints = [], p = this.vertices;
  20637. var f = [];
  20638. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20639. var v1 = p[ faces[ i ][ 0 ] ];
  20640. var v2 = p[ faces[ i ][ 1 ] ];
  20641. var v3 = p[ faces[ i ][ 2 ] ];
  20642. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20643. }
  20644. var centroid = new THREE.Vector3();
  20645. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20646. subdivide(f[ i ], detail);
  20647. }
  20648. // Handle case when face straddles the seam
  20649. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20650. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20651. var x0 = uvs[ 0 ].x;
  20652. var x1 = uvs[ 1 ].x;
  20653. var x2 = uvs[ 2 ].x;
  20654. var max = Math.max( x0, Math.max( x1, x2 ) );
  20655. var min = Math.min( x0, Math.min( x1, x2 ) );
  20656. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20657. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20658. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20659. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20660. }
  20661. }
  20662. // Apply radius
  20663. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20664. this.vertices[ i ].multiplyScalar( radius );
  20665. }
  20666. // Merge vertices
  20667. this.mergeVertices();
  20668. this.computeFaceNormals();
  20669. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20670. // Project vector onto sphere's surface
  20671. function prepare( vector ) {
  20672. var vertex = vector.normalize().clone();
  20673. vertex.index = that.vertices.push( vertex ) - 1;
  20674. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20675. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20676. var v = inclination( vector ) / Math.PI + 0.5;
  20677. vertex.uv = new THREE.Vector2( u, 1 - v );
  20678. return vertex;
  20679. }
  20680. // Approximate a curved face with recursively sub-divided triangles.
  20681. function make( v1, v2, v3 ) {
  20682. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20683. that.faces.push( face );
  20684. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20685. var azi = azimuth( centroid );
  20686. that.faceVertexUvs[ 0 ].push( [
  20687. correctUV( v1.uv, v1, azi ),
  20688. correctUV( v2.uv, v2, azi ),
  20689. correctUV( v3.uv, v3, azi )
  20690. ] );
  20691. }
  20692. // Analytically subdivide a face to the required detail level.
  20693. function subdivide( face, detail ) {
  20694. var cols = Math.pow(2, detail);
  20695. var cells = Math.pow(4, detail);
  20696. var a = prepare( that.vertices[ face.a ] );
  20697. var b = prepare( that.vertices[ face.b ] );
  20698. var c = prepare( that.vertices[ face.c ] );
  20699. var v = [];
  20700. // Construct all of the vertices for this subdivision.
  20701. for ( var i = 0 ; i <= cols; i ++ ) {
  20702. v[ i ] = [];
  20703. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20704. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20705. var rows = cols - i;
  20706. for ( var j = 0; j <= rows; j ++) {
  20707. if ( j == 0 && i == cols ) {
  20708. v[ i ][ j ] = aj;
  20709. } else {
  20710. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20711. }
  20712. }
  20713. }
  20714. // Construct all of the faces.
  20715. for ( var i = 0; i < cols ; i ++ ) {
  20716. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20717. var k = Math.floor( j / 2 );
  20718. if ( j % 2 == 0 ) {
  20719. make(
  20720. v[ i ][ k + 1],
  20721. v[ i + 1 ][ k ],
  20722. v[ i ][ k ]
  20723. );
  20724. } else {
  20725. make(
  20726. v[ i ][ k + 1 ],
  20727. v[ i + 1][ k + 1],
  20728. v[ i + 1 ][ k ]
  20729. );
  20730. }
  20731. }
  20732. }
  20733. }
  20734. // Angle around the Y axis, counter-clockwise when looking from above.
  20735. function azimuth( vector ) {
  20736. return Math.atan2( vector.z, -vector.x );
  20737. }
  20738. // Angle above the XZ plane.
  20739. function inclination( vector ) {
  20740. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20741. }
  20742. // Texture fixing helper. Spheres have some odd behaviours.
  20743. function correctUV( uv, vector, azimuth ) {
  20744. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20745. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20746. return uv.clone();
  20747. }
  20748. };
  20749. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20750. /**
  20751. * @author timothypratley / https://github.com/timothypratley
  20752. */
  20753. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20754. this.parameters = {
  20755. radius: radius,
  20756. detail: detail
  20757. };
  20758. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20759. var vertices = [
  20760. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20761. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20762. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20763. ];
  20764. var faces = [
  20765. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20766. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20767. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20768. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20769. ];
  20770. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20771. };
  20772. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20773. /**
  20774. * @author timothypratley / https://github.com/timothypratley
  20775. */
  20776. THREE.OctahedronGeometry = function ( radius, detail ) {
  20777. this.parameters = {
  20778. radius: radius,
  20779. detail: detail
  20780. };
  20781. var vertices = [
  20782. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20783. ];
  20784. var faces = [
  20785. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20786. ];
  20787. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20788. };
  20789. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20790. /**
  20791. * @author timothypratley / https://github.com/timothypratley
  20792. */
  20793. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20794. var vertices = [
  20795. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20796. ];
  20797. var faces = [
  20798. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20799. ];
  20800. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20801. };
  20802. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20803. /**
  20804. * @author zz85 / https://github.com/zz85
  20805. * Parametric Surfaces Geometry
  20806. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20807. *
  20808. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20809. *
  20810. */
  20811. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20812. THREE.Geometry.call( this );
  20813. var verts = this.vertices;
  20814. var faces = this.faces;
  20815. var uvs = this.faceVertexUvs[ 0 ];
  20816. var i, il, j, p;
  20817. var u, v;
  20818. var stackCount = stacks + 1;
  20819. var sliceCount = slices + 1;
  20820. for ( i = 0; i <= stacks; i ++ ) {
  20821. v = i / stacks;
  20822. for ( j = 0; j <= slices; j ++ ) {
  20823. u = j / slices;
  20824. p = func( u, v );
  20825. verts.push( p );
  20826. }
  20827. }
  20828. var a, b, c, d;
  20829. var uva, uvb, uvc, uvd;
  20830. for ( i = 0; i < stacks; i ++ ) {
  20831. for ( j = 0; j < slices; j ++ ) {
  20832. a = i * sliceCount + j;
  20833. b = i * sliceCount + j + 1;
  20834. c = (i + 1) * sliceCount + j + 1;
  20835. d = (i + 1) * sliceCount + j;
  20836. uva = new THREE.Vector2( j / slices, i / stacks );
  20837. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20838. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20839. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20840. faces.push( new THREE.Face3( a, b, d ) );
  20841. uvs.push( [ uva, uvb, uvd ] );
  20842. faces.push( new THREE.Face3( b, c, d ) );
  20843. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20844. }
  20845. }
  20846. // console.log(this);
  20847. // magic bullet
  20848. // var diff = this.mergeVertices();
  20849. // console.log('removed ', diff, ' vertices by merging');
  20850. this.computeFaceNormals();
  20851. this.computeVertexNormals();
  20852. };
  20853. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20854. /**
  20855. * @author sroucheray / http://sroucheray.org/
  20856. * @author mrdoob / http://mrdoob.com/
  20857. */
  20858. THREE.AxisHelper = function ( size ) {
  20859. size = size || 1;
  20860. var geometry = new THREE.Geometry();
  20861. geometry.vertices.push(
  20862. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20863. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20864. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20865. );
  20866. geometry.colors.push(
  20867. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20868. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20869. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20870. );
  20871. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20872. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20873. };
  20874. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20875. /**
  20876. * @author WestLangley / http://github.com/WestLangley
  20877. * @author zz85 / http://github.com/zz85
  20878. * @author bhouston / http://exocortex.com
  20879. *
  20880. * Creates an arrow for visualizing directions
  20881. *
  20882. * Parameters:
  20883. * dir - Vector3
  20884. * origin - Vector3
  20885. * length - Number
  20886. * hex - color in hex value
  20887. * headLength - Number
  20888. * headWidth - Number
  20889. */
  20890. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  20891. // dir is assumed to be normalized
  20892. THREE.Object3D.call( this );
  20893. if ( hex === undefined ) hex = 0xffff00;
  20894. if ( length === undefined ) length = 1;
  20895. if ( headLength === undefined ) headLength = 0.2 * length;
  20896. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20897. this.position = origin;
  20898. var lineGeometry = new THREE.Geometry();
  20899. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20900. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20901. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20902. this.line.matrixAutoUpdate = false;
  20903. this.add( this.line );
  20904. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20905. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20906. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20907. this.cone.matrixAutoUpdate = false;
  20908. this.add( this.cone );
  20909. this.setDirection( dir );
  20910. this.setLength( length, headLength, headWidth );
  20911. };
  20912. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20913. THREE.ArrowHelper.prototype.setDirection = function () {
  20914. var axis = new THREE.Vector3();
  20915. var radians;
  20916. return function ( dir ) {
  20917. // dir is assumed to be normalized
  20918. if ( dir.y > 0.99999 ) {
  20919. this.quaternion.set( 0, 0, 0, 1 );
  20920. } else if ( dir.y < - 0.99999 ) {
  20921. this.quaternion.set( 1, 0, 0, 0 );
  20922. } else {
  20923. axis.set( dir.z, 0, - dir.x ).normalize();
  20924. radians = Math.acos( dir.y );
  20925. this.quaternion.setFromAxisAngle( axis, radians );
  20926. }
  20927. };
  20928. }();
  20929. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20930. if ( headLength === undefined ) headLength = 0.2 * length;
  20931. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20932. this.line.scale.set( 1, length, 1 );
  20933. this.line.updateMatrix();
  20934. this.cone.scale.set( headWidth, headLength, headWidth );
  20935. this.cone.position.y = length;
  20936. this.cone.updateMatrix();
  20937. };
  20938. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20939. this.line.material.color.setHex( hex );
  20940. this.cone.material.color.setHex( hex );
  20941. };
  20942. /**
  20943. * @author mrdoob / http://mrdoob.com/
  20944. */
  20945. THREE.BoxHelper = function ( object ) {
  20946. // 5____4
  20947. // 1/___0/|
  20948. // | 6__|_7
  20949. // 2/___3/
  20950. var vertices = [
  20951. new THREE.Vector3( 1, 1, 1 ),
  20952. new THREE.Vector3( - 1, 1, 1 ),
  20953. new THREE.Vector3( - 1, - 1, 1 ),
  20954. new THREE.Vector3( 1, - 1, 1 ),
  20955. new THREE.Vector3( 1, 1, - 1 ),
  20956. new THREE.Vector3( - 1, 1, - 1 ),
  20957. new THREE.Vector3( - 1, - 1, - 1 ),
  20958. new THREE.Vector3( 1, - 1, - 1 )
  20959. ];
  20960. this.vertices = vertices;
  20961. // TODO: Wouldn't be nice if Line had .segments?
  20962. var geometry = new THREE.Geometry();
  20963. geometry.vertices.push(
  20964. vertices[ 0 ], vertices[ 1 ],
  20965. vertices[ 1 ], vertices[ 2 ],
  20966. vertices[ 2 ], vertices[ 3 ],
  20967. vertices[ 3 ], vertices[ 0 ],
  20968. vertices[ 4 ], vertices[ 5 ],
  20969. vertices[ 5 ], vertices[ 6 ],
  20970. vertices[ 6 ], vertices[ 7 ],
  20971. vertices[ 7 ], vertices[ 4 ],
  20972. vertices[ 0 ], vertices[ 4 ],
  20973. vertices[ 1 ], vertices[ 5 ],
  20974. vertices[ 2 ], vertices[ 6 ],
  20975. vertices[ 3 ], vertices[ 7 ]
  20976. );
  20977. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20978. if ( object !== undefined ) {
  20979. this.update( object );
  20980. }
  20981. };
  20982. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20983. THREE.BoxHelper.prototype.update = function ( object ) {
  20984. var geometry = object.geometry;
  20985. if ( geometry.boundingBox === null ) {
  20986. geometry.computeBoundingBox();
  20987. }
  20988. var min = geometry.boundingBox.min;
  20989. var max = geometry.boundingBox.max;
  20990. var vertices = this.vertices;
  20991. vertices[ 0 ].set( max.x, max.y, max.z );
  20992. vertices[ 1 ].set( min.x, max.y, max.z );
  20993. vertices[ 2 ].set( min.x, min.y, max.z );
  20994. vertices[ 3 ].set( max.x, min.y, max.z );
  20995. vertices[ 4 ].set( max.x, max.y, min.z );
  20996. vertices[ 5 ].set( min.x, max.y, min.z );
  20997. vertices[ 6 ].set( min.x, min.y, min.z );
  20998. vertices[ 7 ].set( max.x, min.y, min.z );
  20999. this.geometry.computeBoundingSphere();
  21000. this.geometry.verticesNeedUpdate = true;
  21001. this.matrixAutoUpdate = false;
  21002. this.matrixWorld = object.matrixWorld;
  21003. };
  21004. /**
  21005. * @author WestLangley / http://github.com/WestLangley
  21006. */
  21007. // a helper to show the world-axis-aligned bounding box for an object
  21008. THREE.BoundingBoxHelper = function ( object, hex ) {
  21009. var color = ( hex !== undefined ) ? hex : 0x888888;
  21010. this.object = object;
  21011. this.box = new THREE.Box3();
  21012. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  21013. };
  21014. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  21015. THREE.BoundingBoxHelper.prototype.update = function () {
  21016. this.box.setFromObject( this.object );
  21017. this.box.size( this.scale );
  21018. this.box.center( this.position );
  21019. };
  21020. /**
  21021. * @author alteredq / http://alteredqualia.com/
  21022. *
  21023. * - shows frustum, line of sight and up of the camera
  21024. * - suitable for fast updates
  21025. * - based on frustum visualization in lightgl.js shadowmap example
  21026. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  21027. */
  21028. THREE.CameraHelper = function ( camera ) {
  21029. var geometry = new THREE.Geometry();
  21030. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  21031. var pointMap = {};
  21032. // colors
  21033. var hexFrustum = 0xffaa00;
  21034. var hexCone = 0xff0000;
  21035. var hexUp = 0x00aaff;
  21036. var hexTarget = 0xffffff;
  21037. var hexCross = 0x333333;
  21038. // near
  21039. addLine( "n1", "n2", hexFrustum );
  21040. addLine( "n2", "n4", hexFrustum );
  21041. addLine( "n4", "n3", hexFrustum );
  21042. addLine( "n3", "n1", hexFrustum );
  21043. // far
  21044. addLine( "f1", "f2", hexFrustum );
  21045. addLine( "f2", "f4", hexFrustum );
  21046. addLine( "f4", "f3", hexFrustum );
  21047. addLine( "f3", "f1", hexFrustum );
  21048. // sides
  21049. addLine( "n1", "f1", hexFrustum );
  21050. addLine( "n2", "f2", hexFrustum );
  21051. addLine( "n3", "f3", hexFrustum );
  21052. addLine( "n4", "f4", hexFrustum );
  21053. // cone
  21054. addLine( "p", "n1", hexCone );
  21055. addLine( "p", "n2", hexCone );
  21056. addLine( "p", "n3", hexCone );
  21057. addLine( "p", "n4", hexCone );
  21058. // up
  21059. addLine( "u1", "u2", hexUp );
  21060. addLine( "u2", "u3", hexUp );
  21061. addLine( "u3", "u1", hexUp );
  21062. // target
  21063. addLine( "c", "t", hexTarget );
  21064. addLine( "p", "c", hexCross );
  21065. // cross
  21066. addLine( "cn1", "cn2", hexCross );
  21067. addLine( "cn3", "cn4", hexCross );
  21068. addLine( "cf1", "cf2", hexCross );
  21069. addLine( "cf3", "cf4", hexCross );
  21070. function addLine( a, b, hex ) {
  21071. addPoint( a, hex );
  21072. addPoint( b, hex );
  21073. }
  21074. function addPoint( id, hex ) {
  21075. geometry.vertices.push( new THREE.Vector3() );
  21076. geometry.colors.push( new THREE.Color( hex ) );
  21077. if ( pointMap[ id ] === undefined ) {
  21078. pointMap[ id ] = [];
  21079. }
  21080. pointMap[ id ].push( geometry.vertices.length - 1 );
  21081. }
  21082. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21083. this.camera = camera;
  21084. this.matrixWorld = camera.matrixWorld;
  21085. this.matrixAutoUpdate = false;
  21086. this.pointMap = pointMap;
  21087. this.update();
  21088. };
  21089. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  21090. THREE.CameraHelper.prototype.update = function () {
  21091. var vector = new THREE.Vector3();
  21092. var camera = new THREE.Camera();
  21093. var projector = new THREE.Projector();
  21094. return function () {
  21095. var scope = this;
  21096. var w = 1, h = 1;
  21097. // we need just camera projection matrix
  21098. // world matrix must be identity
  21099. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  21100. // center / target
  21101. setPoint( "c", 0, 0, -1 );
  21102. setPoint( "t", 0, 0, 1 );
  21103. // near
  21104. setPoint( "n1", -w, -h, -1 );
  21105. setPoint( "n2", w, -h, -1 );
  21106. setPoint( "n3", -w, h, -1 );
  21107. setPoint( "n4", w, h, -1 );
  21108. // far
  21109. setPoint( "f1", -w, -h, 1 );
  21110. setPoint( "f2", w, -h, 1 );
  21111. setPoint( "f3", -w, h, 1 );
  21112. setPoint( "f4", w, h, 1 );
  21113. // up
  21114. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  21115. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  21116. setPoint( "u3", 0, h * 2, -1 );
  21117. // cross
  21118. setPoint( "cf1", -w, 0, 1 );
  21119. setPoint( "cf2", w, 0, 1 );
  21120. setPoint( "cf3", 0, -h, 1 );
  21121. setPoint( "cf4", 0, h, 1 );
  21122. setPoint( "cn1", -w, 0, -1 );
  21123. setPoint( "cn2", w, 0, -1 );
  21124. setPoint( "cn3", 0, -h, -1 );
  21125. setPoint( "cn4", 0, h, -1 );
  21126. function setPoint( point, x, y, z ) {
  21127. vector.set( x, y, z );
  21128. projector.unprojectVector( vector, camera );
  21129. var points = scope.pointMap[ point ];
  21130. if ( points !== undefined ) {
  21131. for ( var i = 0, il = points.length; i < il; i ++ ) {
  21132. scope.geometry.vertices[ points[ i ] ].copy( vector );
  21133. }
  21134. }
  21135. }
  21136. this.geometry.verticesNeedUpdate = true;
  21137. };
  21138. }();
  21139. /**
  21140. * @author alteredq / http://alteredqualia.com/
  21141. * @author mrdoob / http://mrdoob.com/
  21142. * @author WestLangley / http://github.com/WestLangley
  21143. */
  21144. THREE.DirectionalLightHelper = function ( light, size ) {
  21145. THREE.Object3D.call( this );
  21146. this.light = light;
  21147. this.light.updateMatrixWorld();
  21148. this.matrixWorld = light.matrixWorld;
  21149. this.matrixAutoUpdate = false;
  21150. size = size || 1;
  21151. var geometry = new THREE.Geometry();
  21152. geometry.vertices.push(
  21153. new THREE.Vector3( - size, size, 0 ),
  21154. new THREE.Vector3( size, size, 0 ),
  21155. new THREE.Vector3( size, - size, 0 ),
  21156. new THREE.Vector3( - size, - size, 0 ),
  21157. new THREE.Vector3( - size, size, 0 )
  21158. );
  21159. var material = new THREE.LineBasicMaterial( { fog: false } );
  21160. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21161. this.lightPlane = new THREE.Line( geometry, material );
  21162. this.add( this.lightPlane );
  21163. geometry = new THREE.Geometry();
  21164. geometry.vertices.push(
  21165. new THREE.Vector3(),
  21166. new THREE.Vector3()
  21167. );
  21168. material = new THREE.LineBasicMaterial( { fog: false } );
  21169. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21170. this.targetLine = new THREE.Line( geometry, material );
  21171. this.add( this.targetLine );
  21172. this.update();
  21173. };
  21174. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21175. THREE.DirectionalLightHelper.prototype.dispose = function () {
  21176. this.lightPlane.geometry.dispose();
  21177. this.lightPlane.material.dispose();
  21178. this.targetLine.geometry.dispose();
  21179. this.targetLine.material.dispose();
  21180. };
  21181. THREE.DirectionalLightHelper.prototype.update = function () {
  21182. var v1 = new THREE.Vector3();
  21183. var v2 = new THREE.Vector3();
  21184. var v3 = new THREE.Vector3();
  21185. return function () {
  21186. v1.setFromMatrixPosition( this.light.matrixWorld );
  21187. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  21188. v3.subVectors( v2, v1 );
  21189. this.lightPlane.lookAt( v3 );
  21190. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21191. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  21192. this.targetLine.geometry.verticesNeedUpdate = true;
  21193. this.targetLine.material.color.copy( this.lightPlane.material.color );
  21194. }
  21195. }();
  21196. /**
  21197. * @author WestLangley / http://github.com/WestLangley
  21198. */
  21199. THREE.EdgesHelper = function ( object, hex ) {
  21200. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21201. var edge = [ 0, 0 ], hash = {};
  21202. var sortFunction = function ( a, b ) { return a - b };
  21203. var keys = [ 'a', 'b', 'c' ];
  21204. var geometry = new THREE.BufferGeometry();
  21205. var geometry2 = object.geometry.clone();
  21206. geometry2.mergeVertices();
  21207. geometry2.computeFaceNormals();
  21208. var vertices = geometry2.vertices;
  21209. var faces = geometry2.faces;
  21210. var numEdges = 0;
  21211. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21212. var face = faces[ i ];
  21213. for ( var j = 0; j < 3; j ++ ) {
  21214. edge[ 0 ] = face[ keys[ j ] ];
  21215. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21216. edge.sort( sortFunction );
  21217. var key = edge.toString();
  21218. if ( hash[ key ] === undefined ) {
  21219. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  21220. numEdges ++;
  21221. } else {
  21222. hash[ key ].face2 = i;
  21223. }
  21224. }
  21225. }
  21226. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21227. var coords = geometry.attributes.position.array;
  21228. var index = 0;
  21229. for ( var key in hash ) {
  21230. var h = hash[ key ];
  21231. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  21232. var vertex = vertices[ h.vert1 ];
  21233. coords[ index ++ ] = vertex.x;
  21234. coords[ index ++ ] = vertex.y;
  21235. coords[ index ++ ] = vertex.z;
  21236. vertex = vertices[ h.vert2 ];
  21237. coords[ index ++ ] = vertex.x;
  21238. coords[ index ++ ] = vertex.y;
  21239. coords[ index ++ ] = vertex.z;
  21240. }
  21241. }
  21242. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21243. this.matrixAutoUpdate = false;
  21244. this.matrixWorld = object.matrixWorld;
  21245. };
  21246. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  21247. /**
  21248. * @author mrdoob / http://mrdoob.com/
  21249. * @author WestLangley / http://github.com/WestLangley
  21250. */
  21251. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  21252. this.object = object;
  21253. this.size = ( size !== undefined ) ? size : 1;
  21254. var color = ( hex !== undefined ) ? hex : 0xffff00;
  21255. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21256. var geometry = new THREE.Geometry();
  21257. var faces = this.object.geometry.faces;
  21258. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21259. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  21260. }
  21261. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21262. this.matrixAutoUpdate = false;
  21263. this.normalMatrix = new THREE.Matrix3();
  21264. this.update();
  21265. };
  21266. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21267. THREE.FaceNormalsHelper.prototype.update = function () {
  21268. var vertices = this.geometry.vertices;
  21269. var object = this.object;
  21270. var objectVertices = object.geometry.vertices;
  21271. var objectFaces = object.geometry.faces;
  21272. var objectWorldMatrix = object.matrixWorld;
  21273. object.updateMatrixWorld( true );
  21274. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  21275. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  21276. var face = objectFaces[ i ];
  21277. vertices[ i2 ].copy( objectVertices[ face.a ] )
  21278. .add( objectVertices[ face.b ] )
  21279. .add( objectVertices[ face.c ] )
  21280. .divideScalar( 3 )
  21281. .applyMatrix4( objectWorldMatrix );
  21282. vertices[ i2 + 1 ].copy( face.normal )
  21283. .applyMatrix3( this.normalMatrix )
  21284. .normalize()
  21285. .multiplyScalar( this.size )
  21286. .add( vertices[ i2 ] );
  21287. }
  21288. this.geometry.verticesNeedUpdate = true;
  21289. return this;
  21290. };
  21291. /**
  21292. * @author mrdoob / http://mrdoob.com/
  21293. */
  21294. THREE.GridHelper = function ( size, step ) {
  21295. var geometry = new THREE.Geometry();
  21296. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21297. this.color1 = new THREE.Color( 0x444444 );
  21298. this.color2 = new THREE.Color( 0x888888 );
  21299. for ( var i = - size; i <= size; i += step ) {
  21300. geometry.vertices.push(
  21301. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21302. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21303. );
  21304. var color = i === 0 ? this.color1 : this.color2;
  21305. geometry.colors.push( color, color, color, color );
  21306. }
  21307. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21308. };
  21309. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21310. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21311. this.color1.set( colorCenterLine );
  21312. this.color2.set( colorGrid );
  21313. this.geometry.colorsNeedUpdate = true;
  21314. }
  21315. /**
  21316. * @author alteredq / http://alteredqualia.com/
  21317. * @author mrdoob / http://mrdoob.com/
  21318. */
  21319. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21320. THREE.Object3D.call( this );
  21321. this.light = light;
  21322. this.light.updateMatrixWorld();
  21323. this.matrixWorld = light.matrixWorld;
  21324. this.matrixAutoUpdate = false;
  21325. this.colors = [ new THREE.Color(), new THREE.Color() ];
  21326. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21327. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21328. for ( var i = 0, il = 8; i < il; i ++ ) {
  21329. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  21330. }
  21331. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  21332. this.lightSphere = new THREE.Mesh( geometry, material );
  21333. this.add( this.lightSphere );
  21334. this.update();
  21335. };
  21336. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21337. THREE.HemisphereLightHelper.prototype.dispose = function () {
  21338. this.lightSphere.geometry.dispose();
  21339. this.lightSphere.material.dispose();
  21340. };
  21341. THREE.HemisphereLightHelper.prototype.update = function () {
  21342. var vector = new THREE.Vector3();
  21343. return function () {
  21344. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  21345. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21346. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  21347. this.lightSphere.geometry.colorsNeedUpdate = true;
  21348. }
  21349. }();
  21350. /**
  21351. * @author alteredq / http://alteredqualia.com/
  21352. * @author mrdoob / http://mrdoob.com/
  21353. */
  21354. THREE.PointLightHelper = function ( light, sphereSize ) {
  21355. this.light = light;
  21356. this.light.updateMatrixWorld();
  21357. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21358. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21359. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21360. THREE.Mesh.call( this, geometry, material );
  21361. this.matrixWorld = this.light.matrixWorld;
  21362. this.matrixAutoUpdate = false;
  21363. /*
  21364. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21365. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21366. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21367. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21368. var d = light.distance;
  21369. if ( d === 0.0 ) {
  21370. this.lightDistance.visible = false;
  21371. } else {
  21372. this.lightDistance.scale.set( d, d, d );
  21373. }
  21374. this.add( this.lightDistance );
  21375. */
  21376. };
  21377. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21378. THREE.PointLightHelper.prototype.dispose = function () {
  21379. this.geometry.dispose();
  21380. this.material.dispose();
  21381. };
  21382. THREE.PointLightHelper.prototype.update = function () {
  21383. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21384. /*
  21385. var d = this.light.distance;
  21386. if ( d === 0.0 ) {
  21387. this.lightDistance.visible = false;
  21388. } else {
  21389. this.lightDistance.visible = true;
  21390. this.lightDistance.scale.set( d, d, d );
  21391. }
  21392. */
  21393. };
  21394. /**
  21395. * @author alteredq / http://alteredqualia.com/
  21396. * @author mrdoob / http://mrdoob.com/
  21397. * @author WestLangley / http://github.com/WestLangley
  21398. */
  21399. THREE.SpotLightHelper = function ( light ) {
  21400. THREE.Object3D.call( this );
  21401. this.light = light;
  21402. this.light.updateMatrixWorld();
  21403. this.matrixWorld = light.matrixWorld;
  21404. this.matrixAutoUpdate = false;
  21405. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21406. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21407. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21408. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21409. this.cone = new THREE.Mesh( geometry, material );
  21410. this.add( this.cone );
  21411. this.update();
  21412. };
  21413. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21414. THREE.SpotLightHelper.prototype.dispose = function () {
  21415. this.cone.geometry.dispose();
  21416. this.cone.material.dispose();
  21417. };
  21418. THREE.SpotLightHelper.prototype.update = function () {
  21419. var vector = new THREE.Vector3();
  21420. var vector2 = new THREE.Vector3();
  21421. return function () {
  21422. var coneLength = this.light.distance ? this.light.distance : 10000;
  21423. var coneWidth = coneLength * Math.tan( this.light.angle );
  21424. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  21425. vector.setFromMatrixPosition( this.light.matrixWorld );
  21426. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  21427. this.cone.lookAt( vector2.sub( vector ) );
  21428. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21429. };
  21430. }();
  21431. /**
  21432. * @author mrdoob / http://mrdoob.com/
  21433. * @author WestLangley / http://github.com/WestLangley
  21434. */
  21435. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21436. this.object = object;
  21437. this.size = ( size !== undefined ) ? size : 1;
  21438. var color = ( hex !== undefined ) ? hex : 0xff0000;
  21439. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21440. var geometry = new THREE.Geometry();
  21441. var vertices = object.geometry.vertices;
  21442. var faces = object.geometry.faces;
  21443. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21444. var face = faces[ i ];
  21445. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21446. geometry.vertices.push( new THREE.Vector3() );
  21447. geometry.vertices.push( new THREE.Vector3() );
  21448. }
  21449. }
  21450. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21451. this.matrixAutoUpdate = false;
  21452. this.normalMatrix = new THREE.Matrix3();
  21453. this.update();
  21454. };
  21455. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21456. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21457. var v1 = new THREE.Vector3();
  21458. return function( object ) {
  21459. var keys = [ 'a', 'b', 'c', 'd' ];
  21460. this.object.updateMatrixWorld( true );
  21461. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21462. var vertices = this.geometry.vertices;
  21463. var verts = this.object.geometry.vertices;
  21464. var faces = this.object.geometry.faces;
  21465. var worldMatrix = this.object.matrixWorld;
  21466. var idx = 0;
  21467. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21468. var face = faces[ i ];
  21469. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21470. var vertexId = face[ keys[ j ] ];
  21471. var vertex = verts[ vertexId ];
  21472. var normal = face.vertexNormals[ j ];
  21473. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21474. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21475. v1.add( vertices[ idx ] );
  21476. idx = idx + 1;
  21477. vertices[ idx ].copy( v1 );
  21478. idx = idx + 1;
  21479. }
  21480. }
  21481. this.geometry.verticesNeedUpdate = true;
  21482. return this;
  21483. }
  21484. }());
  21485. /**
  21486. * @author mrdoob / http://mrdoob.com/
  21487. * @author WestLangley / http://github.com/WestLangley
  21488. */
  21489. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21490. this.object = object;
  21491. this.size = ( size !== undefined ) ? size : 1;
  21492. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  21493. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21494. var geometry = new THREE.Geometry();
  21495. var vertices = object.geometry.vertices;
  21496. var faces = object.geometry.faces;
  21497. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21498. var face = faces[ i ];
  21499. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21500. geometry.vertices.push( new THREE.Vector3() );
  21501. geometry.vertices.push( new THREE.Vector3() );
  21502. }
  21503. }
  21504. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21505. this.matrixAutoUpdate = false;
  21506. this.update();
  21507. };
  21508. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21509. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21510. var v1 = new THREE.Vector3();
  21511. return function( object ) {
  21512. var keys = [ 'a', 'b', 'c', 'd' ];
  21513. this.object.updateMatrixWorld( true );
  21514. var vertices = this.geometry.vertices;
  21515. var verts = this.object.geometry.vertices;
  21516. var faces = this.object.geometry.faces;
  21517. var worldMatrix = this.object.matrixWorld;
  21518. var idx = 0;
  21519. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21520. var face = faces[ i ];
  21521. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21522. var vertexId = face[ keys[ j ] ];
  21523. var vertex = verts[ vertexId ];
  21524. var tangent = face.vertexTangents[ j ];
  21525. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21526. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21527. v1.add( vertices[ idx ] );
  21528. idx = idx + 1;
  21529. vertices[ idx ].copy( v1 );
  21530. idx = idx + 1;
  21531. }
  21532. }
  21533. this.geometry.verticesNeedUpdate = true;
  21534. return this;
  21535. }
  21536. }());
  21537. /**
  21538. * @author mrdoob / http://mrdoob.com/
  21539. */
  21540. THREE.WireframeHelper = function ( object, hex ) {
  21541. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21542. var edge = [ 0, 0 ], hash = {};
  21543. var sortFunction = function ( a, b ) { return a - b };
  21544. var keys = [ 'a', 'b', 'c' ];
  21545. var geometry = new THREE.BufferGeometry();
  21546. if ( object.geometry instanceof THREE.Geometry ) {
  21547. var vertices = object.geometry.vertices;
  21548. var faces = object.geometry.faces;
  21549. var numEdges = 0;
  21550. // allocate maximal size
  21551. var edges = new Uint32Array( 6 * faces.length );
  21552. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21553. var face = faces[ i ];
  21554. for ( var j = 0; j < 3; j ++ ) {
  21555. edge[ 0 ] = face[ keys[ j ] ];
  21556. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21557. edge.sort( sortFunction );
  21558. var key = edge.toString();
  21559. if ( hash[ key ] === undefined ) {
  21560. edges[ 2 * numEdges ] = edge[ 0 ];
  21561. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21562. hash[ key ] = true;
  21563. numEdges ++;
  21564. }
  21565. }
  21566. }
  21567. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21568. var coords = geometry.attributes.position.array;
  21569. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21570. for ( var j = 0; j < 2; j ++ ) {
  21571. var vertex = vertices[ edges [ 2 * i + j] ];
  21572. var index = 6 * i + 3 * j;
  21573. coords[ index + 0 ] = vertex.x;
  21574. coords[ index + 1 ] = vertex.y;
  21575. coords[ index + 2 ] = vertex.z;
  21576. }
  21577. }
  21578. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  21579. var vertices = object.geometry.attributes.position.array;
  21580. var indices = object.geometry.attributes.index.array;
  21581. var offsets = object.geometry.offsets;
  21582. var numEdges = 0;
  21583. // allocate maximal size
  21584. var edges = new Uint32Array( 2 * indices.length );
  21585. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  21586. var start = offsets[ o ].start;
  21587. var count = offsets[ o ].count;
  21588. var index = offsets[ o ].index;
  21589. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21590. for ( var j = 0; j < 3; j ++ ) {
  21591. edge[ 0 ] = index + indices[ i + j ];
  21592. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  21593. edge.sort( sortFunction );
  21594. var key = edge.toString();
  21595. if ( hash[ key ] === undefined ) {
  21596. edges[ 2 * numEdges ] = edge[ 0 ];
  21597. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21598. hash[ key ] = true;
  21599. numEdges ++;
  21600. }
  21601. }
  21602. }
  21603. }
  21604. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21605. var coords = geometry.attributes.position.array;
  21606. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21607. for ( var j = 0; j < 2; j ++ ) {
  21608. var index = 6 * i + 3 * j;
  21609. var index2 = 3 * edges[ 2 * i + j];
  21610. coords[ index + 0 ] = vertices[ index2 ];
  21611. coords[ index + 1 ] = vertices[ index2 + 1 ];
  21612. coords[ index + 2 ] = vertices[ index2 + 2 ];
  21613. }
  21614. }
  21615. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  21616. var vertices = object.geometry.attributes.position.array;
  21617. var numEdges = vertices.length / 3;
  21618. var numTris = numEdges / 3;
  21619. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21620. var coords = geometry.attributes.position.array;
  21621. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21622. for ( var j = 0; j < 3; j ++ ) {
  21623. var index = 18 * i + 6 * j;
  21624. var index1 = 9 * i + 3 * j;
  21625. coords[ index + 0 ] = vertices[ index1 ];
  21626. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21627. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21628. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21629. coords[ index + 3 ] = vertices[ index2 ];
  21630. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21631. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21632. }
  21633. }
  21634. }
  21635. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21636. this.matrixAutoUpdate = false;
  21637. this.matrixWorld = object.matrixWorld;
  21638. };
  21639. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21640. /**
  21641. * @author alteredq / http://alteredqualia.com/
  21642. */
  21643. THREE.ImmediateRenderObject = function () {
  21644. THREE.Object3D.call( this );
  21645. this.render = function ( renderCallback ) { };
  21646. };
  21647. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21648. /**
  21649. * @author mikael emtinger / http://gomo.se/
  21650. * @author alteredq / http://alteredqualia.com/
  21651. */
  21652. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21653. THREE.Object3D.call( this );
  21654. this.lensFlares = [];
  21655. this.positionScreen = new THREE.Vector3();
  21656. this.customUpdateCallback = undefined;
  21657. if( texture !== undefined ) {
  21658. this.add( texture, size, distance, blending, color );
  21659. }
  21660. };
  21661. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21662. /*
  21663. * Add: adds another flare
  21664. */
  21665. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21666. if( size === undefined ) size = -1;
  21667. if( distance === undefined ) distance = 0;
  21668. if( opacity === undefined ) opacity = 1;
  21669. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21670. if( blending === undefined ) blending = THREE.NormalBlending;
  21671. distance = Math.min( distance, Math.max( 0, distance ) );
  21672. this.lensFlares.push( { texture: texture, // THREE.Texture
  21673. size: size, // size in pixels (-1 = use texture.width)
  21674. distance: distance, // distance (0-1) from light source (0=at light source)
  21675. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21676. scale: 1, // scale
  21677. rotation: 1, // rotation
  21678. opacity: opacity, // opacity
  21679. color: color, // color
  21680. blending: blending } ); // blending
  21681. };
  21682. /*
  21683. * Update lens flares update positions on all flares based on the screen position
  21684. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21685. */
  21686. THREE.LensFlare.prototype.updateLensFlares = function () {
  21687. var f, fl = this.lensFlares.length;
  21688. var flare;
  21689. var vecX = -this.positionScreen.x * 2;
  21690. var vecY = -this.positionScreen.y * 2;
  21691. for( f = 0; f < fl; f ++ ) {
  21692. flare = this.lensFlares[ f ];
  21693. flare.x = this.positionScreen.x + vecX * flare.distance;
  21694. flare.y = this.positionScreen.y + vecY * flare.distance;
  21695. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21696. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21697. }
  21698. };
  21699. /**
  21700. * @author alteredq / http://alteredqualia.com/
  21701. */
  21702. THREE.MorphBlendMesh = function( geometry, material ) {
  21703. THREE.Mesh.call( this, geometry, material );
  21704. this.animationsMap = {};
  21705. this.animationsList = [];
  21706. // prepare default animation
  21707. // (all frames played together in 1 second)
  21708. var numFrames = this.geometry.morphTargets.length;
  21709. var name = "__default";
  21710. var startFrame = 0;
  21711. var endFrame = numFrames - 1;
  21712. var fps = numFrames / 1;
  21713. this.createAnimation( name, startFrame, endFrame, fps );
  21714. this.setAnimationWeight( name, 1 );
  21715. };
  21716. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21717. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21718. var animation = {
  21719. startFrame: start,
  21720. endFrame: end,
  21721. length: end - start + 1,
  21722. fps: fps,
  21723. duration: ( end - start ) / fps,
  21724. lastFrame: 0,
  21725. currentFrame: 0,
  21726. active: false,
  21727. time: 0,
  21728. direction: 1,
  21729. weight: 1,
  21730. directionBackwards: false,
  21731. mirroredLoop: false
  21732. };
  21733. this.animationsMap[ name ] = animation;
  21734. this.animationsList.push( animation );
  21735. };
  21736. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21737. var pattern = /([a-z]+)(\d+)/;
  21738. var firstAnimation, frameRanges = {};
  21739. var geometry = this.geometry;
  21740. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21741. var morph = geometry.morphTargets[ i ];
  21742. var chunks = morph.name.match( pattern );
  21743. if ( chunks && chunks.length > 1 ) {
  21744. var name = chunks[ 1 ];
  21745. var num = chunks[ 2 ];
  21746. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21747. var range = frameRanges[ name ];
  21748. if ( i < range.start ) range.start = i;
  21749. if ( i > range.end ) range.end = i;
  21750. if ( ! firstAnimation ) firstAnimation = name;
  21751. }
  21752. }
  21753. for ( var name in frameRanges ) {
  21754. var range = frameRanges[ name ];
  21755. this.createAnimation( name, range.start, range.end, fps );
  21756. }
  21757. this.firstAnimation = firstAnimation;
  21758. };
  21759. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21760. var animation = this.animationsMap[ name ];
  21761. if ( animation ) {
  21762. animation.direction = 1;
  21763. animation.directionBackwards = false;
  21764. }
  21765. };
  21766. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21767. var animation = this.animationsMap[ name ];
  21768. if ( animation ) {
  21769. animation.direction = -1;
  21770. animation.directionBackwards = true;
  21771. }
  21772. };
  21773. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21774. var animation = this.animationsMap[ name ];
  21775. if ( animation ) {
  21776. animation.fps = fps;
  21777. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21778. }
  21779. };
  21780. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21781. var animation = this.animationsMap[ name ];
  21782. if ( animation ) {
  21783. animation.duration = duration;
  21784. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21785. }
  21786. };
  21787. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21788. var animation = this.animationsMap[ name ];
  21789. if ( animation ) {
  21790. animation.weight = weight;
  21791. }
  21792. };
  21793. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21794. var animation = this.animationsMap[ name ];
  21795. if ( animation ) {
  21796. animation.time = time;
  21797. }
  21798. };
  21799. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21800. var time = 0;
  21801. var animation = this.animationsMap[ name ];
  21802. if ( animation ) {
  21803. time = animation.time;
  21804. }
  21805. return time;
  21806. };
  21807. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21808. var duration = -1;
  21809. var animation = this.animationsMap[ name ];
  21810. if ( animation ) {
  21811. duration = animation.duration;
  21812. }
  21813. return duration;
  21814. };
  21815. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21816. var animation = this.animationsMap[ name ];
  21817. if ( animation ) {
  21818. animation.time = 0;
  21819. animation.active = true;
  21820. } else {
  21821. console.warn( "animation[" + name + "] undefined" );
  21822. }
  21823. };
  21824. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21825. var animation = this.animationsMap[ name ];
  21826. if ( animation ) {
  21827. animation.active = false;
  21828. }
  21829. };
  21830. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21831. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21832. var animation = this.animationsList[ i ];
  21833. if ( ! animation.active ) continue;
  21834. var frameTime = animation.duration / animation.length;
  21835. animation.time += animation.direction * delta;
  21836. if ( animation.mirroredLoop ) {
  21837. if ( animation.time > animation.duration || animation.time < 0 ) {
  21838. animation.direction *= -1;
  21839. if ( animation.time > animation.duration ) {
  21840. animation.time = animation.duration;
  21841. animation.directionBackwards = true;
  21842. }
  21843. if ( animation.time < 0 ) {
  21844. animation.time = 0;
  21845. animation.directionBackwards = false;
  21846. }
  21847. }
  21848. } else {
  21849. animation.time = animation.time % animation.duration;
  21850. if ( animation.time < 0 ) animation.time += animation.duration;
  21851. }
  21852. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21853. var weight = animation.weight;
  21854. if ( keyframe !== animation.currentFrame ) {
  21855. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21856. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21857. this.morphTargetInfluences[ keyframe ] = 0;
  21858. animation.lastFrame = animation.currentFrame;
  21859. animation.currentFrame = keyframe;
  21860. }
  21861. var mix = ( animation.time % frameTime ) / frameTime;
  21862. if ( animation.directionBackwards ) mix = 1 - mix;
  21863. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21864. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21865. }
  21866. };
  21867. /**
  21868. * @author mikael emtinger / http://gomo.se/
  21869. * @author alteredq / http://alteredqualia.com/
  21870. */
  21871. THREE.LensFlarePlugin = function () {
  21872. var _gl, _renderer, _precision, _lensFlare = {};
  21873. this.init = function ( renderer ) {
  21874. _gl = renderer.context;
  21875. _renderer = renderer;
  21876. _precision = renderer.getPrecision();
  21877. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21878. _lensFlare.faces = new Uint16Array( 6 );
  21879. var i = 0;
  21880. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21881. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21882. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21883. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21884. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21885. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21886. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21887. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21888. i = 0;
  21889. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21890. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21891. // buffers
  21892. _lensFlare.vertexBuffer = _gl.createBuffer();
  21893. _lensFlare.elementBuffer = _gl.createBuffer();
  21894. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21895. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21896. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21897. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21898. // textures
  21899. _lensFlare.tempTexture = _gl.createTexture();
  21900. _lensFlare.occlusionTexture = _gl.createTexture();
  21901. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21902. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21903. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21904. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21905. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21906. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21907. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21908. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21909. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21910. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21911. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21912. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21913. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21914. _lensFlare.hasVertexTexture = false;
  21915. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21916. } else {
  21917. _lensFlare.hasVertexTexture = true;
  21918. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21919. }
  21920. _lensFlare.attributes = {};
  21921. _lensFlare.uniforms = {};
  21922. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21923. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21924. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21925. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21926. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21927. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21928. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21929. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21930. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21931. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21932. };
  21933. /*
  21934. * Render lens flares
  21935. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21936. * reads these back and calculates occlusion.
  21937. * Then _lensFlare.update_lensFlares() is called to re-position and
  21938. * update transparency of flares. Then they are rendered.
  21939. *
  21940. */
  21941. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21942. var flares = scene.__webglFlares,
  21943. nFlares = flares.length;
  21944. if ( ! nFlares ) return;
  21945. var tempPosition = new THREE.Vector3();
  21946. var invAspect = viewportHeight / viewportWidth,
  21947. halfViewportWidth = viewportWidth * 0.5,
  21948. halfViewportHeight = viewportHeight * 0.5;
  21949. var size = 16 / viewportHeight,
  21950. scale = new THREE.Vector2( size * invAspect, size );
  21951. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21952. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21953. var uniforms = _lensFlare.uniforms,
  21954. attributes = _lensFlare.attributes;
  21955. // set _lensFlare program and reset blending
  21956. _gl.useProgram( _lensFlare.program );
  21957. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21958. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21959. // loop through all lens flares to update their occlusion and positions
  21960. // setup gl and common used attribs/unforms
  21961. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21962. _gl.uniform1i( uniforms.map, 1 );
  21963. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21964. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21965. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21966. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21967. _gl.disable( _gl.CULL_FACE );
  21968. _gl.depthMask( false );
  21969. var i, j, jl, flare, sprite;
  21970. for ( i = 0; i < nFlares; i ++ ) {
  21971. size = 16 / viewportHeight;
  21972. scale.set( size * invAspect, size );
  21973. // calc object screen position
  21974. flare = flares[ i ];
  21975. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21976. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21977. tempPosition.applyProjection( camera.projectionMatrix );
  21978. // setup arrays for gl programs
  21979. screenPosition.copy( tempPosition )
  21980. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21981. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21982. // screen cull
  21983. if ( _lensFlare.hasVertexTexture || (
  21984. screenPositionPixels.x > 0 &&
  21985. screenPositionPixels.x < viewportWidth &&
  21986. screenPositionPixels.y > 0 &&
  21987. screenPositionPixels.y < viewportHeight ) ) {
  21988. // save current RGB to temp texture
  21989. _gl.activeTexture( _gl.TEXTURE1 );
  21990. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21991. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21992. // render pink quad
  21993. _gl.uniform1i( uniforms.renderType, 0 );
  21994. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21995. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21996. _gl.disable( _gl.BLEND );
  21997. _gl.enable( _gl.DEPTH_TEST );
  21998. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21999. // copy result to occlusionMap
  22000. _gl.activeTexture( _gl.TEXTURE0 );
  22001. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  22002. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  22003. // restore graphics
  22004. _gl.uniform1i( uniforms.renderType, 1 );
  22005. _gl.disable( _gl.DEPTH_TEST );
  22006. _gl.activeTexture( _gl.TEXTURE1 );
  22007. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  22008. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22009. // update object positions
  22010. flare.positionScreen.copy( screenPosition )
  22011. if ( flare.customUpdateCallback ) {
  22012. flare.customUpdateCallback( flare );
  22013. } else {
  22014. flare.updateLensFlares();
  22015. }
  22016. // render flares
  22017. _gl.uniform1i( uniforms.renderType, 2 );
  22018. _gl.enable( _gl.BLEND );
  22019. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  22020. sprite = flare.lensFlares[ j ];
  22021. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  22022. screenPosition.x = sprite.x;
  22023. screenPosition.y = sprite.y;
  22024. screenPosition.z = sprite.z;
  22025. size = sprite.size * sprite.scale / viewportHeight;
  22026. scale.x = size * invAspect;
  22027. scale.y = size;
  22028. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  22029. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  22030. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  22031. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  22032. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  22033. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  22034. _renderer.setTexture( sprite.texture, 1 );
  22035. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22036. }
  22037. }
  22038. }
  22039. }
  22040. // restore gl
  22041. _gl.enable( _gl.CULL_FACE );
  22042. _gl.enable( _gl.DEPTH_TEST );
  22043. _gl.depthMask( true );
  22044. };
  22045. function createProgram ( shader, precision ) {
  22046. var program = _gl.createProgram();
  22047. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22048. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22049. var prefix = "precision " + precision + " float;\n";
  22050. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  22051. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  22052. _gl.compileShader( fragmentShader );
  22053. _gl.compileShader( vertexShader );
  22054. _gl.attachShader( program, fragmentShader );
  22055. _gl.attachShader( program, vertexShader );
  22056. _gl.linkProgram( program );
  22057. return program;
  22058. };
  22059. };
  22060. /**
  22061. * @author alteredq / http://alteredqualia.com/
  22062. */
  22063. THREE.ShadowMapPlugin = function () {
  22064. var _gl,
  22065. _renderer,
  22066. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22067. _frustum = new THREE.Frustum(),
  22068. _projScreenMatrix = new THREE.Matrix4(),
  22069. _min = new THREE.Vector3(),
  22070. _max = new THREE.Vector3(),
  22071. _matrixPosition = new THREE.Vector3();
  22072. this.init = function ( renderer ) {
  22073. _gl = renderer.context;
  22074. _renderer = renderer;
  22075. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22076. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22077. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22078. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22079. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22080. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22081. _depthMaterial._shadowPass = true;
  22082. _depthMaterialMorph._shadowPass = true;
  22083. _depthMaterialSkin._shadowPass = true;
  22084. _depthMaterialMorphSkin._shadowPass = true;
  22085. };
  22086. this.render = function ( scene, camera ) {
  22087. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  22088. this.update( scene, camera );
  22089. };
  22090. this.update = function ( scene, camera ) {
  22091. var i, il, j, jl, n,
  22092. shadowMap, shadowMatrix, shadowCamera,
  22093. program, buffer, material,
  22094. webglObject, object, light,
  22095. renderList,
  22096. lights = [],
  22097. k = 0,
  22098. fog = null;
  22099. // set GL state for depth map
  22100. _gl.clearColor( 1, 1, 1, 1 );
  22101. _gl.disable( _gl.BLEND );
  22102. _gl.enable( _gl.CULL_FACE );
  22103. _gl.frontFace( _gl.CCW );
  22104. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  22105. _gl.cullFace( _gl.FRONT );
  22106. } else {
  22107. _gl.cullFace( _gl.BACK );
  22108. }
  22109. _renderer.setDepthTest( true );
  22110. // preprocess lights
  22111. // - skip lights that are not casting shadows
  22112. // - create virtual lights for cascaded shadow maps
  22113. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  22114. light = scene.__lights[ i ];
  22115. if ( ! light.castShadow ) continue;
  22116. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  22117. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  22118. var virtualLight;
  22119. if ( ! light.shadowCascadeArray[ n ] ) {
  22120. virtualLight = createVirtualLight( light, n );
  22121. virtualLight.originalCamera = camera;
  22122. var gyro = new THREE.Gyroscope();
  22123. gyro.position.copy( light.shadowCascadeOffset );
  22124. gyro.add( virtualLight );
  22125. gyro.add( virtualLight.target );
  22126. camera.add( gyro );
  22127. light.shadowCascadeArray[ n ] = virtualLight;
  22128. console.log( "Created virtualLight", virtualLight );
  22129. } else {
  22130. virtualLight = light.shadowCascadeArray[ n ];
  22131. }
  22132. updateVirtualLight( light, n );
  22133. lights[ k ] = virtualLight;
  22134. k ++;
  22135. }
  22136. } else {
  22137. lights[ k ] = light;
  22138. k ++;
  22139. }
  22140. }
  22141. // render depth map
  22142. for ( i = 0, il = lights.length; i < il; i ++ ) {
  22143. light = lights[ i ];
  22144. if ( ! light.shadowMap ) {
  22145. var shadowFilter = THREE.LinearFilter;
  22146. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  22147. shadowFilter = THREE.NearestFilter;
  22148. }
  22149. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  22150. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  22151. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  22152. light.shadowMatrix = new THREE.Matrix4();
  22153. }
  22154. if ( ! light.shadowCamera ) {
  22155. if ( light instanceof THREE.SpotLight ) {
  22156. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  22157. } else if ( light instanceof THREE.DirectionalLight ) {
  22158. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  22159. } else {
  22160. console.error( "Unsupported light type for shadow" );
  22161. continue;
  22162. }
  22163. scene.add( light.shadowCamera );
  22164. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22165. }
  22166. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  22167. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  22168. light.shadowCamera.add( light.cameraHelper );
  22169. }
  22170. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  22171. updateShadowCamera( camera, light );
  22172. }
  22173. shadowMap = light.shadowMap;
  22174. shadowMatrix = light.shadowMatrix;
  22175. shadowCamera = light.shadowCamera;
  22176. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  22177. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  22178. shadowCamera.lookAt( _matrixPosition );
  22179. shadowCamera.updateMatrixWorld();
  22180. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  22181. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  22182. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  22183. // compute shadow matrix
  22184. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  22185. 0.0, 0.5, 0.0, 0.5,
  22186. 0.0, 0.0, 0.5, 0.5,
  22187. 0.0, 0.0, 0.0, 1.0 );
  22188. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  22189. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  22190. // update camera matrices and frustum
  22191. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  22192. _frustum.setFromMatrix( _projScreenMatrix );
  22193. // render shadow map
  22194. _renderer.setRenderTarget( shadowMap );
  22195. _renderer.clear();
  22196. // set object matrices & frustum culling
  22197. renderList = scene.__webglObjects;
  22198. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22199. webglObject = renderList[ j ];
  22200. object = webglObject.object;
  22201. webglObject.render = false;
  22202. if ( object.visible && object.castShadow ) {
  22203. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22204. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  22205. webglObject.render = true;
  22206. }
  22207. }
  22208. }
  22209. // render regular objects
  22210. var objectMaterial, useMorphing, useSkinning;
  22211. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22212. webglObject = renderList[ j ];
  22213. if ( webglObject.render ) {
  22214. object = webglObject.object;
  22215. buffer = webglObject.buffer;
  22216. // culling is overriden globally for all objects
  22217. // while rendering depth map
  22218. // need to deal with MeshFaceMaterial somehow
  22219. // in that case just use the first of material.materials for now
  22220. // (proper solution would require to break objects by materials
  22221. // similarly to regular rendering and then set corresponding
  22222. // depth materials per each chunk instead of just once per object)
  22223. objectMaterial = getObjectMaterial( object );
  22224. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22225. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22226. if ( object.customDepthMaterial ) {
  22227. material = object.customDepthMaterial;
  22228. } else if ( useSkinning ) {
  22229. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22230. } else if ( useMorphing ) {
  22231. material = _depthMaterialMorph;
  22232. } else {
  22233. material = _depthMaterial;
  22234. }
  22235. if ( buffer instanceof THREE.BufferGeometry ) {
  22236. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  22237. } else {
  22238. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  22239. }
  22240. }
  22241. }
  22242. // set matrices and render immediate objects
  22243. renderList = scene.__webglObjectsImmediate;
  22244. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22245. webglObject = renderList[ j ];
  22246. object = webglObject.object;
  22247. if ( object.visible && object.castShadow ) {
  22248. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  22249. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  22250. }
  22251. }
  22252. }
  22253. // restore GL state
  22254. var clearColor = _renderer.getClearColor(),
  22255. clearAlpha = _renderer.getClearAlpha();
  22256. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22257. _gl.enable( _gl.BLEND );
  22258. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  22259. _gl.cullFace( _gl.BACK );
  22260. }
  22261. };
  22262. function createVirtualLight( light, cascade ) {
  22263. var virtualLight = new THREE.DirectionalLight();
  22264. virtualLight.isVirtual = true;
  22265. virtualLight.onlyShadow = true;
  22266. virtualLight.castShadow = true;
  22267. virtualLight.shadowCameraNear = light.shadowCameraNear;
  22268. virtualLight.shadowCameraFar = light.shadowCameraFar;
  22269. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  22270. virtualLight.shadowCameraRight = light.shadowCameraRight;
  22271. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  22272. virtualLight.shadowCameraTop = light.shadowCameraTop;
  22273. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22274. virtualLight.shadowDarkness = light.shadowDarkness;
  22275. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22276. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  22277. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  22278. virtualLight.pointsWorld = [];
  22279. virtualLight.pointsFrustum = [];
  22280. var pointsWorld = virtualLight.pointsWorld,
  22281. pointsFrustum = virtualLight.pointsFrustum;
  22282. for ( var i = 0; i < 8; i ++ ) {
  22283. pointsWorld[ i ] = new THREE.Vector3();
  22284. pointsFrustum[ i ] = new THREE.Vector3();
  22285. }
  22286. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22287. var farZ = light.shadowCascadeFarZ[ cascade ];
  22288. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  22289. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  22290. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  22291. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  22292. pointsFrustum[ 4 ].set( -1, -1, farZ );
  22293. pointsFrustum[ 5 ].set( 1, -1, farZ );
  22294. pointsFrustum[ 6 ].set( -1, 1, farZ );
  22295. pointsFrustum[ 7 ].set( 1, 1, farZ );
  22296. return virtualLight;
  22297. }
  22298. // Synchronize virtual light with the original light
  22299. function updateVirtualLight( light, cascade ) {
  22300. var virtualLight = light.shadowCascadeArray[ cascade ];
  22301. virtualLight.position.copy( light.position );
  22302. virtualLight.target.position.copy( light.target.position );
  22303. virtualLight.lookAt( virtualLight.target );
  22304. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22305. virtualLight.shadowDarkness = light.shadowDarkness;
  22306. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22307. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22308. var farZ = light.shadowCascadeFarZ[ cascade ];
  22309. var pointsFrustum = virtualLight.pointsFrustum;
  22310. pointsFrustum[ 0 ].z = nearZ;
  22311. pointsFrustum[ 1 ].z = nearZ;
  22312. pointsFrustum[ 2 ].z = nearZ;
  22313. pointsFrustum[ 3 ].z = nearZ;
  22314. pointsFrustum[ 4 ].z = farZ;
  22315. pointsFrustum[ 5 ].z = farZ;
  22316. pointsFrustum[ 6 ].z = farZ;
  22317. pointsFrustum[ 7 ].z = farZ;
  22318. }
  22319. // Fit shadow camera's ortho frustum to camera frustum
  22320. function updateShadowCamera( camera, light ) {
  22321. var shadowCamera = light.shadowCamera,
  22322. pointsFrustum = light.pointsFrustum,
  22323. pointsWorld = light.pointsWorld;
  22324. _min.set( Infinity, Infinity, Infinity );
  22325. _max.set( -Infinity, -Infinity, -Infinity );
  22326. for ( var i = 0; i < 8; i ++ ) {
  22327. var p = pointsWorld[ i ];
  22328. p.copy( pointsFrustum[ i ] );
  22329. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  22330. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  22331. if ( p.x < _min.x ) _min.x = p.x;
  22332. if ( p.x > _max.x ) _max.x = p.x;
  22333. if ( p.y < _min.y ) _min.y = p.y;
  22334. if ( p.y > _max.y ) _max.y = p.y;
  22335. if ( p.z < _min.z ) _min.z = p.z;
  22336. if ( p.z > _max.z ) _max.z = p.z;
  22337. }
  22338. shadowCamera.left = _min.x;
  22339. shadowCamera.right = _max.x;
  22340. shadowCamera.top = _max.y;
  22341. shadowCamera.bottom = _min.y;
  22342. // can't really fit near/far
  22343. //shadowCamera.near = _min.z;
  22344. //shadowCamera.far = _max.z;
  22345. shadowCamera.updateProjectionMatrix();
  22346. }
  22347. // For the moment just ignore objects that have multiple materials with different animation methods
  22348. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  22349. function getObjectMaterial( object ) {
  22350. return object.material instanceof THREE.MeshFaceMaterial
  22351. ? object.material.materials[ 0 ]
  22352. : object.material;
  22353. };
  22354. };
  22355. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  22356. /**
  22357. * @author mikael emtinger / http://gomo.se/
  22358. * @author alteredq / http://alteredqualia.com/
  22359. */
  22360. THREE.SpritePlugin = function () {
  22361. var _gl, _renderer, _texture;
  22362. var vertices, faces, vertexBuffer, elementBuffer;
  22363. var program, attributes, uniforms;
  22364. this.init = function ( renderer ) {
  22365. _gl = renderer.context;
  22366. _renderer = renderer;
  22367. vertices = new Float32Array( [
  22368. - 0.5, - 0.5, 0, 0,
  22369. 0.5, - 0.5, 1, 0,
  22370. 0.5, 0.5, 1, 1,
  22371. - 0.5, 0.5, 0, 1
  22372. ] );
  22373. faces = new Uint16Array( [
  22374. 0, 1, 2,
  22375. 0, 2, 3
  22376. ] );
  22377. vertexBuffer = _gl.createBuffer();
  22378. elementBuffer = _gl.createBuffer();
  22379. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22380. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  22381. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22382. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  22383. program = createProgram();
  22384. attributes = {
  22385. position: _gl.getAttribLocation ( program, 'position' ),
  22386. uv: _gl.getAttribLocation ( program, 'uv' )
  22387. };
  22388. uniforms = {
  22389. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  22390. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  22391. rotation: _gl.getUniformLocation( program, 'rotation' ),
  22392. scale: _gl.getUniformLocation( program, 'scale' ),
  22393. color: _gl.getUniformLocation( program, 'color' ),
  22394. map: _gl.getUniformLocation( program, 'map' ),
  22395. opacity: _gl.getUniformLocation( program, 'opacity' ),
  22396. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  22397. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  22398. fogType: _gl.getUniformLocation( program, 'fogType' ),
  22399. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  22400. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  22401. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  22402. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  22403. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  22404. };
  22405. var canvas = document.createElement( 'canvas' );
  22406. canvas.width = 8;
  22407. canvas.height = 8;
  22408. var context = canvas.getContext( '2d' );
  22409. context.fillStyle = '#ffffff';
  22410. context.fillRect( 0, 0, canvas.width, canvas.height );
  22411. _texture = new THREE.Texture( canvas );
  22412. _texture.needsUpdate = true;
  22413. };
  22414. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22415. var sprites = scene.__webglSprites,
  22416. nSprites = sprites.length;
  22417. if ( ! nSprites ) return;
  22418. // setup gl
  22419. _gl.useProgram( program );
  22420. _gl.enableVertexAttribArray( attributes.position );
  22421. _gl.enableVertexAttribArray( attributes.uv );
  22422. _gl.disable( _gl.CULL_FACE );
  22423. _gl.enable( _gl.BLEND );
  22424. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22425. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22426. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22427. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22428. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22429. _gl.activeTexture( _gl.TEXTURE0 );
  22430. _gl.uniform1i( uniforms.map, 0 );
  22431. var oldFogType = 0;
  22432. var sceneFogType = 0;
  22433. var fog = scene.fog;
  22434. if ( fog ) {
  22435. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22436. if ( fog instanceof THREE.Fog ) {
  22437. _gl.uniform1f( uniforms.fogNear, fog.near );
  22438. _gl.uniform1f( uniforms.fogFar, fog.far );
  22439. _gl.uniform1i( uniforms.fogType, 1 );
  22440. oldFogType = 1;
  22441. sceneFogType = 1;
  22442. } else if ( fog instanceof THREE.FogExp2 ) {
  22443. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22444. _gl.uniform1i( uniforms.fogType, 2 );
  22445. oldFogType = 2;
  22446. sceneFogType = 2;
  22447. }
  22448. } else {
  22449. _gl.uniform1i( uniforms.fogType, 0 );
  22450. oldFogType = 0;
  22451. sceneFogType = 0;
  22452. }
  22453. // update positions and sort
  22454. var i, sprite, material, fogType, scale = [];
  22455. for( i = 0; i < nSprites; i ++ ) {
  22456. sprite = sprites[ i ];
  22457. material = sprite.material;
  22458. if ( sprite.visible === false ) continue;
  22459. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22460. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22461. }
  22462. sprites.sort( painterSortStable );
  22463. // render all sprites
  22464. for( i = 0; i < nSprites; i ++ ) {
  22465. sprite = sprites[ i ];
  22466. if ( sprite.visible === false ) continue;
  22467. material = sprite.material;
  22468. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22469. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22470. scale[ 0 ] = sprite.scale.x;
  22471. scale[ 1 ] = sprite.scale.y;
  22472. if ( scene.fog && material.fog ) {
  22473. fogType = sceneFogType;
  22474. } else {
  22475. fogType = 0;
  22476. }
  22477. if ( oldFogType !== fogType ) {
  22478. _gl.uniform1i( uniforms.fogType, fogType );
  22479. oldFogType = fogType;
  22480. }
  22481. if ( material.map !== null ) {
  22482. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  22483. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  22484. } else {
  22485. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  22486. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  22487. }
  22488. _gl.uniform1f( uniforms.opacity, material.opacity );
  22489. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22490. _gl.uniform1f( uniforms.rotation, material.rotation );
  22491. _gl.uniform2fv( uniforms.scale, scale );
  22492. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22493. _renderer.setDepthTest( material.depthTest );
  22494. _renderer.setDepthWrite( material.depthWrite );
  22495. if ( material.map && material.map.image && material.map.image.width ) {
  22496. _renderer.setTexture( material.map, 0 );
  22497. } else {
  22498. _renderer.setTexture( _texture, 0 );
  22499. }
  22500. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22501. }
  22502. // restore gl
  22503. _gl.enable( _gl.CULL_FACE );
  22504. };
  22505. function createProgram () {
  22506. var program = _gl.createProgram();
  22507. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22508. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22509. _gl.shaderSource( vertexShader, [
  22510. 'precision ' + _renderer.getPrecision() + ' float;',
  22511. 'uniform mat4 modelViewMatrix;',
  22512. 'uniform mat4 projectionMatrix;',
  22513. 'uniform float rotation;',
  22514. 'uniform vec2 scale;',
  22515. 'uniform vec2 uvOffset;',
  22516. 'uniform vec2 uvScale;',
  22517. 'attribute vec2 position;',
  22518. 'attribute vec2 uv;',
  22519. 'varying vec2 vUV;',
  22520. 'void main() {',
  22521. 'vUV = uvOffset + uv * uvScale;',
  22522. 'vec2 alignedPosition = position * scale;',
  22523. 'vec2 rotatedPosition;',
  22524. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  22525. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  22526. 'vec4 finalPosition;',
  22527. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  22528. 'finalPosition.xy += rotatedPosition;',
  22529. 'finalPosition = projectionMatrix * finalPosition;',
  22530. 'gl_Position = finalPosition;',
  22531. '}'
  22532. ].join( '\n' ) );
  22533. _gl.shaderSource( fragmentShader, [
  22534. 'precision ' + _renderer.getPrecision() + ' float;',
  22535. 'uniform vec3 color;',
  22536. 'uniform sampler2D map;',
  22537. 'uniform float opacity;',
  22538. 'uniform int fogType;',
  22539. 'uniform vec3 fogColor;',
  22540. 'uniform float fogDensity;',
  22541. 'uniform float fogNear;',
  22542. 'uniform float fogFar;',
  22543. 'uniform float alphaTest;',
  22544. 'varying vec2 vUV;',
  22545. 'void main() {',
  22546. 'vec4 texture = texture2D( map, vUV );',
  22547. 'if ( texture.a < alphaTest ) discard;',
  22548. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  22549. 'if ( fogType > 0 ) {',
  22550. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  22551. 'float fogFactor = 0.0;',
  22552. 'if ( fogType == 1 ) {',
  22553. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  22554. '} else {',
  22555. 'const float LOG2 = 1.442695;',
  22556. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  22557. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  22558. '}',
  22559. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  22560. '}',
  22561. '}'
  22562. ].join( '\n' ) );
  22563. _gl.compileShader( vertexShader );
  22564. _gl.compileShader( fragmentShader );
  22565. _gl.attachShader( program, vertexShader );
  22566. _gl.attachShader( program, fragmentShader );
  22567. _gl.linkProgram( program );
  22568. return program;
  22569. };
  22570. function painterSortStable ( a, b ) {
  22571. if ( a.z !== b.z ) {
  22572. return b.z - a.z;
  22573. } else {
  22574. return b.id - a.id;
  22575. }
  22576. };
  22577. };
  22578. /**
  22579. * @author alteredq / http://alteredqualia.com/
  22580. */
  22581. THREE.DepthPassPlugin = function () {
  22582. this.enabled = false;
  22583. this.renderTarget = null;
  22584. var _gl,
  22585. _renderer,
  22586. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22587. _frustum = new THREE.Frustum(),
  22588. _projScreenMatrix = new THREE.Matrix4();
  22589. this.init = function ( renderer ) {
  22590. _gl = renderer.context;
  22591. _renderer = renderer;
  22592. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22593. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22594. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22595. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22596. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22597. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22598. _depthMaterial._shadowPass = true;
  22599. _depthMaterialMorph._shadowPass = true;
  22600. _depthMaterialSkin._shadowPass = true;
  22601. _depthMaterialMorphSkin._shadowPass = true;
  22602. };
  22603. this.render = function ( scene, camera ) {
  22604. if ( ! this.enabled ) return;
  22605. this.update( scene, camera );
  22606. };
  22607. this.update = function ( scene, camera ) {
  22608. var i, il, j, jl, n,
  22609. program, buffer, material,
  22610. webglObject, object, light,
  22611. renderList,
  22612. fog = null;
  22613. // set GL state for depth map
  22614. _gl.clearColor( 1, 1, 1, 1 );
  22615. _gl.disable( _gl.BLEND );
  22616. _renderer.setDepthTest( true );
  22617. // update scene
  22618. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22619. // update camera matrices and frustum
  22620. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22621. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22622. _frustum.setFromMatrix( _projScreenMatrix );
  22623. // render depth map
  22624. _renderer.setRenderTarget( this.renderTarget );
  22625. _renderer.clear();
  22626. // set object matrices & frustum culling
  22627. renderList = scene.__webglObjects;
  22628. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22629. webglObject = renderList[ j ];
  22630. object = webglObject.object;
  22631. webglObject.render = false;
  22632. if ( object.visible ) {
  22633. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22634. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22635. webglObject.render = true;
  22636. }
  22637. }
  22638. }
  22639. // render regular objects
  22640. var objectMaterial, useMorphing, useSkinning;
  22641. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22642. webglObject = renderList[ j ];
  22643. if ( webglObject.render ) {
  22644. object = webglObject.object;
  22645. buffer = webglObject.buffer;
  22646. // todo: create proper depth material for particles
  22647. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22648. objectMaterial = getObjectMaterial( object );
  22649. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22650. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22651. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22652. if ( object.customDepthMaterial ) {
  22653. material = object.customDepthMaterial;
  22654. } else if ( useSkinning ) {
  22655. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22656. } else if ( useMorphing ) {
  22657. material = _depthMaterialMorph;
  22658. } else {
  22659. material = _depthMaterial;
  22660. }
  22661. if ( buffer instanceof THREE.BufferGeometry ) {
  22662. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22663. } else {
  22664. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22665. }
  22666. }
  22667. }
  22668. // set matrices and render immediate objects
  22669. renderList = scene.__webglObjectsImmediate;
  22670. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22671. webglObject = renderList[ j ];
  22672. object = webglObject.object;
  22673. if ( object.visible ) {
  22674. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22675. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22676. }
  22677. }
  22678. // restore GL state
  22679. var clearColor = _renderer.getClearColor(),
  22680. clearAlpha = _renderer.getClearAlpha();
  22681. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22682. _gl.enable( _gl.BLEND );
  22683. };
  22684. // For the moment just ignore objects that have multiple materials with different animation methods
  22685. // Only the first material will be taken into account for deciding which depth material to use
  22686. function getObjectMaterial( object ) {
  22687. return object.material instanceof THREE.MeshFaceMaterial
  22688. ? object.material.materials[ 0 ]
  22689. : object.material;
  22690. };
  22691. };
  22692. /**
  22693. * @author mikael emtinger / http://gomo.se/
  22694. */
  22695. THREE.ShaderFlares = {
  22696. 'lensFlareVertexTexture': {
  22697. vertexShader: [
  22698. "uniform lowp int renderType;",
  22699. "uniform vec3 screenPosition;",
  22700. "uniform vec2 scale;",
  22701. "uniform float rotation;",
  22702. "uniform sampler2D occlusionMap;",
  22703. "attribute vec2 position;",
  22704. "attribute vec2 uv;",
  22705. "varying vec2 vUV;",
  22706. "varying float vVisibility;",
  22707. "void main() {",
  22708. "vUV = uv;",
  22709. "vec2 pos = position;",
  22710. "if( renderType == 2 ) {",
  22711. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22712. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22713. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22714. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22715. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22716. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22717. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22718. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22719. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22720. "vVisibility = visibility.r / 9.0;",
  22721. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22722. "vVisibility *= visibility.b / 9.0;",
  22723. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22724. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22725. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22726. "}",
  22727. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22728. "}"
  22729. ].join( "\n" ),
  22730. fragmentShader: [
  22731. "uniform lowp int renderType;",
  22732. "uniform sampler2D map;",
  22733. "uniform float opacity;",
  22734. "uniform vec3 color;",
  22735. "varying vec2 vUV;",
  22736. "varying float vVisibility;",
  22737. "void main() {",
  22738. // pink square
  22739. "if( renderType == 0 ) {",
  22740. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22741. // restore
  22742. "} else if( renderType == 1 ) {",
  22743. "gl_FragColor = texture2D( map, vUV );",
  22744. // flare
  22745. "} else {",
  22746. "vec4 texture = texture2D( map, vUV );",
  22747. "texture.a *= opacity * vVisibility;",
  22748. "gl_FragColor = texture;",
  22749. "gl_FragColor.rgb *= color;",
  22750. "}",
  22751. "}"
  22752. ].join( "\n" )
  22753. },
  22754. 'lensFlare': {
  22755. vertexShader: [
  22756. "uniform lowp int renderType;",
  22757. "uniform vec3 screenPosition;",
  22758. "uniform vec2 scale;",
  22759. "uniform float rotation;",
  22760. "attribute vec2 position;",
  22761. "attribute vec2 uv;",
  22762. "varying vec2 vUV;",
  22763. "void main() {",
  22764. "vUV = uv;",
  22765. "vec2 pos = position;",
  22766. "if( renderType == 2 ) {",
  22767. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22768. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22769. "}",
  22770. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22771. "}"
  22772. ].join( "\n" ),
  22773. fragmentShader: [
  22774. "precision mediump float;",
  22775. "uniform lowp int renderType;",
  22776. "uniform sampler2D map;",
  22777. "uniform sampler2D occlusionMap;",
  22778. "uniform float opacity;",
  22779. "uniform vec3 color;",
  22780. "varying vec2 vUV;",
  22781. "void main() {",
  22782. // pink square
  22783. "if( renderType == 0 ) {",
  22784. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22785. // restore
  22786. "} else if( renderType == 1 ) {",
  22787. "gl_FragColor = texture2D( map, vUV );",
  22788. // flare
  22789. "} else {",
  22790. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22791. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22792. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22793. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22794. "visibility = ( 1.0 - visibility / 4.0 );",
  22795. "vec4 texture = texture2D( map, vUV );",
  22796. "texture.a *= opacity * visibility;",
  22797. "gl_FragColor = texture;",
  22798. "gl_FragColor.rgb *= color;",
  22799. "}",
  22800. "}"
  22801. ].join( "\n" )
  22802. }
  22803. };