three.js 856 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '54dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. // Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
  16. // not sure we should have this, or at least not have it here
  17. // http://stackoverflow.com/questions/646628/javascript-startswith
  18. // http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
  19. // http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
  20. String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
  21. return this.slice( 0, str.length ) === str;
  22. };
  23. String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
  24. var t = String( str );
  25. var index = this.lastIndexOf( t );
  26. return ( -1 < index && index ) === (this.length - t.length);
  27. };
  28. String.prototype.trim = String.prototype.trim || function () {
  29. return this.replace( /^\s+|\s+$/g, '' );
  30. };
  31. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  32. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  33. // requestAnimationFrame polyfill by Erik Möller
  34. // fixes from Paul Irish and Tino Zijdel
  35. ( function () {
  36. var lastTime = 0;
  37. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  38. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  39. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  40. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  41. }
  42. if ( window.requestAnimationFrame === undefined ) {
  43. window.requestAnimationFrame = function ( callback, element ) {
  44. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  45. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  46. lastTime = currTime + timeToCall;
  47. return id;
  48. };
  49. }
  50. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  51. }() );
  52. // GL STATE CONSTANTS
  53. THREE.CullFaceNone = 0;
  54. THREE.CullFaceBack = 1;
  55. THREE.CullFaceFront = 2;
  56. THREE.CullFaceFrontBack = 3;
  57. THREE.FrontFaceDirectionCW = 0;
  58. THREE.FrontFaceDirectionCCW = 1;
  59. // SHADOWING TYPES
  60. THREE.BasicShadowMap = 0;
  61. THREE.PCFShadowMap = 1;
  62. THREE.PCFSoftShadowMap = 2;
  63. // MATERIAL CONSTANTS
  64. // side
  65. THREE.FrontSide = 0;
  66. THREE.BackSide = 1;
  67. THREE.DoubleSide = 2;
  68. // shading
  69. THREE.NoShading = 0;
  70. THREE.FlatShading = 1;
  71. THREE.SmoothShading = 2;
  72. // colors
  73. THREE.NoColors = 0;
  74. THREE.FaceColors = 1;
  75. THREE.VertexColors = 2;
  76. // blending modes
  77. THREE.NoBlending = 0;
  78. THREE.NormalBlending = 1;
  79. THREE.AdditiveBlending = 2;
  80. THREE.SubtractiveBlending = 3;
  81. THREE.MultiplyBlending = 4;
  82. THREE.CustomBlending = 5;
  83. // custom blending equations
  84. // (numbers start from 100 not to clash with other
  85. // mappings to OpenGL constants defined in Texture.js)
  86. THREE.AddEquation = 100;
  87. THREE.SubtractEquation = 101;
  88. THREE.ReverseSubtractEquation = 102;
  89. // custom blending destination factors
  90. THREE.ZeroFactor = 200;
  91. THREE.OneFactor = 201;
  92. THREE.SrcColorFactor = 202;
  93. THREE.OneMinusSrcColorFactor = 203;
  94. THREE.SrcAlphaFactor = 204;
  95. THREE.OneMinusSrcAlphaFactor = 205;
  96. THREE.DstAlphaFactor = 206;
  97. THREE.OneMinusDstAlphaFactor = 207;
  98. // custom blending source factors
  99. //THREE.ZeroFactor = 200;
  100. //THREE.OneFactor = 201;
  101. //THREE.SrcAlphaFactor = 204;
  102. //THREE.OneMinusSrcAlphaFactor = 205;
  103. //THREE.DstAlphaFactor = 206;
  104. //THREE.OneMinusDstAlphaFactor = 207;
  105. THREE.DstColorFactor = 208;
  106. THREE.OneMinusDstColorFactor = 209;
  107. THREE.SrcAlphaSaturateFactor = 210;
  108. // TEXTURE CONSTANTS
  109. THREE.MultiplyOperation = 0;
  110. THREE.MixOperation = 1;
  111. THREE.AddOperation = 2;
  112. // Mapping modes
  113. THREE.UVMapping = function () {};
  114. THREE.CubeReflectionMapping = function () {};
  115. THREE.CubeRefractionMapping = function () {};
  116. THREE.SphericalReflectionMapping = function () {};
  117. THREE.SphericalRefractionMapping = function () {};
  118. // Wrapping modes
  119. THREE.RepeatWrapping = 1000;
  120. THREE.ClampToEdgeWrapping = 1001;
  121. THREE.MirroredRepeatWrapping = 1002;
  122. // Filters
  123. THREE.NearestFilter = 1003;
  124. THREE.NearestMipMapNearestFilter = 1004;
  125. THREE.NearestMipMapLinearFilter = 1005;
  126. THREE.LinearFilter = 1006;
  127. THREE.LinearMipMapNearestFilter = 1007;
  128. THREE.LinearMipMapLinearFilter = 1008;
  129. // Data types
  130. THREE.UnsignedByteType = 1009;
  131. THREE.ByteType = 1010;
  132. THREE.ShortType = 1011;
  133. THREE.UnsignedShortType = 1012;
  134. THREE.IntType = 1013;
  135. THREE.UnsignedIntType = 1014;
  136. THREE.FloatType = 1015;
  137. // Pixel types
  138. //THREE.UnsignedByteType = 1009;
  139. THREE.UnsignedShort4444Type = 1016;
  140. THREE.UnsignedShort5551Type = 1017;
  141. THREE.UnsignedShort565Type = 1018;
  142. // Pixel formats
  143. THREE.AlphaFormat = 1019;
  144. THREE.RGBFormat = 1020;
  145. THREE.RGBAFormat = 1021;
  146. THREE.LuminanceFormat = 1022;
  147. THREE.LuminanceAlphaFormat = 1023;
  148. // Compressed texture formats
  149. THREE.RGB_S3TC_DXT1_Format = 2001;
  150. THREE.RGBA_S3TC_DXT1_Format = 2002;
  151. THREE.RGBA_S3TC_DXT3_Format = 2003;
  152. THREE.RGBA_S3TC_DXT5_Format = 2004;
  153. /*
  154. // Potential future PVRTC compressed texture formats
  155. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  156. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  157. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  158. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  159. */
  160. /**
  161. * @author mrdoob / http://mrdoob.com/
  162. */
  163. THREE.Color = function ( value ) {
  164. if ( value !== undefined ) this.set( value );
  165. return this;
  166. };
  167. THREE.Color.prototype = {
  168. constructor: THREE.Color,
  169. r: 1, g: 1, b: 1,
  170. copy: function ( color ) {
  171. this.r = color.r;
  172. this.g = color.g;
  173. this.b = color.b;
  174. return this;
  175. },
  176. copyGammaToLinear: function ( color ) {
  177. this.r = color.r * color.r;
  178. this.g = color.g * color.g;
  179. this.b = color.b * color.b;
  180. return this;
  181. },
  182. copyLinearToGamma: function ( color ) {
  183. this.r = Math.sqrt( color.r );
  184. this.g = Math.sqrt( color.g );
  185. this.b = Math.sqrt( color.b );
  186. return this;
  187. },
  188. convertGammaToLinear: function () {
  189. var r = this.r, g = this.g, b = this.b;
  190. this.r = r * r;
  191. this.g = g * g;
  192. this.b = b * b;
  193. return this;
  194. },
  195. convertLinearToGamma: function () {
  196. this.r = Math.sqrt( this.r );
  197. this.g = Math.sqrt( this.g );
  198. this.b = Math.sqrt( this.b );
  199. return this;
  200. },
  201. set: function ( value ) {
  202. switch ( typeof value ) {
  203. case "number":
  204. this.setHex( value );
  205. break;
  206. case "string":
  207. this.setStyle( value );
  208. break;
  209. }
  210. },
  211. setRGB: function ( r, g, b ) {
  212. this.r = r;
  213. this.g = g;
  214. this.b = b;
  215. return this;
  216. },
  217. setHSV: function ( h, s, v ) {
  218. // based on MochiKit implementation by Bob Ippolito
  219. // h,s,v ranges are < 0.0 - 1.0 >
  220. var i, f, p, q, t;
  221. if ( v === 0 ) {
  222. this.r = this.g = this.b = 0;
  223. } else {
  224. i = Math.floor( h * 6 );
  225. f = ( h * 6 ) - i;
  226. p = v * ( 1 - s );
  227. q = v * ( 1 - ( s * f ) );
  228. t = v * ( 1 - ( s * ( 1 - f ) ) );
  229. if ( i === 0 ) {
  230. this.r = v;
  231. this.g = t;
  232. this.b = p;
  233. } else if ( i === 1 ) {
  234. this.r = q;
  235. this.g = v;
  236. this.b = p;
  237. } else if ( i === 2 ) {
  238. this.r = p;
  239. this.g = v;
  240. this.b = t;
  241. } else if ( i === 3 ) {
  242. this.r = p;
  243. this.g = q;
  244. this.b = v;
  245. } else if ( i === 4 ) {
  246. this.r = t;
  247. this.g = p;
  248. this.b = v;
  249. } else if ( i === 5 ) {
  250. this.r = v;
  251. this.g = p;
  252. this.b = q;
  253. }
  254. }
  255. return this;
  256. },
  257. getHex: function () {
  258. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  259. },
  260. setHex: function ( hex ) {
  261. hex = Math.floor( hex );
  262. this.r = ( hex >> 16 & 255 ) / 255;
  263. this.g = ( hex >> 8 & 255 ) / 255;
  264. this.b = ( hex & 255 ) / 255;
  265. return this;
  266. },
  267. getHexString: function () {
  268. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  269. },
  270. getStyle: function () {
  271. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  272. },
  273. setStyle: function ( style ) {
  274. // rgb(255,0,0)
  275. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  276. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  277. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  278. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  279. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  280. return this;
  281. }
  282. // rgb(100%,0%,0%)
  283. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  284. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  285. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  286. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  287. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  288. return this;
  289. }
  290. // #ff0000
  291. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  292. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  293. this.setHex( parseInt( color[ 1 ], 16 ) );
  294. return this;
  295. }
  296. // #f00
  297. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  298. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  299. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  300. return this;
  301. }
  302. // red
  303. if ( /^(\w+)$/i.test( style ) ) {
  304. this.setHex( THREE.ColorKeywords[ style ] );
  305. return this;
  306. }
  307. },
  308. getHSV: function ( hsv ) {
  309. // based on MochiKit implementation by Bob Ippolito
  310. // h,s,v ranges are < 0.0 - 1.0 >
  311. var r = this.r;
  312. var g = this.g;
  313. var b = this.b;
  314. var max = Math.max( Math.max( r, g ), b );
  315. var min = Math.min( Math.min( r, g ), b );
  316. var hue;
  317. var saturation;
  318. var value = max;
  319. if ( min === max ) {
  320. hue = 0;
  321. saturation = 0;
  322. } else {
  323. var delta = ( max - min );
  324. saturation = delta / max;
  325. if ( r === max ) {
  326. hue = ( g - b ) / delta;
  327. } else if ( g === max ) {
  328. hue = 2 + ( ( b - r ) / delta );
  329. } else {
  330. hue = 4 + ( ( r - g ) / delta );
  331. }
  332. hue /= 6;
  333. if ( hue < 0 ) {
  334. hue += 1;
  335. }
  336. if ( hue > 1 ) {
  337. hue -= 1;
  338. }
  339. }
  340. if ( hsv === undefined ) {
  341. hsv = { h: 0, s: 0, v: 0 };
  342. }
  343. hsv.h = hue;
  344. hsv.s = saturation;
  345. hsv.v = value;
  346. return hsv;
  347. },
  348. lerpSelf: function ( color, alpha ) {
  349. this.r += ( color.r - this.r ) * alpha;
  350. this.g += ( color.g - this.g ) * alpha;
  351. this.b += ( color.b - this.b ) * alpha;
  352. return this;
  353. },
  354. clone: function () {
  355. return new THREE.Color().setRGB( this.r, this.g, this.b );
  356. }
  357. };
  358. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  359. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  360. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  361. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  362. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  363. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  364. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  365. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  366. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  367. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  368. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  369. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  370. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  371. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  372. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  373. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  374. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  375. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  376. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  377. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  378. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  379. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  380. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  381. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  382. /**
  383. * @author mrdoob / http://mrdoob.com/
  384. * @author philogb / http://blog.thejit.org/
  385. * @author egraether / http://egraether.com/
  386. * @author zz85 / http://www.lab4games.net/zz85/blog
  387. */
  388. THREE.Vector2 = function ( x, y ) {
  389. this.x = x || 0;
  390. this.y = y || 0;
  391. };
  392. THREE.Vector2.prototype = {
  393. constructor: THREE.Vector2,
  394. set: function ( x, y ) {
  395. this.x = x;
  396. this.y = y;
  397. return this;
  398. },
  399. setX: function ( x ) {
  400. this.x = x;
  401. return this;
  402. },
  403. setY: function ( y ) {
  404. this.y = y;
  405. return this;
  406. },
  407. copy: function ( v ) {
  408. this.x = v.x;
  409. this.y = v.y;
  410. return this;
  411. },
  412. addScalar: function ( s ) {
  413. this.x += s;
  414. this.y += s;
  415. return this;
  416. },
  417. add: function ( a, b ) {
  418. this.x = a.x + b.x;
  419. this.y = a.y + b.y;
  420. return this;
  421. },
  422. addSelf: function ( v ) {
  423. this.x += v.x;
  424. this.y += v.y;
  425. return this;
  426. },
  427. sub: function ( a, b ) {
  428. this.x = a.x - b.x;
  429. this.y = a.y - b.y;
  430. return this;
  431. },
  432. subSelf: function ( v ) {
  433. this.x -= v.x;
  434. this.y -= v.y;
  435. return this;
  436. },
  437. multiplyScalar: function ( s ) {
  438. this.x *= s;
  439. this.y *= s;
  440. return this;
  441. },
  442. divideScalar: function ( s ) {
  443. if ( s ) {
  444. this.x /= s;
  445. this.y /= s;
  446. } else {
  447. this.set( 0, 0 );
  448. }
  449. return this;
  450. },
  451. minSelf: function ( v ) {
  452. if ( this.x > v.x ) {
  453. this.x = v.x;
  454. }
  455. if ( this.y > v.y ) {
  456. this.y = v.y;
  457. }
  458. return this;
  459. },
  460. maxSelf: function ( v ) {
  461. if ( this.x < v.x ) {
  462. this.x = v.x;
  463. }
  464. if ( this.y < v.y ) {
  465. this.y = v.y;
  466. }
  467. return this;
  468. },
  469. clampSelf: function ( min, max ) {
  470. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  471. if ( this.x < min.x ) {
  472. this.x = min.x;
  473. } else if ( this.x > max.x ) {
  474. this.x = max.x;
  475. }
  476. if ( this.y < min.y ) {
  477. this.y = min.y;
  478. } else if ( this.y > max.y ) {
  479. this.y = max.y;
  480. }
  481. return this;
  482. },
  483. negate: function() {
  484. return this.multiplyScalar( - 1 );
  485. },
  486. dot: function ( v ) {
  487. return this.x * v.x + this.y * v.y;
  488. },
  489. lengthSq: function () {
  490. return this.x * this.x + this.y * this.y;
  491. },
  492. length: function () {
  493. return Math.sqrt( this.lengthSq() );
  494. },
  495. normalize: function () {
  496. return this.divideScalar( this.length() );
  497. },
  498. distanceTo: function ( v ) {
  499. return Math.sqrt( this.distanceToSquared( v ) );
  500. },
  501. distanceToSquared: function ( v ) {
  502. var dx = this.x - v.x, dy = this.y - v.y;
  503. return dx * dx + dy * dy;
  504. },
  505. setLength: function ( l ) {
  506. return this.normalize().multiplyScalar( l );
  507. },
  508. lerpSelf: function ( v, alpha ) {
  509. this.x += ( v.x - this.x ) * alpha;
  510. this.y += ( v.y - this.y ) * alpha;
  511. return this;
  512. },
  513. equals: function( v ) {
  514. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  515. },
  516. clone: function () {
  517. return new THREE.Vector2( this.x, this.y );
  518. }
  519. };
  520. /**
  521. * @author mrdoob / http://mrdoob.com/
  522. * @author *kile / http://kile.stravaganza.org/
  523. * @author philogb / http://blog.thejit.org/
  524. * @author mikael emtinger / http://gomo.se/
  525. * @author egraether / http://egraether.com/
  526. * @author WestLangley / http://github.com/WestLangley
  527. */
  528. THREE.Vector3 = function ( x, y, z ) {
  529. this.x = x || 0;
  530. this.y = y || 0;
  531. this.z = z || 0;
  532. };
  533. THREE.Vector3.prototype = {
  534. constructor: THREE.Vector3,
  535. set: function ( x, y, z ) {
  536. this.x = x;
  537. this.y = y;
  538. this.z = z;
  539. return this;
  540. },
  541. setX: function ( x ) {
  542. this.x = x;
  543. return this;
  544. },
  545. setY: function ( y ) {
  546. this.y = y;
  547. return this;
  548. },
  549. setZ: function ( z ) {
  550. this.z = z;
  551. return this;
  552. },
  553. copy: function ( v ) {
  554. this.x = v.x;
  555. this.y = v.y;
  556. this.z = v.z;
  557. return this;
  558. },
  559. add: function ( a, b ) {
  560. this.x = a.x + b.x;
  561. this.y = a.y + b.y;
  562. this.z = a.z + b.z;
  563. return this;
  564. },
  565. addSelf: function ( v ) {
  566. this.x += v.x;
  567. this.y += v.y;
  568. this.z += v.z;
  569. return this;
  570. },
  571. addScalar: function ( s ) {
  572. this.x += s;
  573. this.y += s;
  574. this.z += s;
  575. return this;
  576. },
  577. sub: function ( a, b ) {
  578. this.x = a.x - b.x;
  579. this.y = a.y - b.y;
  580. this.z = a.z - b.z;
  581. return this;
  582. },
  583. subSelf: function ( v ) {
  584. this.x -= v.x;
  585. this.y -= v.y;
  586. this.z -= v.z;
  587. return this;
  588. },
  589. multiply: function ( a, b ) {
  590. this.x = a.x * b.x;
  591. this.y = a.y * b.y;
  592. this.z = a.z * b.z;
  593. return this;
  594. },
  595. multiplySelf: function ( v ) {
  596. this.x *= v.x;
  597. this.y *= v.y;
  598. this.z *= v.z;
  599. return this;
  600. },
  601. multiplyScalar: function ( s ) {
  602. this.x *= s;
  603. this.y *= s;
  604. this.z *= s;
  605. return this;
  606. },
  607. divideSelf: function ( v ) {
  608. this.x /= v.x;
  609. this.y /= v.y;
  610. this.z /= v.z;
  611. return this;
  612. },
  613. divideScalar: function ( s ) {
  614. if ( s ) {
  615. this.x /= s;
  616. this.y /= s;
  617. this.z /= s;
  618. } else {
  619. this.x = 0;
  620. this.y = 0;
  621. this.z = 0;
  622. }
  623. return this;
  624. },
  625. minSelf: function ( v ) {
  626. if ( this.x > v.x ) {
  627. this.x = v.x;
  628. }
  629. if ( this.y > v.y ) {
  630. this.y = v.y;
  631. }
  632. if ( this.z > v.z ) {
  633. this.z = v.z;
  634. }
  635. return this;
  636. },
  637. maxSelf: function ( v ) {
  638. if ( this.x < v.x ) {
  639. this.x = v.x;
  640. }
  641. if ( this.y < v.y ) {
  642. this.y = v.y;
  643. }
  644. if ( this.z < v.z ) {
  645. this.z = v.z;
  646. }
  647. return this;
  648. },
  649. clampSelf: function ( min, max ) {
  650. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  651. if ( this.x < min.x ) {
  652. this.x = min.x;
  653. } else if ( this.x > max.x ) {
  654. this.x = max.x;
  655. }
  656. if ( this.y < min.y ) {
  657. this.y = min.y;
  658. } else if ( this.y > max.y ) {
  659. this.y = max.y;
  660. }
  661. if ( this.z < min.z ) {
  662. this.z = min.z;
  663. } else if ( this.z > max.z ) {
  664. this.z = max.z;
  665. }
  666. return this;
  667. },
  668. negate: function() {
  669. return this.multiplyScalar( - 1 );
  670. },
  671. dot: function ( v ) {
  672. return this.x * v.x + this.y * v.y + this.z * v.z;
  673. },
  674. lengthSq: function () {
  675. return this.x * this.x + this.y * this.y + this.z * this.z;
  676. },
  677. length: function () {
  678. return Math.sqrt( this.lengthSq() );
  679. },
  680. lengthManhattan: function () {
  681. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  682. },
  683. normalize: function () {
  684. return this.divideScalar( this.length() );
  685. },
  686. setLength: function ( l ) {
  687. return this.normalize().multiplyScalar( l );
  688. },
  689. lerpSelf: function ( v, alpha ) {
  690. this.x += ( v.x - this.x ) * alpha;
  691. this.y += ( v.y - this.y ) * alpha;
  692. this.z += ( v.z - this.z ) * alpha;
  693. return this;
  694. },
  695. cross: function ( a, b ) {
  696. this.x = a.y * b.z - a.z * b.y;
  697. this.y = a.z * b.x - a.x * b.z;
  698. this.z = a.x * b.y - a.y * b.x;
  699. return this;
  700. },
  701. crossSelf: function ( v ) {
  702. var x = this.x, y = this.y, z = this.z;
  703. this.x = y * v.z - z * v.y;
  704. this.y = z * v.x - x * v.z;
  705. this.z = x * v.y - y * v.x;
  706. return this;
  707. },
  708. angleTo: function ( v ) {
  709. return Math.acos( this.dot( v ) / this.length() / v.length() );
  710. },
  711. distanceTo: function ( v ) {
  712. return Math.sqrt( this.distanceToSquared( v ) );
  713. },
  714. distanceToSquared: function ( v ) {
  715. var dx = this.x - v.x;
  716. var dy = this.y - v.y;
  717. var dz = this.z - v.z;
  718. return dx * dx + dy * dy + dz * dz;
  719. },
  720. getPositionFromMatrix: function ( m ) {
  721. this.x = m.elements[12];
  722. this.y = m.elements[13];
  723. this.z = m.elements[14];
  724. return this;
  725. },
  726. setEulerFromRotationMatrix: function ( m, order ) {
  727. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  728. // clamp, to handle numerical problems
  729. function clamp( x ) {
  730. return Math.min( Math.max( x, -1 ), 1 );
  731. }
  732. var te = m.elements;
  733. var m11 = te[0], m12 = te[4], m13 = te[8];
  734. var m21 = te[1], m22 = te[5], m23 = te[9];
  735. var m31 = te[2], m32 = te[6], m33 = te[10];
  736. if ( order === undefined || order === 'XYZ' ) {
  737. this.y = Math.asin( clamp( m13 ) );
  738. if ( Math.abs( m13 ) < 0.99999 ) {
  739. this.x = Math.atan2( - m23, m33 );
  740. this.z = Math.atan2( - m12, m11 );
  741. } else {
  742. this.x = Math.atan2( m32, m22 );
  743. this.z = 0;
  744. }
  745. } else if ( order === 'YXZ' ) {
  746. this.x = Math.asin( - clamp( m23 ) );
  747. if ( Math.abs( m23 ) < 0.99999 ) {
  748. this.y = Math.atan2( m13, m33 );
  749. this.z = Math.atan2( m21, m22 );
  750. } else {
  751. this.y = Math.atan2( - m31, m11 );
  752. this.z = 0;
  753. }
  754. } else if ( order === 'ZXY' ) {
  755. this.x = Math.asin( clamp( m32 ) );
  756. if ( Math.abs( m32 ) < 0.99999 ) {
  757. this.y = Math.atan2( - m31, m33 );
  758. this.z = Math.atan2( - m12, m22 );
  759. } else {
  760. this.y = 0;
  761. this.z = Math.atan2( m21, m11 );
  762. }
  763. } else if ( order === 'ZYX' ) {
  764. this.y = Math.asin( - clamp( m31 ) );
  765. if ( Math.abs( m31 ) < 0.99999 ) {
  766. this.x = Math.atan2( m32, m33 );
  767. this.z = Math.atan2( m21, m11 );
  768. } else {
  769. this.x = 0;
  770. this.z = Math.atan2( - m12, m22 );
  771. }
  772. } else if ( order === 'YZX' ) {
  773. this.z = Math.asin( clamp( m21 ) );
  774. if ( Math.abs( m21 ) < 0.99999 ) {
  775. this.x = Math.atan2( - m23, m22 );
  776. this.y = Math.atan2( - m31, m11 );
  777. } else {
  778. this.x = 0;
  779. this.y = Math.atan2( m13, m33 );
  780. }
  781. } else if ( order === 'XZY' ) {
  782. this.z = Math.asin( - clamp( m12 ) );
  783. if ( Math.abs( m12 ) < 0.99999 ) {
  784. this.x = Math.atan2( m32, m22 );
  785. this.y = Math.atan2( m13, m11 );
  786. } else {
  787. this.x = Math.atan2( - m23, m33 );
  788. this.y = 0;
  789. }
  790. }
  791. return this;
  792. },
  793. setEulerFromQuaternion: function ( q, order ) {
  794. // q is assumed to be normalized
  795. // clamp, to handle numerical problems
  796. function clamp( x ) {
  797. return Math.min( Math.max( x, -1 ), 1 );
  798. }
  799. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  800. var sqx = q.x * q.x;
  801. var sqy = q.y * q.y;
  802. var sqz = q.z * q.z;
  803. var sqw = q.w * q.w;
  804. if ( order === undefined || order === 'XYZ' ) {
  805. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  806. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  807. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  808. } else if ( order === 'YXZ' ) {
  809. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  810. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  811. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  812. } else if ( order === 'ZXY' ) {
  813. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  814. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  815. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  816. } else if ( order === 'ZYX' ) {
  817. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  818. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  819. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  820. } else if ( order === 'YZX' ) {
  821. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  822. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  823. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  824. } else if ( order === 'XZY' ) {
  825. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  826. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  827. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  828. }
  829. return this;
  830. },
  831. getScaleFromMatrix: function ( m ) {
  832. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  833. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  834. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  835. this.x = sx;
  836. this.y = sy;
  837. this.z = sz;
  838. return this;
  839. },
  840. equals: function ( v ) {
  841. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  842. },
  843. clone: function () {
  844. return new THREE.Vector3( this.x, this.y, this.z );
  845. }
  846. };
  847. /**
  848. * @author supereggbert / http://www.paulbrunt.co.uk/
  849. * @author philogb / http://blog.thejit.org/
  850. * @author mikael emtinger / http://gomo.se/
  851. * @author egraether / http://egraether.com/
  852. * @author WestLangley / http://github.com/WestLangley
  853. */
  854. THREE.Vector4 = function ( x, y, z, w ) {
  855. this.x = x || 0;
  856. this.y = y || 0;
  857. this.z = z || 0;
  858. this.w = ( w !== undefined ) ? w : 1;
  859. };
  860. THREE.Vector4.prototype = {
  861. constructor: THREE.Vector4,
  862. set: function ( x, y, z, w ) {
  863. this.x = x;
  864. this.y = y;
  865. this.z = z;
  866. this.w = w;
  867. return this;
  868. },
  869. setX: function ( x ) {
  870. this.x = x;
  871. return this;
  872. },
  873. setY: function ( y ) {
  874. this.y = y;
  875. return this;
  876. },
  877. setZ: function ( z ) {
  878. this.z = z;
  879. return this;
  880. },
  881. setW: function ( w ) {
  882. this.w = w;
  883. return this;
  884. },
  885. copy: function ( v ) {
  886. this.x = v.x;
  887. this.y = v.y;
  888. this.z = v.z;
  889. this.w = ( v.w !== undefined ) ? v.w : 1;
  890. return this;
  891. },
  892. addScalar: function ( s ) {
  893. this.x += s;
  894. this.y += s;
  895. this.z += s;
  896. this.w += s;
  897. return this;
  898. },
  899. add: function ( a, b ) {
  900. this.x = a.x + b.x;
  901. this.y = a.y + b.y;
  902. this.z = a.z + b.z;
  903. this.w = a.w + b.w;
  904. return this;
  905. },
  906. addSelf: function ( v ) {
  907. this.x += v.x;
  908. this.y += v.y;
  909. this.z += v.z;
  910. this.w += v.w;
  911. return this;
  912. },
  913. sub: function ( a, b ) {
  914. this.x = a.x - b.x;
  915. this.y = a.y - b.y;
  916. this.z = a.z - b.z;
  917. this.w = a.w - b.w;
  918. return this;
  919. },
  920. subSelf: function ( v ) {
  921. this.x -= v.x;
  922. this.y -= v.y;
  923. this.z -= v.z;
  924. this.w -= v.w;
  925. return this;
  926. },
  927. multiplyScalar: function ( s ) {
  928. this.x *= s;
  929. this.y *= s;
  930. this.z *= s;
  931. this.w *= s;
  932. return this;
  933. },
  934. divideScalar: function ( s ) {
  935. if ( s ) {
  936. this.x /= s;
  937. this.y /= s;
  938. this.z /= s;
  939. this.w /= s;
  940. } else {
  941. this.x = 0;
  942. this.y = 0;
  943. this.z = 0;
  944. this.w = 1;
  945. }
  946. return this;
  947. },
  948. minSelf: function ( v ) {
  949. if ( this.x > v.x ) {
  950. this.x = v.x;
  951. }
  952. if ( this.y > v.y ) {
  953. this.y = v.y;
  954. }
  955. if ( this.z > v.z ) {
  956. this.z = v.z;
  957. }
  958. if ( this.w > v.w ) {
  959. this.w = v.w;
  960. }
  961. return this;
  962. },
  963. maxSelf: function ( v ) {
  964. if ( this.x < v.x ) {
  965. this.x = v.x;
  966. }
  967. if ( this.y < v.y ) {
  968. this.y = v.y;
  969. }
  970. if ( this.z < v.z ) {
  971. this.z = v.z;
  972. }
  973. if ( this.w < v.w ) {
  974. this.w = v.w;
  975. }
  976. return this;
  977. },
  978. clampSelf: function ( min, max ) {
  979. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  980. if ( this.x < min.x ) {
  981. this.x = min.x;
  982. } else if ( this.x > max.x ) {
  983. this.x = max.x;
  984. }
  985. if ( this.y < min.y ) {
  986. this.y = min.y;
  987. } else if ( this.y > max.y ) {
  988. this.y = max.y;
  989. }
  990. if ( this.z < min.z ) {
  991. this.z = min.z;
  992. } else if ( this.z > max.z ) {
  993. this.z = max.z;
  994. }
  995. if ( this.w < min.w ) {
  996. this.w = min.w;
  997. } else if ( this.w > max.w ) {
  998. this.w = max.w;
  999. }
  1000. return this;
  1001. },
  1002. negate: function() {
  1003. return this.multiplyScalar( -1 );
  1004. },
  1005. dot: function ( v ) {
  1006. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1007. },
  1008. lengthSq: function () {
  1009. return this.dot( this );
  1010. },
  1011. length: function () {
  1012. return Math.sqrt( this.lengthSq() );
  1013. },
  1014. lengthManhattan: function () {
  1015. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1016. },
  1017. normalize: function () {
  1018. return this.divideScalar( this.length() );
  1019. },
  1020. setLength: function ( l ) {
  1021. return this.normalize().multiplyScalar( l );
  1022. },
  1023. lerpSelf: function ( v, alpha ) {
  1024. this.x += ( v.x - this.x ) * alpha;
  1025. this.y += ( v.y - this.y ) * alpha;
  1026. this.z += ( v.z - this.z ) * alpha;
  1027. this.w += ( v.w - this.w ) * alpha;
  1028. return this;
  1029. },
  1030. equals: function ( v ) {
  1031. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1032. },
  1033. clone: function () {
  1034. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1035. },
  1036. setAxisAngleFromQuaternion: function ( q ) {
  1037. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1038. // q is assumed to be normalized
  1039. this.w = 2 * Math.acos( q.w );
  1040. var s = Math.sqrt( 1 - q.w * q.w );
  1041. if ( s < 0.0001 ) {
  1042. this.x = 1;
  1043. this.y = 0;
  1044. this.z = 0;
  1045. } else {
  1046. this.x = q.x / s;
  1047. this.y = q.y / s;
  1048. this.z = q.z / s;
  1049. }
  1050. return this;
  1051. },
  1052. setAxisAngleFromRotationMatrix: function ( m ) {
  1053. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1054. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1055. var angle, x, y, z, // variables for result
  1056. epsilon = 0.01, // margin to allow for rounding errors
  1057. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1058. te = m.elements,
  1059. m11 = te[0], m12 = te[4], m13 = te[8],
  1060. m21 = te[1], m22 = te[5], m23 = te[9],
  1061. m31 = te[2], m32 = te[6], m33 = te[10];
  1062. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1063. && ( Math.abs( m13 - m31 ) < epsilon )
  1064. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1065. // singularity found
  1066. // first check for identity matrix which must have +1 for all terms
  1067. // in leading diagonal and zero in other terms
  1068. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1069. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1070. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1071. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1072. // this singularity is identity matrix so angle = 0
  1073. this.set( 1, 0, 0, 0 );
  1074. return this; // zero angle, arbitrary axis
  1075. }
  1076. // otherwise this singularity is angle = 180
  1077. angle = Math.PI;
  1078. var xx = ( m11 + 1 ) / 2;
  1079. var yy = ( m22 + 1 ) / 2;
  1080. var zz = ( m33 + 1 ) / 2;
  1081. var xy = ( m12 + m21 ) / 4;
  1082. var xz = ( m13 + m31 ) / 4;
  1083. var yz = ( m23 + m32 ) / 4;
  1084. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1085. if ( xx < epsilon ) {
  1086. x = 0;
  1087. y = 0.707106781;
  1088. z = 0.707106781;
  1089. } else {
  1090. x = Math.sqrt( xx );
  1091. y = xy / x;
  1092. z = xz / x;
  1093. }
  1094. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1095. if ( yy < epsilon ) {
  1096. x = 0.707106781;
  1097. y = 0;
  1098. z = 0.707106781;
  1099. } else {
  1100. y = Math.sqrt( yy );
  1101. x = xy / y;
  1102. z = yz / y;
  1103. }
  1104. } else { // m33 is the largest diagonal term so base result on this
  1105. if ( zz < epsilon ) {
  1106. x = 0.707106781;
  1107. y = 0.707106781;
  1108. z = 0;
  1109. } else {
  1110. z = Math.sqrt( zz );
  1111. x = xz / z;
  1112. y = yz / z;
  1113. }
  1114. }
  1115. this.set( x, y, z, angle );
  1116. return this; // return 180 deg rotation
  1117. }
  1118. // as we have reached here there are no singularities so we can handle normally
  1119. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1120. + ( m13 - m31 ) * ( m13 - m31 )
  1121. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1122. if ( Math.abs( s ) < 0.001 ) s = 1;
  1123. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1124. // caught by singularity test above, but I've left it in just in case
  1125. this.x = ( m32 - m23 ) / s;
  1126. this.y = ( m13 - m31 ) / s;
  1127. this.z = ( m21 - m12 ) / s;
  1128. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1129. return this;
  1130. }
  1131. };
  1132. /**
  1133. * @author bhouston / http://exocortex.com
  1134. */
  1135. THREE.Box2 = function ( min, max ) {
  1136. this.min = min !== undefined ? min.clone() : new THREE.Vector2( Infinity, Infinity );
  1137. this.max = max !== undefined ? max.clone() : new THREE.Vector2( -Infinity, -Infinity );
  1138. };
  1139. THREE.Box2.prototype = {
  1140. constructor: THREE.Box2,
  1141. set: function ( min, max ) {
  1142. this.min.copy( min );
  1143. this.max.copy( max );
  1144. return this;
  1145. },
  1146. setFromPoints: function ( points ) {
  1147. if ( points.length > 0 ) {
  1148. var point = points[ 0 ];
  1149. this.min.copy( point );
  1150. this.max.copy( point );
  1151. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1152. point = points[ i ];
  1153. if ( point.x < this.min.x ) {
  1154. this.min.x = point.x;
  1155. } else if ( point.x > this.max.x ) {
  1156. this.max.x = point.x;
  1157. }
  1158. if ( point.y < this.min.y ) {
  1159. this.min.y = point.y;
  1160. } else if ( point.y > this.max.y ) {
  1161. this.max.y = point.y;
  1162. }
  1163. }
  1164. } else {
  1165. this.makeEmpty();
  1166. }
  1167. return this;
  1168. },
  1169. setFromCenterAndSize: function ( center, size ) {
  1170. var halfSize = THREE.Box2.__v1.copy( size ).multiplyScalar( 0.5 );
  1171. this.min.copy( center ).subSelf( halfSize );
  1172. this.max.copy( center ).addSelf( halfSize );
  1173. return this;
  1174. },
  1175. copy: function ( box ) {
  1176. this.min.copy( box.min );
  1177. this.max.copy( box.max );
  1178. return this;
  1179. },
  1180. makeEmpty: function () {
  1181. this.min.x = this.min.y = Infinity;
  1182. this.max.x = this.max.y = -Infinity;
  1183. return this;
  1184. },
  1185. empty: function () {
  1186. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1187. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1188. },
  1189. center: function ( optionalTarget ) {
  1190. var result = optionalTarget || new THREE.Vector2();
  1191. return result.add( this.min, this.max ).multiplyScalar( 0.5 );
  1192. },
  1193. size: function ( optionalTarget ) {
  1194. var result = optionalTarget || new THREE.Vector2();
  1195. return result.sub( this.max, this.min );
  1196. },
  1197. expandByPoint: function ( point ) {
  1198. this.min.minSelf( point );
  1199. this.max.maxSelf( point );
  1200. return this;
  1201. },
  1202. expandByVector: function ( vector ) {
  1203. this.min.subSelf( vector );
  1204. this.max.addSelf( vector );
  1205. return this;
  1206. },
  1207. expandByScalar: function ( scalar ) {
  1208. this.min.addScalar( -scalar );
  1209. this.max.addScalar( scalar );
  1210. return this;
  1211. },
  1212. containsPoint: function ( point ) {
  1213. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1214. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) ) {
  1215. return true;
  1216. }
  1217. return false;
  1218. },
  1219. containsBox: function ( box ) {
  1220. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1221. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1222. return true;
  1223. }
  1224. return false;
  1225. },
  1226. getParameter: function ( point ) {
  1227. // This can potentially have a divide by zero if the box
  1228. // has a size dimension of 0.
  1229. return new THREE.Vector2(
  1230. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1231. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1232. );
  1233. },
  1234. isIntersectionBox: function ( box ) {
  1235. // using 6 splitting planes to rule out intersections.
  1236. if ( ( box.max.x < this.min.x ) ||
  1237. ( box.min.x > this.max.x ) ||
  1238. ( box.max.y < this.min.y ) ||
  1239. ( box.min.y > this.max.y ) ) {
  1240. return false;
  1241. }
  1242. return true;
  1243. },
  1244. clampPoint: function ( point, optionalTarget ) {
  1245. var result = optionalTarget || new THREE.Vector2();
  1246. return result.copy( point ).clampSelf( this.min, this.max );
  1247. },
  1248. distanceToPoint: function ( point ) {
  1249. var clampedPoint = THREE.Box2.__v1.copy( point ).clampSelf( this.min, this.max );
  1250. return clampedPoint.subSelf( point ).length();
  1251. },
  1252. intersect: function ( box ) {
  1253. this.min.maxSelf( box.min );
  1254. this.max.minSelf( box.max );
  1255. return this;
  1256. },
  1257. union: function ( box ) {
  1258. this.min.minSelf( box.min );
  1259. this.max.maxSelf( box.max );
  1260. return this;
  1261. },
  1262. translate: function ( offset ) {
  1263. this.min.addSelf( offset );
  1264. this.max.addSelf( offset );
  1265. return this;
  1266. },
  1267. scale: function ( factor ) {
  1268. var sizeDeltaHalf = this.size().multiplyScalar( ( factor - 1 ) * 0.5 );
  1269. this.expandByVector( sizeDeltaHalf );
  1270. return this;
  1271. },
  1272. equals: function ( box ) {
  1273. return box.min.equals( this.min ) && box.max.equals( this.max );
  1274. },
  1275. clone: function () {
  1276. return new THREE.Box2().copy( this );
  1277. }
  1278. };
  1279. THREE.Box2.__v1 = new THREE.Vector2();
  1280. /**
  1281. * @author bhouston / http://exocortex.com
  1282. */
  1283. THREE.Box3 = function ( min, max ) {
  1284. this.min = min !== undefined ? min.clone() : new THREE.Vector3( Infinity, Infinity, Infinity );
  1285. this.max = max !== undefined ? max.clone() : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1286. };
  1287. THREE.Box3.prototype = {
  1288. constructor: THREE.Box3,
  1289. set: function ( min, max ) {
  1290. this.min.copy( min );
  1291. this.max.copy( max );
  1292. return this;
  1293. },
  1294. setFromPoints: function ( points ) {
  1295. if ( points.length > 0 ) {
  1296. var p = points[ 0 ];
  1297. this.min.copy( p );
  1298. this.max.copy( p );
  1299. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1300. p = points[ i ];
  1301. if ( p.x < this.min.x ) {
  1302. this.min.x = p.x;
  1303. } else if ( p.x > this.max.x ) {
  1304. this.max.x = p.x;
  1305. }
  1306. if ( p.y < this.min.y ) {
  1307. this.min.y = p.y;
  1308. } else if ( p.y > this.max.y ) {
  1309. this.max.y = p.y;
  1310. }
  1311. if ( p.z < this.min.z ) {
  1312. this.min.z = p.z;
  1313. } else if ( p.z > this.max.z ) {
  1314. this.max.z = p.z;
  1315. }
  1316. }
  1317. } else {
  1318. this.makeEmpty();
  1319. }
  1320. return this;
  1321. },
  1322. setFromCenterAndSize: function ( center, size ) {
  1323. var halfSize = THREE.Box3.__v1.copy( size ).multiplyScalar( 0.5 );
  1324. this.min.copy( center ).subSelf( halfSize );
  1325. this.max.copy( center ).addSelf( halfSize );
  1326. return this;
  1327. },
  1328. copy: function ( box ) {
  1329. this.min.copy( box.min );
  1330. this.max.copy( box.max );
  1331. return this;
  1332. },
  1333. makeEmpty: function () {
  1334. this.min.x = this.min.y = this.min.z = Infinity;
  1335. this.max.x = this.max.y = this.max.z = -Infinity;
  1336. return this;
  1337. },
  1338. empty: function () {
  1339. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1340. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1341. },
  1342. center: function ( optionalTarget ) {
  1343. var result = optionalTarget || new THREE.Vector3();
  1344. return result.add( this.min, this.max ).multiplyScalar( 0.5 );
  1345. },
  1346. size: function ( optionalTarget ) {
  1347. var result = optionalTarget || new THREE.Vector3();
  1348. return result.sub( this.max, this.min );
  1349. },
  1350. expandByPoint: function ( point ) {
  1351. this.min.minSelf( point );
  1352. this.max.maxSelf( point );
  1353. return this;
  1354. },
  1355. expandByVector: function ( vector ) {
  1356. this.min.subSelf( vector );
  1357. this.max.addSelf( vector );
  1358. return this;
  1359. },
  1360. expandByScalar: function ( scalar ) {
  1361. this.min.addScalar( -scalar );
  1362. this.max.addScalar( scalar );
  1363. return this;
  1364. },
  1365. containsPoint: function ( point ) {
  1366. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1367. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) &&
  1368. ( this.min.z <= point.z ) && ( point.z <= this.max.z ) ) {
  1369. return true;
  1370. }
  1371. return false;
  1372. },
  1373. containsBox: function ( box ) {
  1374. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1375. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1376. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1377. return true;
  1378. }
  1379. return false;
  1380. },
  1381. getParameter: function ( point ) {
  1382. // This can potentially have a divide by zero if the box
  1383. // has a size dimension of 0.
  1384. return new THREE.Vector3(
  1385. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1386. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1387. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1388. );
  1389. },
  1390. isIntersectionBox: function ( box ) {
  1391. // using 6 splitting planes to rule out intersections.
  1392. if ( ( box.max.x < this.min.x ) || ( box.min.x > this.max.x ) ||
  1393. ( box.max.y < this.min.y ) || ( box.min.y > this.max.y ) ||
  1394. ( box.max.z < this.min.z ) || ( box.min.z > this.max.z ) ) {
  1395. return false;
  1396. }
  1397. return true;
  1398. },
  1399. clampPoint: function ( point, optionalTarget ) {
  1400. var result = optionalTarget || new THREE.Vector3();
  1401. return new THREE.Vector3().copy( point ).clampSelf( this.min, this.max );
  1402. },
  1403. distanceToPoint: function ( point ) {
  1404. var clampedPoint = THREE.Box3.__v1.copy( point ).clampSelf( this.min, this.max );
  1405. return clampedPoint.subSelf( point ).length();
  1406. },
  1407. intersect: function ( box ) {
  1408. this.min.maxSelf( box.min );
  1409. this.max.minSelf( box.max );
  1410. return this;
  1411. },
  1412. union: function ( box ) {
  1413. this.min.minSelf( box.min );
  1414. this.max.maxSelf( box.max );
  1415. return this;
  1416. },
  1417. translate: function ( offset ) {
  1418. this.min.addSelf( offset );
  1419. this.max.addSelf( offset );
  1420. return this;
  1421. },
  1422. scale: function ( factor ) {
  1423. var sizeDeltaHalf = this.size().multiplyScalar( ( factor - 1 ) * 0.5 );
  1424. this.expandByVector( sizeDeltaHalf );
  1425. return this;
  1426. },
  1427. equals: function ( box ) {
  1428. return box.min.equals( this.min ) && box.max.equals( this.max );
  1429. },
  1430. clone: function () {
  1431. return new THREE.Box3().copy( this );
  1432. }
  1433. };
  1434. THREE.Box3.__v1 = new THREE.Vector3();
  1435. /**
  1436. * @author alteredq / http://alteredqualia.com/
  1437. * @author WestLangley / http://github.com/WestLangley
  1438. */
  1439. THREE.Matrix3 = function () {
  1440. this.elements = new Float32Array(9);
  1441. };
  1442. THREE.Matrix3.prototype = {
  1443. constructor: THREE.Matrix3,
  1444. multiplyVector3: function ( v ) {
  1445. var te = this.elements;
  1446. var vx = v.x, vy = v.y, vz = v.z;
  1447. v.x = te[0] * vx + te[3] * vy + te[6] * vz;
  1448. v.y = te[1] * vx + te[4] * vy + te[7] * vz;
  1449. v.z = te[2] * vx + te[5] * vy + te[8] * vz;
  1450. return v;
  1451. },
  1452. multiplyVector3Array: function ( a ) {
  1453. var tmp = THREE.Matrix3.__v1;
  1454. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1455. tmp.x = a[ i ];
  1456. tmp.y = a[ i + 1 ];
  1457. tmp.z = a[ i + 2 ];
  1458. this.multiplyVector3( tmp );
  1459. a[ i ] = tmp.x;
  1460. a[ i + 1 ] = tmp.y;
  1461. a[ i + 2 ] = tmp.z;
  1462. }
  1463. return a;
  1464. },
  1465. getInverse: function ( matrix ) {
  1466. // input: THREE.Matrix4
  1467. // ( based on http://code.google.com/p/webgl-mjs/ )
  1468. var me = matrix.elements;
  1469. var a11 = me[10] * me[5] - me[6] * me[9];
  1470. var a21 = - me[10] * me[1] + me[2] * me[9];
  1471. var a31 = me[6] * me[1] - me[2] * me[5];
  1472. var a12 = - me[10] * me[4] + me[6] * me[8];
  1473. var a22 = me[10] * me[0] - me[2] * me[8];
  1474. var a32 = - me[6] * me[0] + me[2] * me[4];
  1475. var a13 = me[9] * me[4] - me[5] * me[8];
  1476. var a23 = - me[9] * me[0] + me[1] * me[8];
  1477. var a33 = me[5] * me[0] - me[1] * me[4];
  1478. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  1479. // no inverse
  1480. if ( det === 0 ) {
  1481. console.warn( "Matrix3.getInverse(): determinant == 0" );
  1482. }
  1483. var idet = 1.0 / det;
  1484. var m = this.elements;
  1485. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  1486. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  1487. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  1488. return this;
  1489. },
  1490. transpose: function () {
  1491. var tmp, m = this.elements;
  1492. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1493. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1494. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1495. return this;
  1496. },
  1497. transposeIntoArray: function ( r ) {
  1498. var m = this.elements;
  1499. r[ 0 ] = m[ 0 ];
  1500. r[ 1 ] = m[ 3 ];
  1501. r[ 2 ] = m[ 6 ];
  1502. r[ 3 ] = m[ 1 ];
  1503. r[ 4 ] = m[ 4 ];
  1504. r[ 5 ] = m[ 7 ];
  1505. r[ 6 ] = m[ 2 ];
  1506. r[ 7 ] = m[ 5 ];
  1507. r[ 8 ] = m[ 8 ];
  1508. return this;
  1509. }
  1510. };
  1511. THREE.Matrix3.__v1 = new THREE.Vector3();/**
  1512. * @author mrdoob / http://mrdoob.com/
  1513. * @author supereggbert / http://www.paulbrunt.co.uk/
  1514. * @author philogb / http://blog.thejit.org/
  1515. * @author jordi_ros / http://plattsoft.com
  1516. * @author D1plo1d / http://github.com/D1plo1d
  1517. * @author alteredq / http://alteredqualia.com/
  1518. * @author mikael emtinger / http://gomo.se/
  1519. * @author timknip / http://www.floorplanner.com/
  1520. */
  1521. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1522. this.elements = new Float32Array( 16 );
  1523. this.set(
  1524. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1525. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1526. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1527. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1528. );
  1529. };
  1530. THREE.Matrix4.prototype = {
  1531. constructor: THREE.Matrix4,
  1532. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1533. var te = this.elements;
  1534. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1535. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1536. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1537. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1538. return this;
  1539. },
  1540. identity: function () {
  1541. this.set(
  1542. 1, 0, 0, 0,
  1543. 0, 1, 0, 0,
  1544. 0, 0, 1, 0,
  1545. 0, 0, 0, 1
  1546. );
  1547. return this;
  1548. },
  1549. copy: function ( m ) {
  1550. var me = m.elements;
  1551. this.set(
  1552. me[0], me[4], me[8], me[12],
  1553. me[1], me[5], me[9], me[13],
  1554. me[2], me[6], me[10], me[14],
  1555. me[3], me[7], me[11], me[15]
  1556. );
  1557. return this;
  1558. },
  1559. lookAt: function ( eye, target, up ) {
  1560. var te = this.elements;
  1561. var x = THREE.Matrix4.__v1;
  1562. var y = THREE.Matrix4.__v2;
  1563. var z = THREE.Matrix4.__v3;
  1564. z.sub( eye, target ).normalize();
  1565. if ( z.length() === 0 ) {
  1566. z.z = 1;
  1567. }
  1568. x.cross( up, z ).normalize();
  1569. if ( x.length() === 0 ) {
  1570. z.x += 0.0001;
  1571. x.cross( up, z ).normalize();
  1572. }
  1573. y.cross( z, x );
  1574. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1575. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1576. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1577. return this;
  1578. },
  1579. multiply: function ( a, b ) {
  1580. var ae = a.elements;
  1581. var be = b.elements;
  1582. var te = this.elements;
  1583. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1584. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1585. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1586. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1587. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1588. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1589. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1590. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1591. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1592. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1593. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1594. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1595. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1596. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1597. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1598. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1599. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1600. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1601. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1602. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1603. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1604. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1605. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1606. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1607. return this;
  1608. },
  1609. multiplySelf: function ( m ) {
  1610. return this.multiply( this, m );
  1611. },
  1612. multiplyToArray: function ( a, b, r ) {
  1613. var te = this.elements;
  1614. this.multiply( a, b );
  1615. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1616. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1617. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1618. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1619. return this;
  1620. },
  1621. multiplyScalar: function ( s ) {
  1622. var te = this.elements;
  1623. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1624. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1625. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1626. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1627. return this;
  1628. },
  1629. multiplyVector3: function ( v ) {
  1630. var te = this.elements;
  1631. var vx = v.x, vy = v.y, vz = v.z;
  1632. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1633. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1634. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1635. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1636. return v;
  1637. },
  1638. multiplyVector4: function ( v ) {
  1639. var te = this.elements;
  1640. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1641. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1642. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1643. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1644. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1645. return v;
  1646. },
  1647. multiplyVector3Array: function ( a ) {
  1648. var tmp = THREE.Matrix4.__v1;
  1649. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1650. tmp.x = a[ i ];
  1651. tmp.y = a[ i + 1 ];
  1652. tmp.z = a[ i + 2 ];
  1653. this.multiplyVector3( tmp );
  1654. a[ i ] = tmp.x;
  1655. a[ i + 1 ] = tmp.y;
  1656. a[ i + 2 ] = tmp.z;
  1657. }
  1658. return a;
  1659. },
  1660. rotateAxis: function ( v ) {
  1661. var te = this.elements;
  1662. var vx = v.x, vy = v.y, vz = v.z;
  1663. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1664. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1665. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1666. v.normalize();
  1667. return v;
  1668. },
  1669. crossVector: function ( a ) {
  1670. var te = this.elements;
  1671. var v = new THREE.Vector4();
  1672. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1673. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1674. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1675. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1676. return v;
  1677. },
  1678. determinant: function () {
  1679. var te = this.elements;
  1680. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1681. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1682. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1683. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1684. //TODO: make this more efficient
  1685. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1686. return (
  1687. n14 * n23 * n32 * n41-
  1688. n13 * n24 * n32 * n41-
  1689. n14 * n22 * n33 * n41+
  1690. n12 * n24 * n33 * n41+
  1691. n13 * n22 * n34 * n41-
  1692. n12 * n23 * n34 * n41-
  1693. n14 * n23 * n31 * n42+
  1694. n13 * n24 * n31 * n42+
  1695. n14 * n21 * n33 * n42-
  1696. n11 * n24 * n33 * n42-
  1697. n13 * n21 * n34 * n42+
  1698. n11 * n23 * n34 * n42+
  1699. n14 * n22 * n31 * n43-
  1700. n12 * n24 * n31 * n43-
  1701. n14 * n21 * n32 * n43+
  1702. n11 * n24 * n32 * n43+
  1703. n12 * n21 * n34 * n43-
  1704. n11 * n22 * n34 * n43-
  1705. n13 * n22 * n31 * n44+
  1706. n12 * n23 * n31 * n44+
  1707. n13 * n21 * n32 * n44-
  1708. n11 * n23 * n32 * n44-
  1709. n12 * n21 * n33 * n44+
  1710. n11 * n22 * n33 * n44
  1711. );
  1712. },
  1713. transpose: function () {
  1714. var te = this.elements;
  1715. var tmp;
  1716. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1717. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1718. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1719. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1720. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1721. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1722. return this;
  1723. },
  1724. flattenToArray: function ( flat ) {
  1725. var te = this.elements;
  1726. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1727. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1728. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1729. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1730. return flat;
  1731. },
  1732. flattenToArrayOffset: function( flat, offset ) {
  1733. var te = this.elements;
  1734. flat[ offset ] = te[0];
  1735. flat[ offset + 1 ] = te[1];
  1736. flat[ offset + 2 ] = te[2];
  1737. flat[ offset + 3 ] = te[3];
  1738. flat[ offset + 4 ] = te[4];
  1739. flat[ offset + 5 ] = te[5];
  1740. flat[ offset + 6 ] = te[6];
  1741. flat[ offset + 7 ] = te[7];
  1742. flat[ offset + 8 ] = te[8];
  1743. flat[ offset + 9 ] = te[9];
  1744. flat[ offset + 10 ] = te[10];
  1745. flat[ offset + 11 ] = te[11];
  1746. flat[ offset + 12 ] = te[12];
  1747. flat[ offset + 13 ] = te[13];
  1748. flat[ offset + 14 ] = te[14];
  1749. flat[ offset + 15 ] = te[15];
  1750. return flat;
  1751. },
  1752. getPosition: function () {
  1753. var te = this.elements;
  1754. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1755. },
  1756. setPosition: function ( v ) {
  1757. var te = this.elements;
  1758. te[12] = v.x;
  1759. te[13] = v.y;
  1760. te[14] = v.z;
  1761. return this;
  1762. },
  1763. getColumnX: function () {
  1764. var te = this.elements;
  1765. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1766. },
  1767. getColumnY: function () {
  1768. var te = this.elements;
  1769. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1770. },
  1771. getColumnZ: function() {
  1772. var te = this.elements;
  1773. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1774. },
  1775. getInverse: function ( m ) {
  1776. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1777. var te = this.elements;
  1778. var me = m.elements;
  1779. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1780. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1781. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1782. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1783. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1784. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1785. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1786. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1787. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1788. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1789. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1790. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1791. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1792. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1793. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1794. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1795. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1796. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1797. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1798. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1799. this.multiplyScalar( 1 / m.determinant() );
  1800. return this;
  1801. },
  1802. setRotationFromEuler: function ( v, order ) {
  1803. var te = this.elements;
  1804. var x = v.x, y = v.y, z = v.z;
  1805. var a = Math.cos( x ), b = Math.sin( x );
  1806. var c = Math.cos( y ), d = Math.sin( y );
  1807. var e = Math.cos( z ), f = Math.sin( z );
  1808. if ( order === undefined || order === 'XYZ' ) {
  1809. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1810. te[0] = c * e;
  1811. te[4] = - c * f;
  1812. te[8] = d;
  1813. te[1] = af + be * d;
  1814. te[5] = ae - bf * d;
  1815. te[9] = - b * c;
  1816. te[2] = bf - ae * d;
  1817. te[6] = be + af * d;
  1818. te[10] = a * c;
  1819. } else if ( order === 'YXZ' ) {
  1820. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1821. te[0] = ce + df * b;
  1822. te[4] = de * b - cf;
  1823. te[8] = a * d;
  1824. te[1] = a * f;
  1825. te[5] = a * e;
  1826. te[9] = - b;
  1827. te[2] = cf * b - de;
  1828. te[6] = df + ce * b;
  1829. te[10] = a * c;
  1830. } else if ( order === 'ZXY' ) {
  1831. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1832. te[0] = ce - df * b;
  1833. te[4] = - a * f;
  1834. te[8] = de + cf * b;
  1835. te[1] = cf + de * b;
  1836. te[5] = a * e;
  1837. te[9] = df - ce * b;
  1838. te[2] = - a * d;
  1839. te[6] = b;
  1840. te[10] = a * c;
  1841. } else if ( order === 'ZYX' ) {
  1842. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1843. te[0] = c * e;
  1844. te[4] = be * d - af;
  1845. te[8] = ae * d + bf;
  1846. te[1] = c * f;
  1847. te[5] = bf * d + ae;
  1848. te[9] = af * d - be;
  1849. te[2] = - d;
  1850. te[6] = b * c;
  1851. te[10] = a * c;
  1852. } else if ( order === 'YZX' ) {
  1853. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1854. te[0] = c * e;
  1855. te[4] = bd - ac * f;
  1856. te[8] = bc * f + ad;
  1857. te[1] = f;
  1858. te[5] = a * e;
  1859. te[9] = - b * e;
  1860. te[2] = - d * e;
  1861. te[6] = ad * f + bc;
  1862. te[10] = ac - bd * f;
  1863. } else if ( order === 'XZY' ) {
  1864. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1865. te[0] = c * e;
  1866. te[4] = - f;
  1867. te[8] = d * e;
  1868. te[1] = ac * f + bd;
  1869. te[5] = a * e;
  1870. te[9] = ad * f - bc;
  1871. te[2] = bc * f - ad;
  1872. te[6] = b * e;
  1873. te[10] = bd * f + ac;
  1874. }
  1875. return this;
  1876. },
  1877. setRotationFromQuaternion: function ( q ) {
  1878. var te = this.elements;
  1879. var x = q.x, y = q.y, z = q.z, w = q.w;
  1880. var x2 = x + x, y2 = y + y, z2 = z + z;
  1881. var xx = x * x2, xy = x * y2, xz = x * z2;
  1882. var yy = y * y2, yz = y * z2, zz = z * z2;
  1883. var wx = w * x2, wy = w * y2, wz = w * z2;
  1884. te[0] = 1 - ( yy + zz );
  1885. te[4] = xy - wz;
  1886. te[8] = xz + wy;
  1887. te[1] = xy + wz;
  1888. te[5] = 1 - ( xx + zz );
  1889. te[9] = yz - wx;
  1890. te[2] = xz - wy;
  1891. te[6] = yz + wx;
  1892. te[10] = 1 - ( xx + yy );
  1893. return this;
  1894. },
  1895. compose: function ( translation, rotation, scale ) {
  1896. var te = this.elements;
  1897. var mRotation = THREE.Matrix4.__m1;
  1898. var mScale = THREE.Matrix4.__m2;
  1899. mRotation.identity();
  1900. mRotation.setRotationFromQuaternion( rotation );
  1901. mScale.makeScale( scale.x, scale.y, scale.z );
  1902. this.multiply( mRotation, mScale );
  1903. te[12] = translation.x;
  1904. te[13] = translation.y;
  1905. te[14] = translation.z;
  1906. return this;
  1907. },
  1908. decompose: function ( translation, rotation, scale ) {
  1909. var te = this.elements;
  1910. // grab the axis vectors
  1911. var x = THREE.Matrix4.__v1;
  1912. var y = THREE.Matrix4.__v2;
  1913. var z = THREE.Matrix4.__v3;
  1914. x.set( te[0], te[1], te[2] );
  1915. y.set( te[4], te[5], te[6] );
  1916. z.set( te[8], te[9], te[10] );
  1917. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1918. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1919. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1920. scale.x = x.length();
  1921. scale.y = y.length();
  1922. scale.z = z.length();
  1923. translation.x = te[12];
  1924. translation.y = te[13];
  1925. translation.z = te[14];
  1926. // scale the rotation part
  1927. var matrix = THREE.Matrix4.__m1;
  1928. matrix.copy( this );
  1929. matrix.elements[0] /= scale.x;
  1930. matrix.elements[1] /= scale.x;
  1931. matrix.elements[2] /= scale.x;
  1932. matrix.elements[4] /= scale.y;
  1933. matrix.elements[5] /= scale.y;
  1934. matrix.elements[6] /= scale.y;
  1935. matrix.elements[8] /= scale.z;
  1936. matrix.elements[9] /= scale.z;
  1937. matrix.elements[10] /= scale.z;
  1938. rotation.setFromRotationMatrix( matrix );
  1939. return [ translation, rotation, scale ];
  1940. },
  1941. extractPosition: function ( m ) {
  1942. var te = this.elements;
  1943. var me = m.elements;
  1944. te[12] = me[12];
  1945. te[13] = me[13];
  1946. te[14] = me[14];
  1947. return this;
  1948. },
  1949. extractRotation: function ( m ) {
  1950. var te = this.elements;
  1951. var me = m.elements;
  1952. var vector = THREE.Matrix4.__v1;
  1953. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1954. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1955. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1956. te[0] = me[0] * scaleX;
  1957. te[1] = me[1] * scaleX;
  1958. te[2] = me[2] * scaleX;
  1959. te[4] = me[4] * scaleY;
  1960. te[5] = me[5] * scaleY;
  1961. te[6] = me[6] * scaleY;
  1962. te[8] = me[8] * scaleZ;
  1963. te[9] = me[9] * scaleZ;
  1964. te[10] = me[10] * scaleZ;
  1965. return this;
  1966. },
  1967. //
  1968. translate: function ( v ) {
  1969. var te = this.elements;
  1970. var x = v.x, y = v.y, z = v.z;
  1971. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1972. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1973. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1974. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1975. return this;
  1976. },
  1977. rotateX: function ( angle ) {
  1978. var te = this.elements;
  1979. var m12 = te[4];
  1980. var m22 = te[5];
  1981. var m32 = te[6];
  1982. var m42 = te[7];
  1983. var m13 = te[8];
  1984. var m23 = te[9];
  1985. var m33 = te[10];
  1986. var m43 = te[11];
  1987. var c = Math.cos( angle );
  1988. var s = Math.sin( angle );
  1989. te[4] = c * m12 + s * m13;
  1990. te[5] = c * m22 + s * m23;
  1991. te[6] = c * m32 + s * m33;
  1992. te[7] = c * m42 + s * m43;
  1993. te[8] = c * m13 - s * m12;
  1994. te[9] = c * m23 - s * m22;
  1995. te[10] = c * m33 - s * m32;
  1996. te[11] = c * m43 - s * m42;
  1997. return this;
  1998. },
  1999. rotateY: function ( angle ) {
  2000. var te = this.elements;
  2001. var m11 = te[0];
  2002. var m21 = te[1];
  2003. var m31 = te[2];
  2004. var m41 = te[3];
  2005. var m13 = te[8];
  2006. var m23 = te[9];
  2007. var m33 = te[10];
  2008. var m43 = te[11];
  2009. var c = Math.cos( angle );
  2010. var s = Math.sin( angle );
  2011. te[0] = c * m11 - s * m13;
  2012. te[1] = c * m21 - s * m23;
  2013. te[2] = c * m31 - s * m33;
  2014. te[3] = c * m41 - s * m43;
  2015. te[8] = c * m13 + s * m11;
  2016. te[9] = c * m23 + s * m21;
  2017. te[10] = c * m33 + s * m31;
  2018. te[11] = c * m43 + s * m41;
  2019. return this;
  2020. },
  2021. rotateZ: function ( angle ) {
  2022. var te = this.elements;
  2023. var m11 = te[0];
  2024. var m21 = te[1];
  2025. var m31 = te[2];
  2026. var m41 = te[3];
  2027. var m12 = te[4];
  2028. var m22 = te[5];
  2029. var m32 = te[6];
  2030. var m42 = te[7];
  2031. var c = Math.cos( angle );
  2032. var s = Math.sin( angle );
  2033. te[0] = c * m11 + s * m12;
  2034. te[1] = c * m21 + s * m22;
  2035. te[2] = c * m31 + s * m32;
  2036. te[3] = c * m41 + s * m42;
  2037. te[4] = c * m12 - s * m11;
  2038. te[5] = c * m22 - s * m21;
  2039. te[6] = c * m32 - s * m31;
  2040. te[7] = c * m42 - s * m41;
  2041. return this;
  2042. },
  2043. rotateByAxis: function ( axis, angle ) {
  2044. var te = this.elements;
  2045. // optimize by checking axis
  2046. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2047. return this.rotateX( angle );
  2048. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2049. return this.rotateY( angle );
  2050. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2051. return this.rotateZ( angle );
  2052. }
  2053. var x = axis.x, y = axis.y, z = axis.z;
  2054. var n = Math.sqrt(x * x + y * y + z * z);
  2055. x /= n;
  2056. y /= n;
  2057. z /= n;
  2058. var xx = x * x, yy = y * y, zz = z * z;
  2059. var c = Math.cos( angle );
  2060. var s = Math.sin( angle );
  2061. var oneMinusCosine = 1 - c;
  2062. var xy = x * y * oneMinusCosine;
  2063. var xz = x * z * oneMinusCosine;
  2064. var yz = y * z * oneMinusCosine;
  2065. var xs = x * s;
  2066. var ys = y * s;
  2067. var zs = z * s;
  2068. var r11 = xx + (1 - xx) * c;
  2069. var r21 = xy + zs;
  2070. var r31 = xz - ys;
  2071. var r12 = xy - zs;
  2072. var r22 = yy + (1 - yy) * c;
  2073. var r32 = yz + xs;
  2074. var r13 = xz + ys;
  2075. var r23 = yz - xs;
  2076. var r33 = zz + (1 - zz) * c;
  2077. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2078. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2079. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2080. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  2081. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2082. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2083. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2084. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2085. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2086. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2087. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2088. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2089. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2090. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2091. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2092. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2093. return this;
  2094. },
  2095. scale: function ( v ) {
  2096. var te = this.elements;
  2097. var x = v.x, y = v.y, z = v.z;
  2098. te[0] *= x; te[4] *= y; te[8] *= z;
  2099. te[1] *= x; te[5] *= y; te[9] *= z;
  2100. te[2] *= x; te[6] *= y; te[10] *= z;
  2101. te[3] *= x; te[7] *= y; te[11] *= z;
  2102. return this;
  2103. },
  2104. getMaxScaleOnAxis: function () {
  2105. var te = this.elements;
  2106. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2107. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2108. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2109. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2110. },
  2111. //
  2112. makeTranslation: function ( x, y, z ) {
  2113. this.set(
  2114. 1, 0, 0, x,
  2115. 0, 1, 0, y,
  2116. 0, 0, 1, z,
  2117. 0, 0, 0, 1
  2118. );
  2119. return this;
  2120. },
  2121. makeRotationX: function ( theta ) {
  2122. var c = Math.cos( theta ), s = Math.sin( theta );
  2123. this.set(
  2124. 1, 0, 0, 0,
  2125. 0, c, -s, 0,
  2126. 0, s, c, 0,
  2127. 0, 0, 0, 1
  2128. );
  2129. return this;
  2130. },
  2131. makeRotationY: function ( theta ) {
  2132. var c = Math.cos( theta ), s = Math.sin( theta );
  2133. this.set(
  2134. c, 0, s, 0,
  2135. 0, 1, 0, 0,
  2136. -s, 0, c, 0,
  2137. 0, 0, 0, 1
  2138. );
  2139. return this;
  2140. },
  2141. makeRotationZ: function ( theta ) {
  2142. var c = Math.cos( theta ), s = Math.sin( theta );
  2143. this.set(
  2144. c, -s, 0, 0,
  2145. s, c, 0, 0,
  2146. 0, 0, 1, 0,
  2147. 0, 0, 0, 1
  2148. );
  2149. return this;
  2150. },
  2151. makeRotationAxis: function ( axis, angle ) {
  2152. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2153. var c = Math.cos( angle );
  2154. var s = Math.sin( angle );
  2155. var t = 1 - c;
  2156. var x = axis.x, y = axis.y, z = axis.z;
  2157. var tx = t * x, ty = t * y;
  2158. this.set(
  2159. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2160. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2161. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2162. 0, 0, 0, 1
  2163. );
  2164. return this;
  2165. },
  2166. makeScale: function ( x, y, z ) {
  2167. this.set(
  2168. x, 0, 0, 0,
  2169. 0, y, 0, 0,
  2170. 0, 0, z, 0,
  2171. 0, 0, 0, 1
  2172. );
  2173. return this;
  2174. },
  2175. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2176. var te = this.elements;
  2177. var x = 2 * near / ( right - left );
  2178. var y = 2 * near / ( top - bottom );
  2179. var a = ( right + left ) / ( right - left );
  2180. var b = ( top + bottom ) / ( top - bottom );
  2181. var c = - ( far + near ) / ( far - near );
  2182. var d = - 2 * far * near / ( far - near );
  2183. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2184. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2185. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2186. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2187. return this;
  2188. },
  2189. makePerspective: function ( fov, aspect, near, far ) {
  2190. var ymax = near * Math.tan( fov * Math.PI / 360 );
  2191. var ymin = - ymax;
  2192. var xmin = ymin * aspect;
  2193. var xmax = ymax * aspect;
  2194. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2195. },
  2196. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2197. var te = this.elements;
  2198. var w = right - left;
  2199. var h = top - bottom;
  2200. var p = far - near;
  2201. var x = ( right + left ) / w;
  2202. var y = ( top + bottom ) / h;
  2203. var z = ( far + near ) / p;
  2204. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2205. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2206. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  2207. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2208. return this;
  2209. },
  2210. clone: function () {
  2211. var te = this.elements;
  2212. return new THREE.Matrix4(
  2213. te[0], te[4], te[8], te[12],
  2214. te[1], te[5], te[9], te[13],
  2215. te[2], te[6], te[10], te[14],
  2216. te[3], te[7], te[11], te[15]
  2217. );
  2218. }
  2219. };
  2220. THREE.Matrix4.__v1 = new THREE.Vector3();
  2221. THREE.Matrix4.__v2 = new THREE.Vector3();
  2222. THREE.Matrix4.__v3 = new THREE.Vector3();
  2223. THREE.Matrix4.__m1 = new THREE.Matrix4();
  2224. THREE.Matrix4.__m2 = new THREE.Matrix4();
  2225. /**
  2226. * @author bhouston / http://exocortex.com
  2227. */
  2228. THREE.Ray = function ( origin, direction ) {
  2229. this.origin = origin !== undefined ? origin.clone() : new THREE.Vector3();
  2230. this.direction = direction !== undefined ? direction.clone() : new THREE.Vector3();
  2231. };
  2232. THREE.Ray.prototype = {
  2233. constructor: THREE.Ray,
  2234. set: function ( origin, direction ) {
  2235. this.origin.copy( origin );
  2236. this.direction.copy( direction );
  2237. return this;
  2238. },
  2239. copy: function ( ray ) {
  2240. this.origin.copy( ray.origin );
  2241. this.direction.copy( ray.direction );
  2242. return this;
  2243. },
  2244. at: function( t, optionalTarget ) {
  2245. var result = optionalTarget || new THREE.Vector3();
  2246. return result.copy( this.direction ).multiplyScalar( t ).addSelf( this.origin );
  2247. },
  2248. recastSelf: function ( t ) {
  2249. this.origin.copy( this.at( t, THREE.Ray.__v1 ) );
  2250. return this;
  2251. },
  2252. closestPointToPoint: function ( point, optionalTarget ) {
  2253. var result = optionalTarget || new THREE.Vector3();
  2254. result.sub( point, this.origin );
  2255. var directionDistance = result.dot( this.direction );
  2256. return result.copy( this.direction ).multiplyScalar( directionDistance ).addSelf( this.origin );
  2257. },
  2258. distanceToPoint: function ( point ) {
  2259. var directionDistance = THREE.Ray.__v1.sub( point, this.origin ).dot( this.direction );
  2260. THREE.Ray.__v1.copy( this.direction ).multiplyScalar( directionDistance ).addSelf( this.origin );
  2261. return THREE.Ray.__v1.distanceTo( point );
  2262. },
  2263. isIntersectionSphere: function( sphere ) {
  2264. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2265. },
  2266. isIntersectionPlane: function ( plane ) {
  2267. // check if the line and plane are non-perpendicular, if they
  2268. // eventually they will intersect.
  2269. var denominator = plane.normal.dot( this.direction );
  2270. if ( denominator != 0 ) {
  2271. return true;
  2272. }
  2273. // line is coplanar, return origin
  2274. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2275. return true;
  2276. }
  2277. return false;
  2278. },
  2279. distanceToPlane: function ( plane ) {
  2280. var denominator = plane.normal.dot( this.direction );
  2281. if ( denominator == 0 ) {
  2282. // line is coplanar, return origin
  2283. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2284. return 0;
  2285. }
  2286. // Unsure if this is the correct method to handle this case.
  2287. return undefined;
  2288. }
  2289. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2290. return t;
  2291. },
  2292. intersectPlane: function ( plane, optionalTarget ) {
  2293. var t = this.distanceToPlane( plane );
  2294. if( t === undefined ) {
  2295. return undefined;
  2296. }
  2297. return this.at( t, optionalTarget );
  2298. },
  2299. transformSelf: function ( matrix4 ) {
  2300. this.direction = matrix4.multiplyVector3( this.direction.addSelf( this.origin ) );
  2301. this.origin = matrix4.multiplyVector3( this.origin );
  2302. this.direction.subSelf( this.origin );
  2303. return this;
  2304. },
  2305. equals: function ( ray ) {
  2306. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2307. },
  2308. clone: function () {
  2309. return new THREE.Ray().copy( this );
  2310. }
  2311. };
  2312. THREE.Ray.__v1 = new THREE.Vector3();
  2313. THREE.Ray.__v2 = new THREE.Vector3();/**
  2314. * @author mrdoob / http://mrdoob.com/
  2315. * @author alteredq / http://alteredqualia.com/
  2316. * @author bhouston / http://exocortex.com
  2317. */
  2318. THREE.Frustum = function ( ) {
  2319. this.planes = [
  2320. new THREE.Plane(),
  2321. new THREE.Plane(),
  2322. new THREE.Plane(),
  2323. new THREE.Plane(),
  2324. new THREE.Plane(),
  2325. new THREE.Plane()
  2326. ];
  2327. };
  2328. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  2329. var planes = this.planes;
  2330. var me = m.elements;
  2331. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2332. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2333. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2334. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2335. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  2336. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  2337. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  2338. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  2339. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  2340. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  2341. for ( var i = 0; i < 6; i ++ ) {
  2342. planes[ i ].normalize();
  2343. }
  2344. };
  2345. THREE.Frustum.prototype.contains = function ( object ) {
  2346. var planes = this.planes;
  2347. var matrix = object.matrixWorld;
  2348. var matrixPosition = matrix.getPosition();
  2349. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2350. var distance = 0.0;
  2351. for ( var i = 0; i < 6; i ++ ) {
  2352. distance = planes[ i ].distanceToPoint( matrixPosition );
  2353. if ( distance <= radius ) return false;
  2354. }
  2355. return true;
  2356. };
  2357. THREE.Frustum.__v1 = new THREE.Vector3();
  2358. /**
  2359. * @author bhouston / http://exocortex.com
  2360. */
  2361. THREE.Plane = function ( normal, constant ) {
  2362. this.normal = normal !== undefined ? normal.clone() : new THREE.Vector3();
  2363. this.constant = constant !== undefined ? constant : 0;
  2364. };
  2365. THREE.Plane.prototype = {
  2366. constructor: THREE.Plane,
  2367. set: function ( normal, constant ) {
  2368. this.normal.copy( normal );
  2369. this.constant = constant;
  2370. return this;
  2371. },
  2372. setComponents: function ( x, y, z, w ) {
  2373. this.normal.set( x, y, z );
  2374. this.constant = w;
  2375. return this;
  2376. },
  2377. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  2378. this.normal.copy( normal );
  2379. this.constant = - point.dot( normal );
  2380. return this;
  2381. },
  2382. setFromCoplanarPoints: function ( a, b, c ) {
  2383. var normal = THREE.Plane.__v1.sub( c, b ).crossSelf(
  2384. THREE.Plane.__v2.sub( a, b ) );
  2385. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  2386. this.setFromNormalAndCoplanarPoint( normal, a );
  2387. return this;
  2388. },
  2389. copy: function ( plane ) {
  2390. this.normal.copy( plane.normal );
  2391. this.constant = plane.constant;
  2392. return this;
  2393. },
  2394. normalize: function () {
  2395. // Note: will lead to a divide by zero if the plane is invalid.
  2396. var inverseNormalLength = 1.0 / this.normal.length();
  2397. this.normal.multiplyScalar( inverseNormalLength );
  2398. this.constant *= inverseNormalLength;
  2399. return this;
  2400. },
  2401. distanceToPoint: function ( point ) {
  2402. return this.normal.dot( point ) + this.constant;
  2403. },
  2404. distanceToSphere: function ( sphere ) {
  2405. return this.distanceToPoint( sphere.center ) - sphere.radius;
  2406. },
  2407. projectPoint: function ( point, optionalTarget ) {
  2408. return this.orthoPoint( point, optionalTarget ).subSelf( point ).negate();
  2409. },
  2410. orthoPoint: function ( point, optionalTarget ) {
  2411. var perpendicularMagnitude = this.distanceToPoint( point );
  2412. var result = optionalTarget || new THREE.Vector3();
  2413. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  2414. },
  2415. isIntersectionLine: function ( startPoint, endPoint ) {
  2416. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  2417. var startSign = this.distanceToPoint( startPoint );
  2418. var endSign = this.distanceToPoint( endPoint );
  2419. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  2420. },
  2421. coplanarPoint: function ( optionalTarget ) {
  2422. var result = optionalTarget || new THREE.Vector3();
  2423. return result.copy( this.normal ).multiplyScalar( - this.constant );
  2424. },
  2425. translate: function ( offset ) {
  2426. this.constant = - offset.dot( this.normal );
  2427. return this;
  2428. },
  2429. equals: function ( plane ) {
  2430. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  2431. },
  2432. clone: function () {
  2433. return new THREE.Plane().copy( this );
  2434. }
  2435. };
  2436. THREE.Plane.__v1 = new THREE.Vector3();
  2437. THREE.Plane.__v2 = new THREE.Vector3();
  2438. /**
  2439. * @author bhouston / http://exocortex.com
  2440. * @author mrdoob / http://mrdoob.com/
  2441. */
  2442. THREE.Sphere = function ( center, radius ) {
  2443. this.center = center === undefined ? new THREE.Vector3() : center.clone();
  2444. this.radius = radius === undefined ? 0 : radius;
  2445. };
  2446. THREE.Sphere.prototype = {
  2447. constructor: THREE.Sphere,
  2448. set: function ( center, radius ) {
  2449. this.center.copy( center );
  2450. this.radius = radius;
  2451. return this;
  2452. },
  2453. setFromCenterAndPoints: function ( center, points ) {
  2454. var maxRadiusSq = 0;
  2455. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2456. var radiusSq = center.distanceToSquared( points[ i ] );
  2457. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2458. }
  2459. this.center = center;
  2460. this.radius = Math.sqrt( maxRadiusSq );
  2461. return this;
  2462. },
  2463. copy: function ( sphere ) {
  2464. this.center.copy( sphere.center );
  2465. this.radius = sphere.radius;
  2466. return this;
  2467. },
  2468. empty: function () {
  2469. return ( this.radius <= 0 );
  2470. },
  2471. containsPoint: function ( point ) {
  2472. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2473. },
  2474. distanceToPoint: function ( point ) {
  2475. return ( point.distanceTo( this.center ) - this.radius );
  2476. },
  2477. clampPoint: function ( point, optionalTarget ) {
  2478. var deltaLengthSq = this.center.distanceToSquared( point );
  2479. var result = optionalTarget || new THREE.Vector3();
  2480. result.copy( point );
  2481. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2482. result.subSelf( this.center ).normalize();
  2483. result.multiplyScalar( this.radius ).addSelf( this.center );
  2484. }
  2485. return result;
  2486. },
  2487. bounds: function ( optionalTarget ) {
  2488. var box = optionalTarget || new THREE.Box3();
  2489. box.set( this.center, this.center );
  2490. box.expandByScalar( this.radius );
  2491. return box;
  2492. },
  2493. translate: function ( offset ) {
  2494. this.center.addSelf( this.offset );
  2495. return this;
  2496. },
  2497. scale: function ( factor ) {
  2498. this.radius *= factor;
  2499. return this;
  2500. },
  2501. equals: function ( sphere ) {
  2502. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2503. },
  2504. clone: function () {
  2505. return new THREE.Sphere3().copy( this );
  2506. }
  2507. };
  2508. /**
  2509. * @author alteredq / http://alteredqualia.com/
  2510. */
  2511. THREE.Math = {
  2512. // Clamp value to range <a, b>
  2513. clamp: function ( x, a, b ) {
  2514. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2515. },
  2516. // Clamp value to range <a, inf)
  2517. clampBottom: function ( x, a ) {
  2518. return x < a ? a : x;
  2519. },
  2520. // Linear mapping from range <a1, a2> to range <b1, b2>
  2521. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2522. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2523. },
  2524. // Random float from <0, 1> with 16 bits of randomness
  2525. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2526. random16: function () {
  2527. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2528. },
  2529. // Random integer from <low, high> interval
  2530. randInt: function ( low, high ) {
  2531. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2532. },
  2533. // Random float from <low, high> interval
  2534. randFloat: function ( low, high ) {
  2535. return low + Math.random() * ( high - low );
  2536. },
  2537. // Random float from <-range/2, range/2> interval
  2538. randFloatSpread: function ( range ) {
  2539. return range * ( 0.5 - Math.random() );
  2540. },
  2541. sign: function ( x ) {
  2542. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2543. },
  2544. degreesToRadians: function ( degrees ) {
  2545. return degrees * THREE.Math.__d2r;
  2546. },
  2547. radiansToDegrees: function ( radians ) {
  2548. return radians * THREE.Math.__r2d;
  2549. }
  2550. };
  2551. THREE.Math.__d2r = Math.PI / 180;
  2552. THREE.Math.__r2d = 180 / Math.PI;
  2553. /**
  2554. * @author mikael emtinger / http://gomo.se/
  2555. * @author alteredq / http://alteredqualia.com/
  2556. * @author WestLangley / http://github.com/WestLangley
  2557. */
  2558. THREE.Quaternion = function( x, y, z, w ) {
  2559. this.x = x || 0;
  2560. this.y = y || 0;
  2561. this.z = z || 0;
  2562. this.w = ( w !== undefined ) ? w : 1;
  2563. };
  2564. THREE.Quaternion.prototype = {
  2565. constructor: THREE.Quaternion,
  2566. set: function ( x, y, z, w ) {
  2567. this.x = x;
  2568. this.y = y;
  2569. this.z = z;
  2570. this.w = w;
  2571. return this;
  2572. },
  2573. copy: function ( q ) {
  2574. this.x = q.x;
  2575. this.y = q.y;
  2576. this.z = q.z;
  2577. this.w = q.w;
  2578. return this;
  2579. },
  2580. setFromEuler: function ( v, order ) {
  2581. // http://www.mathworks.com/matlabcentral/fileexchange/
  2582. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2583. // content/SpinCalc.m
  2584. var c1 = Math.cos( v.x / 2 );
  2585. var c2 = Math.cos( v.y / 2 );
  2586. var c3 = Math.cos( v.z / 2 );
  2587. var s1 = Math.sin( v.x / 2 );
  2588. var s2 = Math.sin( v.y / 2 );
  2589. var s3 = Math.sin( v.z / 2 );
  2590. if ( order === undefined || order === 'XYZ' ) {
  2591. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2592. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2593. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2594. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2595. } else if ( order === 'YXZ' ) {
  2596. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2597. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2598. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2599. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2600. } else if ( order === 'ZXY' ) {
  2601. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2602. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2603. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2604. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2605. } else if ( order === 'ZYX' ) {
  2606. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2607. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2608. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2609. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2610. } else if ( order === 'YZX' ) {
  2611. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2612. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2613. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2614. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2615. } else if ( order === 'XZY' ) {
  2616. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2617. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2618. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2619. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2620. }
  2621. return this;
  2622. },
  2623. setFromAxisAngle: function ( axis, angle ) {
  2624. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2625. // axis have to be normalized
  2626. var halfAngle = angle / 2,
  2627. s = Math.sin( halfAngle );
  2628. this.x = axis.x * s;
  2629. this.y = axis.y * s;
  2630. this.z = axis.z * s;
  2631. this.w = Math.cos( halfAngle );
  2632. return this;
  2633. },
  2634. setFromRotationMatrix: function ( m ) {
  2635. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2636. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2637. var te = m.elements,
  2638. m11 = te[0], m12 = te[4], m13 = te[8],
  2639. m21 = te[1], m22 = te[5], m23 = te[9],
  2640. m31 = te[2], m32 = te[6], m33 = te[10],
  2641. trace = m11 + m22 + m33,
  2642. s;
  2643. if( trace > 0 ) {
  2644. s = 0.5 / Math.sqrt( trace + 1.0 );
  2645. this.w = 0.25 / s;
  2646. this.x = ( m32 - m23 ) * s;
  2647. this.y = ( m13 - m31 ) * s;
  2648. this.z = ( m21 - m12 ) * s;
  2649. } else if ( m11 > m22 && m11 > m33 ) {
  2650. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2651. this.w = (m32 - m23 ) / s;
  2652. this.x = 0.25 * s;
  2653. this.y = (m12 + m21 ) / s;
  2654. this.z = (m13 + m31 ) / s;
  2655. } else if (m22 > m33) {
  2656. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2657. this.w = (m13 - m31 ) / s;
  2658. this.x = (m12 + m21 ) / s;
  2659. this.y = 0.25 * s;
  2660. this.z = (m23 + m32 ) / s;
  2661. } else {
  2662. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2663. this.w = ( m21 - m12 ) / s;
  2664. this.x = ( m13 + m31 ) / s;
  2665. this.y = ( m23 + m32 ) / s;
  2666. this.z = 0.25 * s;
  2667. }
  2668. return this;
  2669. },
  2670. inverse: function () {
  2671. this.conjugate().normalize();
  2672. return this;
  2673. },
  2674. conjugate: function () {
  2675. this.x *= -1;
  2676. this.y *= -1;
  2677. this.z *= -1;
  2678. return this;
  2679. },
  2680. length: function () {
  2681. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2682. },
  2683. normalize: function () {
  2684. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2685. if ( l === 0 ) {
  2686. this.x = 0;
  2687. this.y = 0;
  2688. this.z = 0;
  2689. this.w = 1;
  2690. } else {
  2691. l = 1 / l;
  2692. this.x = this.x * l;
  2693. this.y = this.y * l;
  2694. this.z = this.z * l;
  2695. this.w = this.w * l;
  2696. }
  2697. return this;
  2698. },
  2699. multiply: function ( a, b ) {
  2700. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2701. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2702. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2703. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2704. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2705. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2706. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2707. return this;
  2708. },
  2709. multiplySelf: function ( b ) {
  2710. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2711. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2712. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2713. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2714. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2715. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2716. return this;
  2717. },
  2718. multiplyVector3: function ( vector, dest ) {
  2719. if ( !dest ) { dest = vector; }
  2720. var x = vector.x, y = vector.y, z = vector.z,
  2721. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2722. // calculate quat * vector
  2723. var ix = qw * x + qy * z - qz * y,
  2724. iy = qw * y + qz * x - qx * z,
  2725. iz = qw * z + qx * y - qy * x,
  2726. iw = -qx * x - qy * y - qz * z;
  2727. // calculate result * inverse quat
  2728. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2729. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2730. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2731. return dest;
  2732. },
  2733. slerpSelf: function ( qb, t ) {
  2734. var x = this.x, y = this.y, z = this.z, w = this.w;
  2735. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2736. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2737. if ( cosHalfTheta < 0 ) {
  2738. this.w = -qb.w;
  2739. this.x = -qb.x;
  2740. this.y = -qb.y;
  2741. this.z = -qb.z;
  2742. cosHalfTheta = -cosHalfTheta;
  2743. } else {
  2744. this.copy( qb );
  2745. }
  2746. if ( cosHalfTheta >= 1.0 ) {
  2747. this.w = w;
  2748. this.x = x;
  2749. this.y = y;
  2750. this.z = z;
  2751. return this;
  2752. }
  2753. var halfTheta = Math.acos( cosHalfTheta );
  2754. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2755. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2756. this.w = 0.5 * ( w + this.w );
  2757. this.x = 0.5 * ( x + this.x );
  2758. this.y = 0.5 * ( y + this.y );
  2759. this.z = 0.5 * ( z + this.z );
  2760. return this;
  2761. }
  2762. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2763. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2764. this.w = ( w * ratioA + this.w * ratioB );
  2765. this.x = ( x * ratioA + this.x * ratioB );
  2766. this.y = ( y * ratioA + this.y * ratioB );
  2767. this.z = ( z * ratioA + this.z * ratioB );
  2768. return this;
  2769. },
  2770. clone: function () {
  2771. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2772. }
  2773. }
  2774. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2775. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2776. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2777. if ( cosHalfTheta < 0 ) {
  2778. qm.w = -qb.w;
  2779. qm.x = -qb.x;
  2780. qm.y = -qb.y;
  2781. qm.z = -qb.z;
  2782. cosHalfTheta = -cosHalfTheta;
  2783. } else {
  2784. qm.copy( qb );
  2785. }
  2786. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2787. qm.w = qa.w;
  2788. qm.x = qa.x;
  2789. qm.y = qa.y;
  2790. qm.z = qa.z;
  2791. return qm;
  2792. }
  2793. var halfTheta = Math.acos( cosHalfTheta );
  2794. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2795. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2796. qm.w = 0.5 * ( qa.w + qm.w );
  2797. qm.x = 0.5 * ( qa.x + qm.x );
  2798. qm.y = 0.5 * ( qa.y + qm.y );
  2799. qm.z = 0.5 * ( qa.z + qm.z );
  2800. return qm;
  2801. }
  2802. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2803. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2804. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2805. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2806. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2807. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2808. return qm;
  2809. }
  2810. /**
  2811. * Spline from Tween.js, slightly optimized (and trashed)
  2812. * http://sole.github.com/tween.js/examples/05_spline.html
  2813. *
  2814. * @author mrdoob / http://mrdoob.com/
  2815. * @author alteredq / http://alteredqualia.com/
  2816. */
  2817. THREE.Spline = function ( points ) {
  2818. this.points = points;
  2819. var c = [], v3 = { x: 0, y: 0, z: 0 },
  2820. point, intPoint, weight, w2, w3,
  2821. pa, pb, pc, pd;
  2822. this.initFromArray = function( a ) {
  2823. this.points = [];
  2824. for ( var i = 0; i < a.length; i++ ) {
  2825. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  2826. }
  2827. };
  2828. this.getPoint = function ( k ) {
  2829. point = ( this.points.length - 1 ) * k;
  2830. intPoint = Math.floor( point );
  2831. weight = point - intPoint;
  2832. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  2833. c[ 1 ] = intPoint;
  2834. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  2835. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  2836. pa = this.points[ c[ 0 ] ];
  2837. pb = this.points[ c[ 1 ] ];
  2838. pc = this.points[ c[ 2 ] ];
  2839. pd = this.points[ c[ 3 ] ];
  2840. w2 = weight * weight;
  2841. w3 = weight * w2;
  2842. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  2843. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  2844. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  2845. return v3;
  2846. };
  2847. this.getControlPointsArray = function () {
  2848. var i, p, l = this.points.length,
  2849. coords = [];
  2850. for ( i = 0; i < l; i ++ ) {
  2851. p = this.points[ i ];
  2852. coords[ i ] = [ p.x, p.y, p.z ];
  2853. }
  2854. return coords;
  2855. };
  2856. // approximate length by summing linear segments
  2857. this.getLength = function ( nSubDivisions ) {
  2858. var i, index, nSamples, position,
  2859. point = 0, intPoint = 0, oldIntPoint = 0,
  2860. oldPosition = new THREE.Vector3(),
  2861. tmpVec = new THREE.Vector3(),
  2862. chunkLengths = [],
  2863. totalLength = 0;
  2864. // first point has 0 length
  2865. chunkLengths[ 0 ] = 0;
  2866. if ( !nSubDivisions ) nSubDivisions = 100;
  2867. nSamples = this.points.length * nSubDivisions;
  2868. oldPosition.copy( this.points[ 0 ] );
  2869. for ( i = 1; i < nSamples; i ++ ) {
  2870. index = i / nSamples;
  2871. position = this.getPoint( index );
  2872. tmpVec.copy( position );
  2873. totalLength += tmpVec.distanceTo( oldPosition );
  2874. oldPosition.copy( position );
  2875. point = ( this.points.length - 1 ) * index;
  2876. intPoint = Math.floor( point );
  2877. if ( intPoint != oldIntPoint ) {
  2878. chunkLengths[ intPoint ] = totalLength;
  2879. oldIntPoint = intPoint;
  2880. }
  2881. }
  2882. // last point ends with total length
  2883. chunkLengths[ chunkLengths.length ] = totalLength;
  2884. return { chunks: chunkLengths, total: totalLength };
  2885. };
  2886. this.reparametrizeByArcLength = function ( samplingCoef ) {
  2887. var i, j,
  2888. index, indexCurrent, indexNext,
  2889. linearDistance, realDistance,
  2890. sampling, position,
  2891. newpoints = [],
  2892. tmpVec = new THREE.Vector3(),
  2893. sl = this.getLength();
  2894. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  2895. for ( i = 1; i < this.points.length; i++ ) {
  2896. //tmpVec.copy( this.points[ i - 1 ] );
  2897. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  2898. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  2899. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  2900. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  2901. indexNext = i / ( this.points.length - 1 );
  2902. for ( j = 1; j < sampling - 1; j++ ) {
  2903. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  2904. position = this.getPoint( index );
  2905. newpoints.push( tmpVec.copy( position ).clone() );
  2906. }
  2907. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  2908. }
  2909. this.points = newpoints;
  2910. };
  2911. // Catmull-Rom
  2912. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  2913. var v0 = ( p2 - p0 ) * 0.5,
  2914. v1 = ( p3 - p1 ) * 0.5;
  2915. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  2916. };
  2917. };
  2918. /**
  2919. * @author bhouston / http://exocortex.com
  2920. * @author mrdoob / http://mrdoob.com/
  2921. */
  2922. THREE.Triangle = function ( a, b, c ) {
  2923. this.a = new THREE.Vector3();
  2924. this.b = new THREE.Vector3();
  2925. this.c = new THREE.Vector3();
  2926. if( a !== undefined && b !== undefined && c !== undefined ) {
  2927. this.a.copy( a );
  2928. this.b.copy( b );
  2929. this.c.copy( c );
  2930. }
  2931. };
  2932. THREE.Triangle.normal = function( a, b, c, optionalTarget ) {
  2933. var result = optionalTarget || new THREE.Vector3();
  2934. result.sub( c, b );
  2935. THREE.Triangle.__v0.sub( a, b );
  2936. result.crossSelf( THREE.Triangle.__v0 );
  2937. var resultLengthSq = result.lengthSq();
  2938. if( resultLengthSq > 0 ) {
  2939. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  2940. }
  2941. return result.set( 0, 0, 0 );
  2942. };
  2943. // static/instance method to calculate barycoordinates
  2944. THREE.Triangle.barycoordFromPoint = function ( point, a, b, c, optionalTarget ) {
  2945. THREE.Triangle.__v0.sub( c, a );
  2946. THREE.Triangle.__v1.sub( b, a );
  2947. THREE.Triangle.__v2.sub( point, a );
  2948. var dot00 = THREE.Triangle.__v0.dot( THREE.Triangle.__v0 );
  2949. var dot01 = THREE.Triangle.__v0.dot( THREE.Triangle.__v1 );
  2950. var dot02 = THREE.Triangle.__v0.dot( THREE.Triangle.__v2 );
  2951. var dot11 = THREE.Triangle.__v1.dot( THREE.Triangle.__v1 );
  2952. var dot12 = THREE.Triangle.__v1.dot( THREE.Triangle.__v2 );
  2953. var denom = ( dot00 * dot11 - dot01 * dot01 );
  2954. var result = optionalTarget || new THREE.Vector3();
  2955. // colinear or singular triangle
  2956. if( denom == 0 ) {
  2957. // arbitrary location outside of triangle?
  2958. // not sure if this is the best idea, maybe should be returning undefined
  2959. return result.set( -2, -1, -1 );
  2960. }
  2961. var invDenom = 1 / denom;
  2962. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  2963. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  2964. // barycoordinates must always sum to 1
  2965. return result.set( 1 - u - v, v, u );
  2966. };
  2967. THREE.Triangle.containsPoint = function ( point, a, b, c ) {
  2968. // NOTE: need to use __v3 here because __v0, __v1 and __v2 are used in barycoordFromPoint.
  2969. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, THREE.Triangle.__v3 );
  2970. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  2971. };
  2972. THREE.Triangle.prototype = {
  2973. constructor: THREE.Triangle,
  2974. set: function ( a, b, c ) {
  2975. this.a.copy( a );
  2976. this.b.copy( b );
  2977. this.c.copy( c );
  2978. return this;
  2979. },
  2980. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  2981. this.a.copy( points[i0] );
  2982. this.b.copy( points[i1] );
  2983. this.c.copy( points[i2] );
  2984. return this;
  2985. },
  2986. copy: function ( triangle ) {
  2987. this.a.copy( triangle.a );
  2988. this.b.copy( triangle.b );
  2989. this.c.copy( triangle.c );
  2990. return this;
  2991. },
  2992. area: function () {
  2993. THREE.Triangle.__v0.sub( this.c, this.b );
  2994. THREE.Triangle.__v1.sub( this.a, this.b );
  2995. return THREE.Triangle.__v0.crossSelf( THREE.Triangle.__v1 ).length() * 0.5;
  2996. },
  2997. midpoint: function ( optionalTarget ) {
  2998. var result = optionalTarget || new THREE.Vector3();
  2999. return result.add( this.a, this.b ).addSelf( this.c ).multiplyScalar( 1 / 3 );
  3000. },
  3001. normal: function ( optionalTarget ) {
  3002. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3003. },
  3004. plane: function ( optionalTarget ) {
  3005. var result = optionalTarget || new THREE.Plane();
  3006. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3007. },
  3008. barycoordFromPoint: function ( point, optionalTarget ) {
  3009. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3010. },
  3011. containsPoint: function ( point ) {
  3012. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3013. },
  3014. equals: function ( triangle ) {
  3015. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3016. },
  3017. clone: function () {
  3018. return new THREE.Triangle().copy( this );
  3019. }
  3020. };
  3021. THREE.Triangle.__v0 = new THREE.Vector3();
  3022. THREE.Triangle.__v1 = new THREE.Vector3();
  3023. THREE.Triangle.__v2 = new THREE.Vector3();
  3024. THREE.Triangle.__v3 = new THREE.Vector3();
  3025. /**
  3026. * @author mrdoob / http://mrdoob.com/
  3027. */
  3028. THREE.Vertex = function ( v ) {
  3029. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3030. return v;
  3031. };
  3032. /**
  3033. * @author mrdoob / http://mrdoob.com/
  3034. */
  3035. THREE.UV = function ( u, v ) {
  3036. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3037. return new THREE.Vector2( u, v );
  3038. };
  3039. /**
  3040. * @author alteredq / http://alteredqualia.com/
  3041. */
  3042. THREE.Clock = function ( autoStart ) {
  3043. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3044. this.startTime = 0;
  3045. this.oldTime = 0;
  3046. this.elapsedTime = 0;
  3047. this.running = false;
  3048. };
  3049. THREE.Clock.prototype.start = function () {
  3050. this.startTime = Date.now();
  3051. this.oldTime = this.startTime;
  3052. this.running = true;
  3053. };
  3054. THREE.Clock.prototype.stop = function () {
  3055. this.getElapsedTime();
  3056. this.running = false;
  3057. };
  3058. THREE.Clock.prototype.getElapsedTime = function () {
  3059. this.getDelta();
  3060. return this.elapsedTime;
  3061. };
  3062. THREE.Clock.prototype.getDelta = function () {
  3063. var diff = 0;
  3064. if ( this.autoStart && ! this.running ) {
  3065. this.start();
  3066. }
  3067. if ( this.running ) {
  3068. var newTime = Date.now();
  3069. diff = 0.001 * ( newTime - this.oldTime );
  3070. this.oldTime = newTime;
  3071. this.elapsedTime += diff;
  3072. }
  3073. return diff;
  3074. };/**
  3075. * https://github.com/mrdoob/eventtarget.js/
  3076. */
  3077. THREE.EventTarget = function () {
  3078. var listeners = {};
  3079. this.addEventListener = function ( type, listener ) {
  3080. if ( listeners[ type ] === undefined ) {
  3081. listeners[ type ] = [];
  3082. }
  3083. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3084. listeners[ type ].push( listener );
  3085. }
  3086. };
  3087. this.dispatchEvent = function ( event ) {
  3088. var listenerArray = listeners[ event.type ];
  3089. if ( listenerArray !== undefined ) {
  3090. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3091. listenerArray[ i ]( event );
  3092. }
  3093. }
  3094. };
  3095. this.removeEventListener = function ( type, listener ) {
  3096. var index = listeners[ type ].indexOf( listener );
  3097. if ( index !== - 1 ) {
  3098. listeners[ type ].splice( index, 1 );
  3099. }
  3100. };
  3101. };
  3102. /**
  3103. * @author mrdoob / http://mrdoob.com/
  3104. * @author bhouston / http://exocortex.com/
  3105. */
  3106. ( function ( THREE ) {
  3107. THREE.Raycaster = function ( origin, direction, near, far ) {
  3108. this.ray = new THREE.Ray( origin, direction );
  3109. // normalized ray.direction required for accurate distance calculations
  3110. if( this.ray.direction.length() > 0 ) {
  3111. this.ray.direction.normalize();
  3112. }
  3113. this.near = near || 0;
  3114. this.far = far || Infinity;
  3115. };
  3116. var sphere = new THREE.Sphere();
  3117. var localRay = new THREE.Ray();
  3118. var facePlane = new THREE.Plane();
  3119. var intersectPoint = new THREE.Vector3();
  3120. var inverseMatrix = new THREE.Matrix4();
  3121. var descSort = function ( a, b ) {
  3122. return a.distance - b.distance;
  3123. };
  3124. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  3125. // http://www.blackpawn.com/texts/pointinpoly/default.html
  3126. var intersectObject = function ( object, raycaster, intersects ) {
  3127. if ( object instanceof THREE.Particle ) {
  3128. var distance = raycaster.ray.distanceToPoint( object.matrixWorld.getPosition() );
  3129. if ( distance > object.scale.x ) {
  3130. return intersects;
  3131. }
  3132. intersects.push( {
  3133. distance: distance,
  3134. point: object.position,
  3135. face: null,
  3136. object: object
  3137. } );
  3138. } else if ( object instanceof THREE.Mesh ) {
  3139. // Checking boundingSphere distance to ray
  3140. sphere.set(
  3141. object.matrixWorld.getPosition(),
  3142. object.geometry.boundingSphere.radius* object.matrixWorld.getMaxScaleOnAxis() );
  3143. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3144. return intersects;
  3145. }
  3146. // Checking faces
  3147. var geometry = object.geometry;
  3148. var vertices = geometry.vertices;
  3149. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3150. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3151. var side = object.material.side;
  3152. var a, b, c, d;
  3153. var precision = raycaster.precision;
  3154. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3155. inverseMatrix.getInverse( object.matrixWorld );
  3156. localRay.copy( raycaster.ray ).transformSelf( inverseMatrix );
  3157. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3158. var face = geometry.faces[ f ];
  3159. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3160. if ( material === undefined ) continue;
  3161. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3162. var planeDistance = localRay.distanceToPlane( facePlane );
  3163. // bail if raycaster and plane are parallel
  3164. if ( Math.abs( planeDistance ) < precision ) continue;
  3165. // if negative distance, then plane is behind raycaster
  3166. if ( planeDistance < 0 ) continue;
  3167. // check if we hit the wrong side of a single sided face
  3168. side = material.side;
  3169. if( side !== THREE.DoubleSide ) {
  3170. var planeSign = localRay.direction.dot( facePlane.normal );
  3171. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3172. }
  3173. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3174. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3175. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3176. if ( face instanceof THREE.Face3 ) {
  3177. a = vertices[ face.a ];
  3178. b = vertices[ face.b ];
  3179. c = vertices[ face.c ];
  3180. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3181. } else if ( face instanceof THREE.Face4 ) {
  3182. a = vertices[ face.a ];
  3183. b = vertices[ face.b ];
  3184. c = vertices[ face.c ];
  3185. d = vertices[ face.d ];
  3186. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3187. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3188. } else {
  3189. // This is added because if we call out of this if/else group when none of the cases
  3190. // match it will add a point to the intersection list erroneously.
  3191. throw Error( "face type not supported" );
  3192. }
  3193. intersects.push( {
  3194. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3195. point: raycaster.ray.at( planeDistance ),
  3196. face: face,
  3197. faceIndex: f,
  3198. object: object
  3199. } );
  3200. }
  3201. }
  3202. };
  3203. var intersectDescendants = function ( object, raycaster, intersects ) {
  3204. var descendants = object.getDescendants();
  3205. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3206. intersectObject( descendants[ i ], raycaster, intersects );
  3207. }
  3208. };
  3209. //
  3210. THREE.Raycaster.prototype.precision = 0.0001;
  3211. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3212. this.ray.set( origin, direction );
  3213. // normalized ray.direction required for accurate distance calculations
  3214. if( this.ray.direction.length() > 0 ) {
  3215. this.ray.direction.normalize();
  3216. }
  3217. };
  3218. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3219. var intersects = [];
  3220. if ( recursive === true ) {
  3221. intersectDescendants( object, this, intersects );
  3222. }
  3223. intersectObject( object, this, intersects );
  3224. intersects.sort( descSort );
  3225. return intersects;
  3226. };
  3227. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3228. var intersects = [];
  3229. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3230. intersectObject( objects[ i ], this, intersects );
  3231. if ( recursive === true ) {
  3232. intersectDescendants( objects[ i ], this, intersects );
  3233. }
  3234. }
  3235. intersects.sort( descSort );
  3236. return intersects;
  3237. };
  3238. }( THREE ) );
  3239. /**
  3240. * @author mrdoob / http://mrdoob.com/
  3241. * @author mikael emtinger / http://gomo.se/
  3242. * @author alteredq / http://alteredqualia.com/
  3243. */
  3244. THREE.Object3D = function () {
  3245. this.id = THREE.Object3DIdCount ++;
  3246. this.name = '';
  3247. this.properties = {};
  3248. this.parent = undefined;
  3249. this.children = [];
  3250. this.up = new THREE.Vector3( 0, 1, 0 );
  3251. this.position = new THREE.Vector3();
  3252. this.rotation = new THREE.Vector3();
  3253. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3254. this.scale = new THREE.Vector3( 1, 1, 1 );
  3255. this.renderDepth = null;
  3256. this.rotationAutoUpdate = true;
  3257. this.matrix = new THREE.Matrix4();
  3258. this.matrixWorld = new THREE.Matrix4();
  3259. this.matrixRotationWorld = new THREE.Matrix4();
  3260. this.matrixAutoUpdate = true;
  3261. this.matrixWorldNeedsUpdate = true;
  3262. this.quaternion = new THREE.Quaternion();
  3263. this.useQuaternion = false;
  3264. this.visible = true;
  3265. this.castShadow = false;
  3266. this.receiveShadow = false;
  3267. this.frustumCulled = true;
  3268. this._vector = new THREE.Vector3();
  3269. };
  3270. THREE.Object3D.prototype = {
  3271. constructor: THREE.Object3D,
  3272. applyMatrix: function ( matrix ) {
  3273. this.matrix.multiply( matrix, this.matrix );
  3274. this.scale.getScaleFromMatrix( this.matrix );
  3275. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  3276. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  3277. this.position.getPositionFromMatrix( this.matrix );
  3278. },
  3279. translate: function ( distance, axis ) {
  3280. this.matrix.rotateAxis( axis );
  3281. this.position.addSelf( axis.multiplyScalar( distance ) );
  3282. },
  3283. translateX: function ( distance ) {
  3284. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  3285. },
  3286. translateY: function ( distance ) {
  3287. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  3288. },
  3289. translateZ: function ( distance ) {
  3290. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  3291. },
  3292. localToWorld: function ( vector ) {
  3293. return this.matrixWorld.multiplyVector3( vector );
  3294. },
  3295. worldToLocal: function ( vector ) {
  3296. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  3297. },
  3298. lookAt: function ( vector ) {
  3299. // TODO: Add hierarchy support.
  3300. this.matrix.lookAt( vector, this.position, this.up );
  3301. if ( this.rotationAutoUpdate ) {
  3302. if ( this.useQuaternion === false ) {
  3303. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3304. } else {
  3305. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3306. }
  3307. }
  3308. },
  3309. add: function ( object ) {
  3310. if ( object === this ) {
  3311. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3312. return;
  3313. }
  3314. if ( object instanceof THREE.Object3D ) {
  3315. if ( object.parent !== undefined ) {
  3316. object.parent.remove( object );
  3317. }
  3318. object.parent = this;
  3319. this.children.push( object );
  3320. // add to scene
  3321. var scene = this;
  3322. while ( scene.parent !== undefined ) {
  3323. scene = scene.parent;
  3324. }
  3325. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3326. scene.__addObject( object );
  3327. }
  3328. }
  3329. },
  3330. remove: function ( object ) {
  3331. var index = this.children.indexOf( object );
  3332. if ( index !== - 1 ) {
  3333. object.parent = undefined;
  3334. this.children.splice( index, 1 );
  3335. // remove from scene
  3336. var scene = this;
  3337. while ( scene.parent !== undefined ) {
  3338. scene = scene.parent;
  3339. }
  3340. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3341. scene.__removeObject( object );
  3342. }
  3343. }
  3344. },
  3345. traverse: function ( callback ) {
  3346. callback( this );
  3347. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3348. this.children[ i ].traverse( callback );
  3349. }
  3350. },
  3351. getChildByName: function ( name, recursive ) {
  3352. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3353. var child = this.children[ i ];
  3354. if ( child.name === name ) {
  3355. return child;
  3356. }
  3357. if ( recursive === true ) {
  3358. child = child.getChildByName( name, recursive );
  3359. if ( child !== undefined ) {
  3360. return child;
  3361. }
  3362. }
  3363. }
  3364. return undefined;
  3365. },
  3366. getDescendants: function ( array ) {
  3367. if ( array === undefined ) array = [];
  3368. Array.prototype.push.apply( array, this.children );
  3369. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3370. this.children[ i ].getDescendants( array );
  3371. }
  3372. return array;
  3373. },
  3374. updateMatrix: function () {
  3375. this.matrix.setPosition( this.position );
  3376. if ( this.useQuaternion === false ) {
  3377. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3378. } else {
  3379. this.matrix.setRotationFromQuaternion( this.quaternion );
  3380. }
  3381. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3382. this.matrix.scale( this.scale );
  3383. }
  3384. this.matrixWorldNeedsUpdate = true;
  3385. },
  3386. updateMatrixWorld: function ( force ) {
  3387. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3388. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3389. if ( this.parent === undefined ) {
  3390. this.matrixWorld.copy( this.matrix );
  3391. } else {
  3392. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  3393. }
  3394. this.matrixWorldNeedsUpdate = false;
  3395. force = true;
  3396. }
  3397. // update children
  3398. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3399. this.children[ i ].updateMatrixWorld( force );
  3400. }
  3401. },
  3402. clone: function ( object ) {
  3403. if ( object === undefined ) object = new THREE.Object3D();
  3404. object.name = this.name;
  3405. object.up.copy( this.up );
  3406. object.position.copy( this.position );
  3407. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3408. object.eulerOrder = this.eulerOrder;
  3409. object.scale.copy( this.scale );
  3410. object.renderDepth = this.renderDepth;
  3411. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3412. object.matrix.copy( this.matrix );
  3413. object.matrixWorld.copy( this.matrixWorld );
  3414. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3415. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3416. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3417. object.quaternion.copy( this.quaternion );
  3418. object.useQuaternion = this.useQuaternion;
  3419. object.visible = this.visible;
  3420. object.castShadow = this.castShadow;
  3421. object.receiveShadow = this.receiveShadow;
  3422. object.frustumCulled = this.frustumCulled;
  3423. for ( var i = 0; i < this.children.length; i ++ ) {
  3424. var child = this.children[ i ];
  3425. object.add( child.clone() );
  3426. }
  3427. return object;
  3428. }
  3429. };
  3430. THREE.Object3D.__m1 = new THREE.Matrix4();
  3431. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3432. THREE.Object3DIdCount = 0;
  3433. /**
  3434. * @author mrdoob / http://mrdoob.com/
  3435. * @author supereggbert / http://www.paulbrunt.co.uk/
  3436. * @author julianwa / https://github.com/julianwa
  3437. */
  3438. THREE.Projector = function() {
  3439. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3440. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3441. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3442. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3443. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3444. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3445. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3446. _vector3 = new THREE.Vector3(),
  3447. _vector4 = new THREE.Vector4(),
  3448. _viewProjectionMatrix = new THREE.Matrix4(),
  3449. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3450. _normalMatrix = new THREE.Matrix3(),
  3451. _frustum = new THREE.Frustum(),
  3452. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3453. _clippedVertex2PositionScreen = new THREE.Vector4(),
  3454. _face3VertexNormals;
  3455. this.projectVector = function ( vector, camera ) {
  3456. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3457. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  3458. _viewProjectionMatrix.multiplyVector3( vector );
  3459. return vector;
  3460. };
  3461. this.unprojectVector = function ( vector, camera ) {
  3462. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3463. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  3464. _viewProjectionMatrix.multiplyVector3( vector );
  3465. return vector;
  3466. };
  3467. this.pickingRay = function ( vector, camera ) {
  3468. // set two vectors with opposing z values
  3469. vector.z = -1.0;
  3470. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3471. this.unprojectVector( vector, camera );
  3472. this.unprojectVector( end, camera );
  3473. // find direction from vector to end
  3474. end.subSelf( vector ).normalize();
  3475. return new THREE.Raycaster( vector, end );
  3476. };
  3477. var projectGraph = function ( root, sortObjects ) {
  3478. _objectCount = 0;
  3479. _renderData.objects.length = 0;
  3480. _renderData.sprites.length = 0;
  3481. _renderData.lights.length = 0;
  3482. var projectObject = function ( parent ) {
  3483. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3484. var object = parent.children[ c ];
  3485. if ( object.visible === false ) continue;
  3486. if ( object instanceof THREE.Light ) {
  3487. _renderData.lights.push( object );
  3488. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3489. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  3490. _object = getNextObjectInPool();
  3491. _object.object = object;
  3492. if ( object.renderDepth !== null ) {
  3493. _object.z = object.renderDepth;
  3494. } else {
  3495. _vector3.copy( object.matrixWorld.getPosition() );
  3496. _viewProjectionMatrix.multiplyVector3( _vector3 );
  3497. _object.z = _vector3.z;
  3498. }
  3499. _renderData.objects.push( _object );
  3500. }
  3501. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3502. _object = getNextObjectInPool();
  3503. _object.object = object;
  3504. // TODO: Find an elegant and performant solution and remove this dupe code.
  3505. if ( object.renderDepth !== null ) {
  3506. _object.z = object.renderDepth;
  3507. } else {
  3508. _vector3.copy( object.matrixWorld.getPosition() );
  3509. _viewProjectionMatrix.multiplyVector3( _vector3 );
  3510. _object.z = _vector3.z;
  3511. }
  3512. _renderData.sprites.push( _object );
  3513. } else {
  3514. _object = getNextObjectInPool();
  3515. _object.object = object;
  3516. if ( object.renderDepth !== null ) {
  3517. _object.z = object.renderDepth;
  3518. } else {
  3519. _vector3.copy( object.matrixWorld.getPosition() );
  3520. _viewProjectionMatrix.multiplyVector3( _vector3 );
  3521. _object.z = _vector3.z;
  3522. }
  3523. _renderData.objects.push( _object );
  3524. }
  3525. projectObject( object );
  3526. }
  3527. };
  3528. projectObject( root );
  3529. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3530. return _renderData;
  3531. };
  3532. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3533. var near = camera.near, far = camera.far, visible = false,
  3534. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object, modelMatrix,
  3535. geometry, vertices, vertex, vertexPositionScreen,
  3536. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  3537. v1, v2, v3, v4, isFaceMaterial, objectMaterials, material, side;
  3538. _face3Count = 0;
  3539. _face4Count = 0;
  3540. _lineCount = 0;
  3541. _particleCount = 0;
  3542. _renderData.elements.length = 0;
  3543. scene.updateMatrixWorld();
  3544. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3545. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3546. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  3547. _frustum.setFromMatrix( _viewProjectionMatrix );
  3548. _renderData = projectGraph( scene, sortObjects );
  3549. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3550. object = _renderData.objects[ o ].object;
  3551. modelMatrix = object.matrixWorld;
  3552. _vertexCount = 0;
  3553. if ( object instanceof THREE.Mesh ) {
  3554. geometry = object.geometry;
  3555. vertices = geometry.vertices;
  3556. faces = geometry.faces;
  3557. faceVertexUvs = geometry.faceVertexUvs;
  3558. _normalMatrix.getInverse( modelMatrix );
  3559. _normalMatrix.transpose();
  3560. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3561. objectMaterials = isFaceMaterial === true ? object.material : null;
  3562. side = object.material.side;
  3563. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  3564. _vertex = getNextVertexInPool();
  3565. _vertex.positionWorld.copy( vertices[ v ] );
  3566. modelMatrix.multiplyVector3( _vertex.positionWorld );
  3567. _vertex.positionScreen.copy( _vertex.positionWorld );
  3568. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  3569. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  3570. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  3571. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  3572. }
  3573. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  3574. face = faces[ f ];
  3575. material = isFaceMaterial === true ? objectMaterials.materials[ face.materialIndex ] : object.material;
  3576. if ( material === undefined ) continue;
  3577. side = material.side;
  3578. if ( face instanceof THREE.Face3 ) {
  3579. v1 = _vertexPool[ face.a ];
  3580. v2 = _vertexPool[ face.b ];
  3581. v3 = _vertexPool[ face.c ];
  3582. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  3583. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3584. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  3585. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3586. _face = getNextFace3InPool();
  3587. _face.v1.copy( v1 );
  3588. _face.v2.copy( v2 );
  3589. _face.v3.copy( v3 );
  3590. } else {
  3591. continue;
  3592. }
  3593. } else {
  3594. continue;
  3595. }
  3596. } else if ( face instanceof THREE.Face4 ) {
  3597. v1 = _vertexPool[ face.a ];
  3598. v2 = _vertexPool[ face.b ];
  3599. v3 = _vertexPool[ face.c ];
  3600. v4 = _vertexPool[ face.d ];
  3601. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  3602. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3603. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  3604. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  3605. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  3606. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3607. _face = getNextFace4InPool();
  3608. _face.v1.copy( v1 );
  3609. _face.v2.copy( v2 );
  3610. _face.v3.copy( v3 );
  3611. _face.v4.copy( v4 );
  3612. } else {
  3613. continue;
  3614. }
  3615. } else {
  3616. continue;
  3617. }
  3618. }
  3619. _face.normalWorld.copy( face.normal );
  3620. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  3621. _normalMatrix.multiplyVector3( _face.normalWorld ).normalize();
  3622. _face.centroidWorld.copy( face.centroid );
  3623. modelMatrix.multiplyVector3( _face.centroidWorld );
  3624. _face.centroidScreen.copy( _face.centroidWorld );
  3625. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  3626. faceVertexNormals = face.vertexNormals;
  3627. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  3628. normal = _face.vertexNormalsWorld[ n ];
  3629. normal.copy( faceVertexNormals[ n ] );
  3630. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  3631. _normalMatrix.multiplyVector3( normal ).normalize();
  3632. }
  3633. _face.vertexNormalsLength = faceVertexNormals.length;
  3634. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  3635. uvs = faceVertexUvs[ c ][ f ];
  3636. if ( uvs === undefined ) continue;
  3637. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  3638. _face.uvs[ c ][ u ] = uvs[ u ];
  3639. }
  3640. }
  3641. _face.color = face.color;
  3642. _face.material = material;
  3643. _face.z = _face.centroidScreen.z;
  3644. _renderData.elements.push( _face );
  3645. }
  3646. } else if ( object instanceof THREE.Line ) {
  3647. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  3648. vertices = object.geometry.vertices;
  3649. v1 = getNextVertexInPool();
  3650. v1.positionScreen.copy( vertices[ 0 ] );
  3651. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  3652. // Handle LineStrip and LinePieces
  3653. var step = object.type === THREE.LinePieces ? 2 : 1;
  3654. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  3655. v1 = getNextVertexInPool();
  3656. v1.positionScreen.copy( vertices[ v ] );
  3657. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  3658. if ( ( v + 1 ) % step > 0 ) continue;
  3659. v2 = _vertexPool[ _vertexCount - 2 ];
  3660. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  3661. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  3662. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  3663. // Perform the perspective divide
  3664. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  3665. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  3666. _line = getNextLineInPool();
  3667. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  3668. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  3669. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  3670. _line.material = object.material;
  3671. _renderData.elements.push( _line );
  3672. }
  3673. }
  3674. }
  3675. }
  3676. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  3677. object = _renderData.sprites[ o ].object;
  3678. modelMatrix = object.matrixWorld;
  3679. if ( object instanceof THREE.Particle ) {
  3680. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  3681. _viewProjectionMatrix.multiplyVector4( _vector4 );
  3682. _vector4.z /= _vector4.w;
  3683. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  3684. _particle = getNextParticleInPool();
  3685. _particle.object = object;
  3686. _particle.x = _vector4.x / _vector4.w;
  3687. _particle.y = _vector4.y / _vector4.w;
  3688. _particle.z = _vector4.z;
  3689. _particle.rotation = object.rotation.z;
  3690. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  3691. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  3692. _particle.material = object.material;
  3693. _renderData.elements.push( _particle );
  3694. }
  3695. }
  3696. }
  3697. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  3698. return _renderData;
  3699. };
  3700. // Pools
  3701. function getNextObjectInPool() {
  3702. if ( _objectCount === _objectPoolLength ) {
  3703. var object = new THREE.RenderableObject();
  3704. _objectPool.push( object );
  3705. _objectPoolLength ++;
  3706. _objectCount ++;
  3707. return object;
  3708. }
  3709. return _objectPool[ _objectCount ++ ];
  3710. }
  3711. function getNextVertexInPool() {
  3712. if ( _vertexCount === _vertexPoolLength ) {
  3713. var vertex = new THREE.RenderableVertex();
  3714. _vertexPool.push( vertex );
  3715. _vertexPoolLength ++;
  3716. _vertexCount ++;
  3717. return vertex;
  3718. }
  3719. return _vertexPool[ _vertexCount ++ ];
  3720. }
  3721. function getNextFace3InPool() {
  3722. if ( _face3Count === _face3PoolLength ) {
  3723. var face = new THREE.RenderableFace3();
  3724. _face3Pool.push( face );
  3725. _face3PoolLength ++;
  3726. _face3Count ++;
  3727. return face;
  3728. }
  3729. return _face3Pool[ _face3Count ++ ];
  3730. }
  3731. function getNextFace4InPool() {
  3732. if ( _face4Count === _face4PoolLength ) {
  3733. var face = new THREE.RenderableFace4();
  3734. _face4Pool.push( face );
  3735. _face4PoolLength ++;
  3736. _face4Count ++;
  3737. return face;
  3738. }
  3739. return _face4Pool[ _face4Count ++ ];
  3740. }
  3741. function getNextLineInPool() {
  3742. if ( _lineCount === _linePoolLength ) {
  3743. var line = new THREE.RenderableLine();
  3744. _linePool.push( line );
  3745. _linePoolLength ++;
  3746. _lineCount ++
  3747. return line;
  3748. }
  3749. return _linePool[ _lineCount ++ ];
  3750. }
  3751. function getNextParticleInPool() {
  3752. if ( _particleCount === _particlePoolLength ) {
  3753. var particle = new THREE.RenderableParticle();
  3754. _particlePool.push( particle );
  3755. _particlePoolLength ++;
  3756. _particleCount ++
  3757. return particle;
  3758. }
  3759. return _particlePool[ _particleCount ++ ];
  3760. }
  3761. //
  3762. function painterSort( a, b ) {
  3763. return b.z - a.z;
  3764. }
  3765. function clipLine( s1, s2 ) {
  3766. var alpha1 = 0, alpha2 = 1,
  3767. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  3768. // Z = -1 and Z = +1, respectively.
  3769. bc1near = s1.z + s1.w,
  3770. bc2near = s2.z + s2.w,
  3771. bc1far = - s1.z + s1.w,
  3772. bc2far = - s2.z + s2.w;
  3773. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  3774. // Both vertices lie entirely within all clip planes.
  3775. return true;
  3776. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  3777. // Both vertices lie entirely outside one of the clip planes.
  3778. return false;
  3779. } else {
  3780. // The line segment spans at least one clip plane.
  3781. if ( bc1near < 0 ) {
  3782. // v1 lies outside the near plane, v2 inside
  3783. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  3784. } else if ( bc2near < 0 ) {
  3785. // v2 lies outside the near plane, v1 inside
  3786. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  3787. }
  3788. if ( bc1far < 0 ) {
  3789. // v1 lies outside the far plane, v2 inside
  3790. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  3791. } else if ( bc2far < 0 ) {
  3792. // v2 lies outside the far plane, v2 inside
  3793. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  3794. }
  3795. if ( alpha2 < alpha1 ) {
  3796. // The line segment spans two boundaries, but is outside both of them.
  3797. // (This can't happen when we're only clipping against just near/far but good
  3798. // to leave the check here for future usage if other clip planes are added.)
  3799. return false;
  3800. } else {
  3801. // Update the s1 and s2 vertices to match the clipped line segment.
  3802. s1.lerpSelf( s2, alpha1 );
  3803. s2.lerpSelf( s1, 1 - alpha2 );
  3804. return true;
  3805. }
  3806. }
  3807. }
  3808. };
  3809. /**
  3810. * @author mrdoob / http://mrdoob.com/
  3811. * @author alteredq / http://alteredqualia.com/
  3812. */
  3813. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  3814. this.a = a;
  3815. this.b = b;
  3816. this.c = c;
  3817. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  3818. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3819. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3820. this.vertexColors = color instanceof Array ? color : [];
  3821. this.vertexTangents = [];
  3822. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  3823. this.centroid = new THREE.Vector3();
  3824. };
  3825. THREE.Face3.prototype = {
  3826. constructor: THREE.Face3,
  3827. clone: function () {
  3828. var face = new THREE.Face3( this.a, this.b, this.c );
  3829. face.normal.copy( this.normal );
  3830. face.color.copy( this.color );
  3831. face.centroid.copy( this.centroid );
  3832. face.materialIndex = this.materialIndex;
  3833. var i, il;
  3834. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3835. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3836. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3837. return face;
  3838. }
  3839. };
  3840. /**
  3841. * @author mrdoob / http://mrdoob.com/
  3842. * @author alteredq / http://alteredqualia.com/
  3843. */
  3844. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  3845. this.a = a;
  3846. this.b = b;
  3847. this.c = c;
  3848. this.d = d;
  3849. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  3850. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3851. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3852. this.vertexColors = color instanceof Array ? color : [];
  3853. this.vertexTangents = [];
  3854. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  3855. this.centroid = new THREE.Vector3();
  3856. };
  3857. THREE.Face4.prototype = {
  3858. constructor: THREE.Face4,
  3859. clone: function () {
  3860. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  3861. face.normal.copy( this.normal );
  3862. face.color.copy( this.color );
  3863. face.centroid.copy( this.centroid );
  3864. face.materialIndex = this.materialIndex;
  3865. var i, il;
  3866. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3867. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3868. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3869. return face;
  3870. }
  3871. };
  3872. /**
  3873. * @author mrdoob / http://mrdoob.com/
  3874. * @author kile / http://kile.stravaganza.org/
  3875. * @author alteredq / http://alteredqualia.com/
  3876. * @author mikael emtinger / http://gomo.se/
  3877. * @author zz85 / http://www.lab4games.net/zz85/blog
  3878. * @author bhouston / http://exocortex.com
  3879. */
  3880. THREE.Geometry = function () {
  3881. this.id = THREE.GeometryIdCount ++;
  3882. this.name = '';
  3883. this.vertices = [];
  3884. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  3885. this.normals = []; // one-to-one vertex normals, used in Ribbon
  3886. this.faces = [];
  3887. this.faceUvs = [[]];
  3888. this.faceVertexUvs = [[]];
  3889. this.morphTargets = [];
  3890. this.morphColors = [];
  3891. this.morphNormals = [];
  3892. this.skinWeights = [];
  3893. this.skinIndices = [];
  3894. this.lineDistances = [];
  3895. this.boundingBox = null;
  3896. this.boundingSphere = null;
  3897. this.hasTangents = false;
  3898. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  3899. // update flags
  3900. this.verticesNeedUpdate = false;
  3901. this.elementsNeedUpdate = false;
  3902. this.uvsNeedUpdate = false;
  3903. this.normalsNeedUpdate = false;
  3904. this.tangentsNeedUpdate = false;
  3905. this.colorsNeedUpdate = false;
  3906. this.lineDistancesNeedUpdate = false;
  3907. this.buffersNeedUpdate = false;
  3908. };
  3909. THREE.Geometry.prototype = {
  3910. constructor: THREE.Geometry,
  3911. applyMatrix: function ( matrix ) {
  3912. var normalMatrix = new THREE.Matrix3();
  3913. normalMatrix.getInverse( matrix ).transpose();
  3914. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3915. var vertex = this.vertices[ i ];
  3916. matrix.multiplyVector3( vertex );
  3917. }
  3918. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3919. var face = this.faces[ i ];
  3920. normalMatrix.multiplyVector3( face.normal ).normalize();
  3921. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3922. normalMatrix.multiplyVector3( face.vertexNormals[ j ] ).normalize();
  3923. }
  3924. matrix.multiplyVector3( face.centroid );
  3925. }
  3926. },
  3927. computeCentroids: function () {
  3928. var f, fl, face;
  3929. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3930. face = this.faces[ f ];
  3931. face.centroid.set( 0, 0, 0 );
  3932. if ( face instanceof THREE.Face3 ) {
  3933. face.centroid.addSelf( this.vertices[ face.a ] );
  3934. face.centroid.addSelf( this.vertices[ face.b ] );
  3935. face.centroid.addSelf( this.vertices[ face.c ] );
  3936. face.centroid.divideScalar( 3 );
  3937. } else if ( face instanceof THREE.Face4 ) {
  3938. face.centroid.addSelf( this.vertices[ face.a ] );
  3939. face.centroid.addSelf( this.vertices[ face.b ] );
  3940. face.centroid.addSelf( this.vertices[ face.c ] );
  3941. face.centroid.addSelf( this.vertices[ face.d ] );
  3942. face.centroid.divideScalar( 4 );
  3943. }
  3944. }
  3945. },
  3946. computeFaceNormals: function () {
  3947. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3948. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3949. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3950. face = this.faces[ f ];
  3951. vA = this.vertices[ face.a ];
  3952. vB = this.vertices[ face.b ];
  3953. vC = this.vertices[ face.c ];
  3954. cb.sub( vC, vB );
  3955. ab.sub( vA, vB );
  3956. cb.crossSelf( ab );
  3957. cb.normalize();
  3958. face.normal.copy( cb );
  3959. }
  3960. },
  3961. computeVertexNormals: function ( areaWeighted ) {
  3962. var v, vl, f, fl, face, vertices;
  3963. // create internal buffers for reuse when calling this method repeatedly
  3964. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3965. if ( this.__tmpVertices === undefined ) {
  3966. this.__tmpVertices = new Array( this.vertices.length );
  3967. vertices = this.__tmpVertices;
  3968. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3969. vertices[ v ] = new THREE.Vector3();
  3970. }
  3971. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3972. face = this.faces[ f ];
  3973. if ( face instanceof THREE.Face3 ) {
  3974. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3975. } else if ( face instanceof THREE.Face4 ) {
  3976. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3977. }
  3978. }
  3979. } else {
  3980. vertices = this.__tmpVertices;
  3981. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3982. vertices[ v ].set( 0, 0, 0 );
  3983. }
  3984. }
  3985. if ( areaWeighted ) {
  3986. // vertex normals weighted by triangle areas
  3987. // http://www.iquilezles.org/www/articles/normals/normals.htm
  3988. var vA, vB, vC, vD;
  3989. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  3990. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  3991. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3992. face = this.faces[ f ];
  3993. if ( face instanceof THREE.Face3 ) {
  3994. vA = this.vertices[ face.a ];
  3995. vB = this.vertices[ face.b ];
  3996. vC = this.vertices[ face.c ];
  3997. cb.sub( vC, vB );
  3998. ab.sub( vA, vB );
  3999. cb.crossSelf( ab );
  4000. vertices[ face.a ].addSelf( cb );
  4001. vertices[ face.b ].addSelf( cb );
  4002. vertices[ face.c ].addSelf( cb );
  4003. } else if ( face instanceof THREE.Face4 ) {
  4004. vA = this.vertices[ face.a ];
  4005. vB = this.vertices[ face.b ];
  4006. vC = this.vertices[ face.c ];
  4007. vD = this.vertices[ face.d ];
  4008. // abd
  4009. db.sub( vD, vB );
  4010. ab.sub( vA, vB );
  4011. db.crossSelf( ab );
  4012. vertices[ face.a ].addSelf( db );
  4013. vertices[ face.b ].addSelf( db );
  4014. vertices[ face.d ].addSelf( db );
  4015. // bcd
  4016. dc.sub( vD, vC );
  4017. bc.sub( vB, vC );
  4018. dc.crossSelf( bc );
  4019. vertices[ face.b ].addSelf( dc );
  4020. vertices[ face.c ].addSelf( dc );
  4021. vertices[ face.d ].addSelf( dc );
  4022. }
  4023. }
  4024. } else {
  4025. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4026. face = this.faces[ f ];
  4027. if ( face instanceof THREE.Face3 ) {
  4028. vertices[ face.a ].addSelf( face.normal );
  4029. vertices[ face.b ].addSelf( face.normal );
  4030. vertices[ face.c ].addSelf( face.normal );
  4031. } else if ( face instanceof THREE.Face4 ) {
  4032. vertices[ face.a ].addSelf( face.normal );
  4033. vertices[ face.b ].addSelf( face.normal );
  4034. vertices[ face.c ].addSelf( face.normal );
  4035. vertices[ face.d ].addSelf( face.normal );
  4036. }
  4037. }
  4038. }
  4039. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4040. vertices[ v ].normalize();
  4041. }
  4042. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4043. face = this.faces[ f ];
  4044. if ( face instanceof THREE.Face3 ) {
  4045. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4046. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4047. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4048. } else if ( face instanceof THREE.Face4 ) {
  4049. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4050. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4051. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4052. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4053. }
  4054. }
  4055. },
  4056. computeMorphNormals: function () {
  4057. var i, il, f, fl, face;
  4058. // save original normals
  4059. // - create temp variables on first access
  4060. // otherwise just copy (for faster repeated calls)
  4061. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4062. face = this.faces[ f ];
  4063. if ( ! face.__originalFaceNormal ) {
  4064. face.__originalFaceNormal = face.normal.clone();
  4065. } else {
  4066. face.__originalFaceNormal.copy( face.normal );
  4067. }
  4068. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4069. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4070. if ( ! face.__originalVertexNormals[ i ] ) {
  4071. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4072. } else {
  4073. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4074. }
  4075. }
  4076. }
  4077. // use temp geometry to compute face and vertex normals for each morph
  4078. var tmpGeo = new THREE.Geometry();
  4079. tmpGeo.faces = this.faces;
  4080. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4081. // create on first access
  4082. if ( ! this.morphNormals[ i ] ) {
  4083. this.morphNormals[ i ] = {};
  4084. this.morphNormals[ i ].faceNormals = [];
  4085. this.morphNormals[ i ].vertexNormals = [];
  4086. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4087. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4088. var faceNormal, vertexNormals;
  4089. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4090. face = this.faces[ f ];
  4091. faceNormal = new THREE.Vector3();
  4092. if ( face instanceof THREE.Face3 ) {
  4093. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4094. } else {
  4095. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4096. }
  4097. dstNormalsFace.push( faceNormal );
  4098. dstNormalsVertex.push( vertexNormals );
  4099. }
  4100. }
  4101. var morphNormals = this.morphNormals[ i ];
  4102. // set vertices to morph target
  4103. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4104. // compute morph normals
  4105. tmpGeo.computeFaceNormals();
  4106. tmpGeo.computeVertexNormals();
  4107. // store morph normals
  4108. var faceNormal, vertexNormals;
  4109. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4110. face = this.faces[ f ];
  4111. faceNormal = morphNormals.faceNormals[ f ];
  4112. vertexNormals = morphNormals.vertexNormals[ f ];
  4113. faceNormal.copy( face.normal );
  4114. if ( face instanceof THREE.Face3 ) {
  4115. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4116. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4117. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4118. } else {
  4119. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4120. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4121. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4122. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4123. }
  4124. }
  4125. }
  4126. // restore original normals
  4127. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4128. face = this.faces[ f ];
  4129. face.normal = face.__originalFaceNormal;
  4130. face.vertexNormals = face.__originalVertexNormals;
  4131. }
  4132. },
  4133. computeTangents: function () {
  4134. // based on http://www.terathon.com/code/tangent.html
  4135. // tangents go to vertices
  4136. var f, fl, v, vl, i, il, vertexIndex,
  4137. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4138. x1, x2, y1, y2, z1, z2,
  4139. s1, s2, t1, t2, r, t, test,
  4140. tan1 = [], tan2 = [],
  4141. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4142. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4143. n = new THREE.Vector3(), w;
  4144. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4145. tan1[ v ] = new THREE.Vector3();
  4146. tan2[ v ] = new THREE.Vector3();
  4147. }
  4148. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4149. vA = context.vertices[ a ];
  4150. vB = context.vertices[ b ];
  4151. vC = context.vertices[ c ];
  4152. uvA = uv[ ua ];
  4153. uvB = uv[ ub ];
  4154. uvC = uv[ uc ];
  4155. x1 = vB.x - vA.x;
  4156. x2 = vC.x - vA.x;
  4157. y1 = vB.y - vA.y;
  4158. y2 = vC.y - vA.y;
  4159. z1 = vB.z - vA.z;
  4160. z2 = vC.z - vA.z;
  4161. s1 = uvB.x - uvA.x;
  4162. s2 = uvC.x - uvA.x;
  4163. t1 = uvB.y - uvA.y;
  4164. t2 = uvC.y - uvA.y;
  4165. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4166. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4167. ( t2 * y1 - t1 * y2 ) * r,
  4168. ( t2 * z1 - t1 * z2 ) * r );
  4169. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4170. ( s1 * y2 - s2 * y1 ) * r,
  4171. ( s1 * z2 - s2 * z1 ) * r );
  4172. tan1[ a ].addSelf( sdir );
  4173. tan1[ b ].addSelf( sdir );
  4174. tan1[ c ].addSelf( sdir );
  4175. tan2[ a ].addSelf( tdir );
  4176. tan2[ b ].addSelf( tdir );
  4177. tan2[ c ].addSelf( tdir );
  4178. }
  4179. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4180. face = this.faces[ f ];
  4181. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4182. if ( face instanceof THREE.Face3 ) {
  4183. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4184. } else if ( face instanceof THREE.Face4 ) {
  4185. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4186. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4187. }
  4188. }
  4189. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4190. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4191. face = this.faces[ f ];
  4192. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4193. n.copy( face.vertexNormals[ i ] );
  4194. vertexIndex = face[ faceIndex[ i ] ];
  4195. t = tan1[ vertexIndex ];
  4196. // Gram-Schmidt orthogonalize
  4197. tmp.copy( t );
  4198. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4199. // Calculate handedness
  4200. tmp2.cross( face.vertexNormals[ i ], t );
  4201. test = tmp2.dot( tan2[ vertexIndex ] );
  4202. w = (test < 0.0) ? -1.0 : 1.0;
  4203. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4204. }
  4205. }
  4206. this.hasTangents = true;
  4207. },
  4208. computeLineDistances: function ( ) {
  4209. var d = 0;
  4210. var vertices = this.vertices;
  4211. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4212. if ( i > 0 ) {
  4213. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4214. }
  4215. this.lineDistances[ i ] = d;
  4216. }
  4217. },
  4218. computeBoundingBox: function () {
  4219. if ( this.boundingBox === null ) {
  4220. this.boundingBox = new THREE.Box3();
  4221. }
  4222. this.boundingBox.setFromPoints( this.vertices );
  4223. },
  4224. computeBoundingSphere: function () {
  4225. if ( this.boundingSphere === null ) {
  4226. this.boundingSphere = new THREE.Sphere();
  4227. }
  4228. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4229. },
  4230. /*
  4231. * Checks for duplicate vertices with hashmap.
  4232. * Duplicated vertices are removed
  4233. * and faces' vertices are updated.
  4234. */
  4235. mergeVertices: function () {
  4236. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4237. var unique = [], changes = [];
  4238. var v, key;
  4239. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4240. var precision = Math.pow( 10, precisionPoints );
  4241. var i,il, face;
  4242. var abcd = 'abcd', o, k, j, jl, u;
  4243. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4244. v = this.vertices[ i ];
  4245. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4246. if ( verticesMap[ key ] === undefined ) {
  4247. verticesMap[ key ] = i;
  4248. unique.push( this.vertices[ i ] );
  4249. changes[ i ] = unique.length - 1;
  4250. } else {
  4251. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4252. changes[ i ] = changes[ verticesMap[ key ] ];
  4253. }
  4254. };
  4255. // Start to patch face indices
  4256. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4257. face = this.faces[ i ];
  4258. if ( face instanceof THREE.Face3 ) {
  4259. face.a = changes[ face.a ];
  4260. face.b = changes[ face.b ];
  4261. face.c = changes[ face.c ];
  4262. } else if ( face instanceof THREE.Face4 ) {
  4263. face.a = changes[ face.a ];
  4264. face.b = changes[ face.b ];
  4265. face.c = changes[ face.c ];
  4266. face.d = changes[ face.d ];
  4267. // check dups in (a, b, c, d) and convert to -> face3
  4268. o = [ face.a, face.b, face.c, face.d ];
  4269. for ( k = 3; k > 0; k -- ) {
  4270. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  4271. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  4272. o.splice( k, 1 );
  4273. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  4274. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4275. u = this.faceVertexUvs[ j ][ i ];
  4276. if ( u ) u.splice( k, 1 );
  4277. }
  4278. this.faces[ i ].vertexColors = face.vertexColors;
  4279. break;
  4280. }
  4281. }
  4282. }
  4283. }
  4284. // Use unique set of vertices
  4285. var diff = this.vertices.length - unique.length;
  4286. this.vertices = unique;
  4287. return diff;
  4288. },
  4289. clone: function () {
  4290. var geometry = new THREE.Geometry();
  4291. var vertices = this.vertices;
  4292. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4293. geometry.vertices.push( vertices[ i ].clone() );
  4294. }
  4295. var faces = this.faces;
  4296. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4297. geometry.faces.push( faces[ i ].clone() );
  4298. }
  4299. var uvs = this.faceVertexUvs[ 0 ];
  4300. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4301. var uv = uvs[ i ], uvCopy = [];
  4302. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4303. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4304. }
  4305. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4306. }
  4307. return geometry;
  4308. }
  4309. };
  4310. THREE.GeometryIdCount = 0;
  4311. /**
  4312. * @author alteredq / http://alteredqualia.com/
  4313. */
  4314. THREE.BufferGeometry = function () {
  4315. this.id = THREE.GeometryIdCount ++;
  4316. // attributes
  4317. this.attributes = {};
  4318. // attributes typed arrays are kept only if dynamic flag is set
  4319. this.dynamic = false;
  4320. // offsets for chunks when using indexed elements
  4321. this.offsets = [];
  4322. // boundings
  4323. this.boundingBox = null;
  4324. this.boundingSphere = null;
  4325. this.hasTangents = false;
  4326. // for compatibility
  4327. this.morphTargets = [];
  4328. };
  4329. THREE.BufferGeometry.prototype = {
  4330. constructor : THREE.BufferGeometry,
  4331. applyMatrix: function ( matrix ) {
  4332. var positionArray;
  4333. var normalArray;
  4334. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4335. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4336. if ( positionArray !== undefined ) {
  4337. matrix.multiplyVector3Array( positionArray );
  4338. this.verticesNeedUpdate = true;
  4339. }
  4340. if ( normalArray !== undefined ) {
  4341. var normalMatrix = new THREE.Matrix3();
  4342. normalMatrix.getInverse( matrix ).transpose();
  4343. normalMatrix.multiplyVector3Array( normalArray );
  4344. this.normalizeNormals();
  4345. this.normalsNeedUpdate = true;
  4346. }
  4347. },
  4348. computeBoundingBox: function () {
  4349. if ( this.boundingBox === null ) {
  4350. this.boundingBox = new THREE.Box3();
  4351. }
  4352. var positions = this.attributes[ "position" ].array;
  4353. if ( positions ) {
  4354. var bb = this.boundingBox;
  4355. var x, y, z;
  4356. if( positions.length >= 3 ) {
  4357. bb.min.x = bb.max.x = positions[ 0 ];
  4358. bb.min.y = bb.max.y = positions[ 1 ];
  4359. bb.min.z = bb.max.z = positions[ 2 ];
  4360. }
  4361. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4362. x = positions[ i ];
  4363. y = positions[ i + 1 ];
  4364. z = positions[ i + 2 ];
  4365. // bounding box
  4366. if ( x < bb.min.x ) {
  4367. bb.min.x = x;
  4368. } else if ( x > bb.max.x ) {
  4369. bb.max.x = x;
  4370. }
  4371. if ( y < bb.min.y ) {
  4372. bb.min.y = y;
  4373. } else if ( y > bb.max.y ) {
  4374. bb.max.y = y;
  4375. }
  4376. if ( z < bb.min.z ) {
  4377. bb.min.z = z;
  4378. } else if ( z > bb.max.z ) {
  4379. bb.max.z = z;
  4380. }
  4381. }
  4382. }
  4383. if ( positions === undefined || positions.length === 0 ) {
  4384. this.boundingBox.min.set( 0, 0, 0 );
  4385. this.boundingBox.max.set( 0, 0, 0 );
  4386. }
  4387. },
  4388. computeBoundingSphere: function () {
  4389. if ( this.boundingSphere === null ) {
  4390. this.boundingSphere = new THREE.Sphere();
  4391. }
  4392. var positions = this.attributes[ "position" ].array;
  4393. if ( positions ) {
  4394. var radiusSq, maxRadiusSq = 0;
  4395. var x, y, z;
  4396. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4397. x = positions[ i ];
  4398. y = positions[ i + 1 ];
  4399. z = positions[ i + 2 ];
  4400. radiusSq = x * x + y * y + z * z;
  4401. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4402. }
  4403. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4404. }
  4405. },
  4406. computeVertexNormals: function () {
  4407. if ( this.attributes[ "position" ] ) {
  4408. var i, il;
  4409. var j, jl;
  4410. var nVertexElements = this.attributes[ "position" ].array.length;
  4411. if ( this.attributes[ "normal" ] === undefined ) {
  4412. this.attributes[ "normal" ] = {
  4413. itemSize: 3,
  4414. array: new Float32Array( nVertexElements ),
  4415. numItems: nVertexElements
  4416. };
  4417. } else {
  4418. // reset existing normals to zero
  4419. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4420. this.attributes[ "normal" ].array[ i ] = 0;
  4421. }
  4422. }
  4423. var positions = this.attributes[ "position" ].array;
  4424. var normals = this.attributes[ "normal" ].array;
  4425. var vA, vB, vC, x, y, z,
  4426. pA = new THREE.Vector3(),
  4427. pB = new THREE.Vector3(),
  4428. pC = new THREE.Vector3(),
  4429. cb = new THREE.Vector3(),
  4430. ab = new THREE.Vector3();
  4431. // indexed elements
  4432. if ( this.attributes[ "index" ] ) {
  4433. var indices = this.attributes[ "index" ].array;
  4434. var offsets = this.offsets;
  4435. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4436. var start = offsets[ j ].start;
  4437. var count = offsets[ j ].count;
  4438. var index = offsets[ j ].index;
  4439. for ( i = start, il = start + count; i < il; i += 3 ) {
  4440. vA = index + indices[ i ];
  4441. vB = index + indices[ i + 1 ];
  4442. vC = index + indices[ i + 2 ];
  4443. x = positions[ vA * 3 ];
  4444. y = positions[ vA * 3 + 1 ];
  4445. z = positions[ vA * 3 + 2 ];
  4446. pA.set( x, y, z );
  4447. x = positions[ vB * 3 ];
  4448. y = positions[ vB * 3 + 1 ];
  4449. z = positions[ vB * 3 + 2 ];
  4450. pB.set( x, y, z );
  4451. x = positions[ vC * 3 ];
  4452. y = positions[ vC * 3 + 1 ];
  4453. z = positions[ vC * 3 + 2 ];
  4454. pC.set( x, y, z );
  4455. cb.sub( pC, pB );
  4456. ab.sub( pA, pB );
  4457. cb.crossSelf( ab );
  4458. normals[ vA * 3 ] += cb.x;
  4459. normals[ vA * 3 + 1 ] += cb.y;
  4460. normals[ vA * 3 + 2 ] += cb.z;
  4461. normals[ vB * 3 ] += cb.x;
  4462. normals[ vB * 3 + 1 ] += cb.y;
  4463. normals[ vB * 3 + 2 ] += cb.z;
  4464. normals[ vC * 3 ] += cb.x;
  4465. normals[ vC * 3 + 1 ] += cb.y;
  4466. normals[ vC * 3 + 2 ] += cb.z;
  4467. }
  4468. }
  4469. // non-indexed elements (unconnected triangle soup)
  4470. } else {
  4471. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4472. x = positions[ i ];
  4473. y = positions[ i + 1 ];
  4474. z = positions[ i + 2 ];
  4475. pA.set( x, y, z );
  4476. x = positions[ i + 3 ];
  4477. y = positions[ i + 4 ];
  4478. z = positions[ i + 5 ];
  4479. pB.set( x, y, z );
  4480. x = positions[ i + 6 ];
  4481. y = positions[ i + 7 ];
  4482. z = positions[ i + 8 ];
  4483. pC.set( x, y, z );
  4484. cb.sub( pC, pB );
  4485. ab.sub( pA, pB );
  4486. cb.crossSelf( ab );
  4487. normals[ i ] = cb.x;
  4488. normals[ i + 1 ] = cb.y;
  4489. normals[ i + 2 ] = cb.z;
  4490. normals[ i + 3 ] = cb.x;
  4491. normals[ i + 4 ] = cb.y;
  4492. normals[ i + 5 ] = cb.z;
  4493. normals[ i + 6 ] = cb.x;
  4494. normals[ i + 7 ] = cb.y;
  4495. normals[ i + 8 ] = cb.z;
  4496. }
  4497. }
  4498. this.normalizeNormals();
  4499. this.normalsNeedUpdate = true;
  4500. }
  4501. },
  4502. normalizeNormals: function () {
  4503. var normals = this.attributes[ "normal" ].array;
  4504. var x, y, z, n;
  4505. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  4506. x = normals[ i ];
  4507. y = normals[ i + 1 ];
  4508. z = normals[ i + 2 ];
  4509. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  4510. normals[ i ] *= n;
  4511. normals[ i + 1 ] *= n;
  4512. normals[ i + 2 ] *= n;
  4513. }
  4514. },
  4515. computeTangents: function () {
  4516. // based on http://www.terathon.com/code/tangent.html
  4517. // (per vertex tangents)
  4518. if ( this.attributes[ "index" ] === undefined ||
  4519. this.attributes[ "position" ] === undefined ||
  4520. this.attributes[ "normal" ] === undefined ||
  4521. this.attributes[ "uv" ] === undefined ) {
  4522. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  4523. return;
  4524. }
  4525. var indices = this.attributes[ "index" ].array;
  4526. var positions = this.attributes[ "position" ].array;
  4527. var normals = this.attributes[ "normal" ].array;
  4528. var uvs = this.attributes[ "uv" ].array;
  4529. var nVertices = positions.length / 3;
  4530. if ( this.attributes[ "tangent" ] === undefined ) {
  4531. var nTangentElements = 4 * nVertices;
  4532. this.attributes[ "tangent" ] = {
  4533. itemSize: 4,
  4534. array: new Float32Array( nTangentElements ),
  4535. numItems: nTangentElements
  4536. };
  4537. }
  4538. var tangents = this.attributes[ "tangent" ].array;
  4539. var tan1 = [], tan2 = [];
  4540. for ( var k = 0; k < nVertices; k ++ ) {
  4541. tan1[ k ] = new THREE.Vector3();
  4542. tan2[ k ] = new THREE.Vector3();
  4543. }
  4544. var xA, yA, zA,
  4545. xB, yB, zB,
  4546. xC, yC, zC,
  4547. uA, vA,
  4548. uB, vB,
  4549. uC, vC,
  4550. x1, x2, y1, y2, z1, z2,
  4551. s1, s2, t1, t2, r;
  4552. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  4553. function handleTriangle( a, b, c ) {
  4554. xA = positions[ a * 3 ];
  4555. yA = positions[ a * 3 + 1 ];
  4556. zA = positions[ a * 3 + 2 ];
  4557. xB = positions[ b * 3 ];
  4558. yB = positions[ b * 3 + 1 ];
  4559. zB = positions[ b * 3 + 2 ];
  4560. xC = positions[ c * 3 ];
  4561. yC = positions[ c * 3 + 1 ];
  4562. zC = positions[ c * 3 + 2 ];
  4563. uA = uvs[ a * 2 ];
  4564. vA = uvs[ a * 2 + 1 ];
  4565. uB = uvs[ b * 2 ];
  4566. vB = uvs[ b * 2 + 1 ];
  4567. uC = uvs[ c * 2 ];
  4568. vC = uvs[ c * 2 + 1 ];
  4569. x1 = xB - xA;
  4570. x2 = xC - xA;
  4571. y1 = yB - yA;
  4572. y2 = yC - yA;
  4573. z1 = zB - zA;
  4574. z2 = zC - zA;
  4575. s1 = uB - uA;
  4576. s2 = uC - uA;
  4577. t1 = vB - vA;
  4578. t2 = vC - vA;
  4579. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4580. sdir.set(
  4581. ( t2 * x1 - t1 * x2 ) * r,
  4582. ( t2 * y1 - t1 * y2 ) * r,
  4583. ( t2 * z1 - t1 * z2 ) * r
  4584. );
  4585. tdir.set(
  4586. ( s1 * x2 - s2 * x1 ) * r,
  4587. ( s1 * y2 - s2 * y1 ) * r,
  4588. ( s1 * z2 - s2 * z1 ) * r
  4589. );
  4590. tan1[ a ].addSelf( sdir );
  4591. tan1[ b ].addSelf( sdir );
  4592. tan1[ c ].addSelf( sdir );
  4593. tan2[ a ].addSelf( tdir );
  4594. tan2[ b ].addSelf( tdir );
  4595. tan2[ c ].addSelf( tdir );
  4596. }
  4597. var i, il;
  4598. var j, jl;
  4599. var iA, iB, iC;
  4600. var offsets = this.offsets;
  4601. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4602. var start = offsets[ j ].start;
  4603. var count = offsets[ j ].count;
  4604. var index = offsets[ j ].index;
  4605. for ( i = start, il = start + count; i < il; i += 3 ) {
  4606. iA = index + indices[ i ];
  4607. iB = index + indices[ i + 1 ];
  4608. iC = index + indices[ i + 2 ];
  4609. handleTriangle( iA, iB, iC );
  4610. }
  4611. }
  4612. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  4613. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  4614. var w, t, test;
  4615. var nx, ny, nz;
  4616. function handleVertex( v ) {
  4617. n.x = normals[ v * 3 ];
  4618. n.y = normals[ v * 3 + 1 ];
  4619. n.z = normals[ v * 3 + 2 ];
  4620. n2.copy( n );
  4621. t = tan1[ v ];
  4622. // Gram-Schmidt orthogonalize
  4623. tmp.copy( t );
  4624. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4625. // Calculate handedness
  4626. tmp2.cross( n2, t );
  4627. test = tmp2.dot( tan2[ v ] );
  4628. w = ( test < 0.0 ) ? -1.0 : 1.0;
  4629. tangents[ v * 4 ] = tmp.x;
  4630. tangents[ v * 4 + 1 ] = tmp.y;
  4631. tangents[ v * 4 + 2 ] = tmp.z;
  4632. tangents[ v * 4 + 3 ] = w;
  4633. }
  4634. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4635. var start = offsets[ j ].start;
  4636. var count = offsets[ j ].count;
  4637. var index = offsets[ j ].index;
  4638. for ( i = start, il = start + count; i < il; i += 3 ) {
  4639. iA = index + indices[ i ];
  4640. iB = index + indices[ i + 1 ];
  4641. iC = index + indices[ i + 2 ];
  4642. handleVertex( iA );
  4643. handleVertex( iB );
  4644. handleVertex( iC );
  4645. }
  4646. }
  4647. this.hasTangents = true;
  4648. this.tangentsNeedUpdate = true;
  4649. }
  4650. };
  4651. /**
  4652. * @author mrdoob / http://mrdoob.com/
  4653. * @author mikael emtinger / http://gomo.se/
  4654. */
  4655. THREE.Camera = function () {
  4656. THREE.Object3D.call( this );
  4657. this.matrixWorldInverse = new THREE.Matrix4();
  4658. this.projectionMatrix = new THREE.Matrix4();
  4659. this.projectionMatrixInverse = new THREE.Matrix4();
  4660. };
  4661. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  4662. THREE.Camera.prototype.lookAt = function ( vector ) {
  4663. // TODO: Add hierarchy support.
  4664. this.matrix.lookAt( this.position, vector, this.up );
  4665. if ( this.rotationAutoUpdate === true ) {
  4666. if ( this.useQuaternion === false ) {
  4667. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  4668. } else {
  4669. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  4670. }
  4671. }
  4672. };
  4673. /**
  4674. * @author alteredq / http://alteredqualia.com/
  4675. */
  4676. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  4677. THREE.Camera.call( this );
  4678. this.left = left;
  4679. this.right = right;
  4680. this.top = top;
  4681. this.bottom = bottom;
  4682. this.near = ( near !== undefined ) ? near : 0.1;
  4683. this.far = ( far !== undefined ) ? far : 2000;
  4684. this.updateProjectionMatrix();
  4685. };
  4686. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  4687. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  4688. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  4689. };
  4690. /**
  4691. * @author mrdoob / http://mrdoob.com/
  4692. * @author greggman / http://games.greggman.com/
  4693. * @author zz85 / http://www.lab4games.net/zz85/blog
  4694. */
  4695. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  4696. THREE.Camera.call( this );
  4697. this.fov = fov !== undefined ? fov : 50;
  4698. this.aspect = aspect !== undefined ? aspect : 1;
  4699. this.near = near !== undefined ? near : 0.1;
  4700. this.far = far !== undefined ? far : 2000;
  4701. this.updateProjectionMatrix();
  4702. };
  4703. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  4704. /**
  4705. * Uses Focal Length (in mm) to estimate and set FOV
  4706. * 35mm (fullframe) camera is used if frame size is not specified;
  4707. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  4708. */
  4709. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  4710. if ( frameHeight === undefined ) frameHeight = 24;
  4711. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  4712. this.updateProjectionMatrix();
  4713. }
  4714. /**
  4715. * Sets an offset in a larger frustum. This is useful for multi-window or
  4716. * multi-monitor/multi-machine setups.
  4717. *
  4718. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  4719. * the monitors are in grid like this
  4720. *
  4721. * +---+---+---+
  4722. * | A | B | C |
  4723. * +---+---+---+
  4724. * | D | E | F |
  4725. * +---+---+---+
  4726. *
  4727. * then for each monitor you would call it like this
  4728. *
  4729. * var w = 1920;
  4730. * var h = 1080;
  4731. * var fullWidth = w * 3;
  4732. * var fullHeight = h * 2;
  4733. *
  4734. * --A--
  4735. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4736. * --B--
  4737. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4738. * --C--
  4739. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4740. * --D--
  4741. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4742. * --E--
  4743. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4744. * --F--
  4745. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4746. *
  4747. * Note there is no reason monitors have to be the same size or in a grid.
  4748. */
  4749. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4750. this.fullWidth = fullWidth;
  4751. this.fullHeight = fullHeight;
  4752. this.x = x;
  4753. this.y = y;
  4754. this.width = width;
  4755. this.height = height;
  4756. this.updateProjectionMatrix();
  4757. };
  4758. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4759. if ( this.fullWidth ) {
  4760. var aspect = this.fullWidth / this.fullHeight;
  4761. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  4762. var bottom = -top;
  4763. var left = aspect * bottom;
  4764. var right = aspect * top;
  4765. var width = Math.abs( right - left );
  4766. var height = Math.abs( top - bottom );
  4767. this.projectionMatrix.makeFrustum(
  4768. left + this.x * width / this.fullWidth,
  4769. left + ( this.x + this.width ) * width / this.fullWidth,
  4770. top - ( this.y + this.height ) * height / this.fullHeight,
  4771. top - this.y * height / this.fullHeight,
  4772. this.near,
  4773. this.far
  4774. );
  4775. } else {
  4776. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4777. }
  4778. };
  4779. /**
  4780. * @author mrdoob / http://mrdoob.com/
  4781. * @author alteredq / http://alteredqualia.com/
  4782. */
  4783. THREE.Light = function ( hex ) {
  4784. THREE.Object3D.call( this );
  4785. this.color = new THREE.Color( hex );
  4786. };
  4787. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4788. /**
  4789. * @author mrdoob / http://mrdoob.com/
  4790. */
  4791. THREE.AmbientLight = function ( hex ) {
  4792. THREE.Light.call( this, hex );
  4793. };
  4794. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4795. /**
  4796. * @author mrdoob / http://mrdoob.com/
  4797. * @author alteredq / http://alteredqualia.com/
  4798. */
  4799. THREE.DirectionalLight = function ( hex, intensity ) {
  4800. THREE.Light.call( this, hex );
  4801. this.position = new THREE.Vector3( 0, 1, 0 );
  4802. this.target = new THREE.Object3D();
  4803. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4804. this.castShadow = false;
  4805. this.onlyShadow = false;
  4806. //
  4807. this.shadowCameraNear = 50;
  4808. this.shadowCameraFar = 5000;
  4809. this.shadowCameraLeft = -500;
  4810. this.shadowCameraRight = 500;
  4811. this.shadowCameraTop = 500;
  4812. this.shadowCameraBottom = -500;
  4813. this.shadowCameraVisible = false;
  4814. this.shadowBias = 0;
  4815. this.shadowDarkness = 0.5;
  4816. this.shadowMapWidth = 512;
  4817. this.shadowMapHeight = 512;
  4818. //
  4819. this.shadowCascade = false;
  4820. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  4821. this.shadowCascadeCount = 2;
  4822. this.shadowCascadeBias = [ 0, 0, 0 ];
  4823. this.shadowCascadeWidth = [ 512, 512, 512 ];
  4824. this.shadowCascadeHeight = [ 512, 512, 512 ];
  4825. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  4826. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  4827. this.shadowCascadeArray = [];
  4828. //
  4829. this.shadowMap = null;
  4830. this.shadowMapSize = null;
  4831. this.shadowCamera = null;
  4832. this.shadowMatrix = null;
  4833. };
  4834. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  4835. /**
  4836. * @author alteredq / http://alteredqualia.com/
  4837. */
  4838. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  4839. THREE.Light.call( this, skyColorHex );
  4840. this.groundColor = new THREE.Color( groundColorHex );
  4841. this.position = new THREE.Vector3( 0, 100, 0 );
  4842. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4843. };
  4844. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  4845. /**
  4846. * @author mrdoob / http://mrdoob.com/
  4847. */
  4848. THREE.PointLight = function ( hex, intensity, distance ) {
  4849. THREE.Light.call( this, hex );
  4850. this.position = new THREE.Vector3( 0, 0, 0 );
  4851. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4852. this.distance = ( distance !== undefined ) ? distance : 0;
  4853. };
  4854. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  4855. /**
  4856. * @author alteredq / http://alteredqualia.com/
  4857. */
  4858. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  4859. THREE.Light.call( this, hex );
  4860. this.position = new THREE.Vector3( 0, 1, 0 );
  4861. this.target = new THREE.Object3D();
  4862. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4863. this.distance = ( distance !== undefined ) ? distance : 0;
  4864. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  4865. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  4866. this.castShadow = false;
  4867. this.onlyShadow = false;
  4868. //
  4869. this.shadowCameraNear = 50;
  4870. this.shadowCameraFar = 5000;
  4871. this.shadowCameraFov = 50;
  4872. this.shadowCameraVisible = false;
  4873. this.shadowBias = 0;
  4874. this.shadowDarkness = 0.5;
  4875. this.shadowMapWidth = 512;
  4876. this.shadowMapHeight = 512;
  4877. //
  4878. this.shadowMap = null;
  4879. this.shadowMapSize = null;
  4880. this.shadowCamera = null;
  4881. this.shadowMatrix = null;
  4882. };
  4883. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4884. /**
  4885. * @author alteredq / http://alteredqualia.com/
  4886. */
  4887. THREE.Loader = function ( showStatus ) {
  4888. this.showStatus = showStatus;
  4889. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4890. this.onLoadStart = function () {};
  4891. this.onLoadProgress = function () {};
  4892. this.onLoadComplete = function () {};
  4893. };
  4894. THREE.Loader.prototype = {
  4895. constructor: THREE.Loader,
  4896. crossOrigin: 'anonymous',
  4897. addStatusElement: function () {
  4898. var e = document.createElement( "div" );
  4899. e.style.position = "absolute";
  4900. e.style.right = "0px";
  4901. e.style.top = "0px";
  4902. e.style.fontSize = "0.8em";
  4903. e.style.textAlign = "left";
  4904. e.style.background = "rgba(0,0,0,0.25)";
  4905. e.style.color = "#fff";
  4906. e.style.width = "120px";
  4907. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4908. e.style.zIndex = 1000;
  4909. e.innerHTML = "Loading ...";
  4910. return e;
  4911. },
  4912. updateProgress: function ( progress ) {
  4913. var message = "Loaded ";
  4914. if ( progress.total ) {
  4915. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4916. } else {
  4917. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4918. }
  4919. this.statusDomElement.innerHTML = message;
  4920. },
  4921. extractUrlBase: function ( url ) {
  4922. var parts = url.split( '/' );
  4923. parts.pop();
  4924. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4925. },
  4926. initMaterials: function ( materials, texturePath ) {
  4927. var array = [];
  4928. for ( var i = 0; i < materials.length; ++ i ) {
  4929. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4930. }
  4931. return array;
  4932. },
  4933. needsTangents: function ( materials ) {
  4934. for( var i = 0, il = materials.length; i < il; i ++ ) {
  4935. var m = materials[ i ];
  4936. if ( m instanceof THREE.ShaderMaterial ) return true;
  4937. }
  4938. return false;
  4939. },
  4940. createMaterial: function ( m, texturePath ) {
  4941. var _this = this;
  4942. function is_pow2( n ) {
  4943. var l = Math.log( n ) / Math.LN2;
  4944. return Math.floor( l ) == l;
  4945. }
  4946. function nearest_pow2( n ) {
  4947. var l = Math.log( n ) / Math.LN2;
  4948. return Math.pow( 2, Math.round( l ) );
  4949. }
  4950. function load_image( where, url ) {
  4951. var image = new Image();
  4952. image.onload = function () {
  4953. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4954. var width = nearest_pow2( this.width );
  4955. var height = nearest_pow2( this.height );
  4956. where.image.width = width;
  4957. where.image.height = height;
  4958. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4959. } else {
  4960. where.image = this;
  4961. }
  4962. where.needsUpdate = true;
  4963. };
  4964. image.crossOrigin = _this.crossOrigin;
  4965. image.src = url;
  4966. }
  4967. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4968. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4969. var fullPath = texturePath + "/" + sourceFile;
  4970. if ( isCompressed ) {
  4971. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4972. where[ name ] = texture;
  4973. } else {
  4974. var texture = document.createElement( 'canvas' );
  4975. where[ name ] = new THREE.Texture( texture );
  4976. }
  4977. where[ name ].sourceFile = sourceFile;
  4978. if( repeat ) {
  4979. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4980. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4981. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4982. }
  4983. if ( offset ) {
  4984. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4985. }
  4986. if ( wrap ) {
  4987. var wrapMap = {
  4988. "repeat": THREE.RepeatWrapping,
  4989. "mirror": THREE.MirroredRepeatWrapping
  4990. }
  4991. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4992. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4993. }
  4994. if ( anisotropy ) {
  4995. where[ name ].anisotropy = anisotropy;
  4996. }
  4997. if ( ! isCompressed ) {
  4998. load_image( where[ name ], fullPath );
  4999. }
  5000. }
  5001. function rgb2hex( rgb ) {
  5002. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5003. }
  5004. // defaults
  5005. var mtype = "MeshLambertMaterial";
  5006. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5007. // parameters from model file
  5008. if ( m.shading ) {
  5009. var shading = m.shading.toLowerCase();
  5010. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5011. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5012. }
  5013. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5014. mpars.blending = THREE[ m.blending ];
  5015. }
  5016. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5017. mpars.transparent = m.transparent;
  5018. }
  5019. if ( m.depthTest !== undefined ) {
  5020. mpars.depthTest = m.depthTest;
  5021. }
  5022. if ( m.depthWrite !== undefined ) {
  5023. mpars.depthWrite = m.depthWrite;
  5024. }
  5025. if ( m.visible !== undefined ) {
  5026. mpars.visible = m.visible;
  5027. }
  5028. if ( m.flipSided !== undefined ) {
  5029. mpars.side = THREE.BackSide;
  5030. }
  5031. if ( m.doubleSided !== undefined ) {
  5032. mpars.side = THREE.DoubleSide;
  5033. }
  5034. if ( m.wireframe !== undefined ) {
  5035. mpars.wireframe = m.wireframe;
  5036. }
  5037. if ( m.vertexColors !== undefined ) {
  5038. if ( m.vertexColors === "face" ) {
  5039. mpars.vertexColors = THREE.FaceColors;
  5040. } else if ( m.vertexColors ) {
  5041. mpars.vertexColors = THREE.VertexColors;
  5042. }
  5043. }
  5044. // colors
  5045. if ( m.colorDiffuse ) {
  5046. mpars.color = rgb2hex( m.colorDiffuse );
  5047. } else if ( m.DbgColor ) {
  5048. mpars.color = m.DbgColor;
  5049. }
  5050. if ( m.colorSpecular ) {
  5051. mpars.specular = rgb2hex( m.colorSpecular );
  5052. }
  5053. if ( m.colorAmbient ) {
  5054. mpars.ambient = rgb2hex( m.colorAmbient );
  5055. }
  5056. // modifiers
  5057. if ( m.transparency ) {
  5058. mpars.opacity = m.transparency;
  5059. }
  5060. if ( m.specularCoef ) {
  5061. mpars.shininess = m.specularCoef;
  5062. }
  5063. // textures
  5064. if ( m.mapDiffuse && texturePath ) {
  5065. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5066. }
  5067. if ( m.mapLight && texturePath ) {
  5068. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5069. }
  5070. if ( m.mapBump && texturePath ) {
  5071. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5072. }
  5073. if ( m.mapNormal && texturePath ) {
  5074. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5075. }
  5076. if ( m.mapSpecular && texturePath ) {
  5077. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5078. }
  5079. //
  5080. if ( m.mapBumpScale ) {
  5081. mpars.bumpScale = m.mapBumpScale;
  5082. }
  5083. // special case for normal mapped material
  5084. if ( m.mapNormal ) {
  5085. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5086. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5087. uniforms[ "tNormal" ].value = mpars.normalMap;
  5088. if ( m.mapNormalFactor ) {
  5089. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5090. }
  5091. if ( mpars.map ) {
  5092. uniforms[ "tDiffuse" ].value = mpars.map;
  5093. uniforms[ "enableDiffuse" ].value = true;
  5094. }
  5095. if ( mpars.specularMap ) {
  5096. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5097. uniforms[ "enableSpecular" ].value = true;
  5098. }
  5099. if ( mpars.lightMap ) {
  5100. uniforms[ "tAO" ].value = mpars.lightMap;
  5101. uniforms[ "enableAO" ].value = true;
  5102. }
  5103. // for the moment don't handle displacement texture
  5104. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5105. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5106. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5107. uniforms[ "uShininess" ].value = mpars.shininess;
  5108. if ( mpars.opacity !== undefined ) {
  5109. uniforms[ "uOpacity" ].value = mpars.opacity;
  5110. }
  5111. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5112. var material = new THREE.ShaderMaterial( parameters );
  5113. if ( mpars.transparent ) {
  5114. material.transparent = true;
  5115. }
  5116. } else {
  5117. var material = new THREE[ mtype ]( mpars );
  5118. }
  5119. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5120. return material;
  5121. }
  5122. };
  5123. /**
  5124. * @author alteredq / http://alteredqualia.com/
  5125. */
  5126. THREE.BinaryLoader = function ( showStatus ) {
  5127. THREE.Loader.call( this, showStatus );
  5128. };
  5129. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  5130. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  5131. // - binary models consist of two files: JS and BIN
  5132. // - parameters
  5133. // - url (required)
  5134. // - callback (required)
  5135. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  5136. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  5137. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  5138. // todo: unify load API to for easier SceneLoader use
  5139. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5140. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  5141. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  5142. this.onLoadStart();
  5143. // #1 load JS part via web worker
  5144. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  5145. };
  5146. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  5147. var xhr = new XMLHttpRequest();
  5148. xhr.onreadystatechange = function () {
  5149. if ( xhr.readyState == 4 ) {
  5150. if ( xhr.status == 200 || xhr.status == 0 ) {
  5151. var json = JSON.parse( xhr.responseText );
  5152. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  5153. } else {
  5154. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5155. }
  5156. }
  5157. };
  5158. xhr.open( "GET", url, true );
  5159. xhr.send( null );
  5160. };
  5161. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  5162. var xhr = new XMLHttpRequest(),
  5163. url = binaryPath + "/" + json.buffers;
  5164. var length = 0;
  5165. xhr.onreadystatechange = function () {
  5166. if ( xhr.readyState == 4 ) {
  5167. if ( xhr.status == 200 || xhr.status == 0 ) {
  5168. var buffer = xhr.response;
  5169. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  5170. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  5171. } else {
  5172. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5173. }
  5174. } else if ( xhr.readyState == 3 ) {
  5175. if ( callbackProgress ) {
  5176. if ( length == 0 ) {
  5177. length = xhr.getResponseHeader( "Content-Length" );
  5178. }
  5179. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5180. }
  5181. } else if ( xhr.readyState == 2 ) {
  5182. length = xhr.getResponseHeader( "Content-Length" );
  5183. }
  5184. };
  5185. xhr.open( "GET", url, true );
  5186. xhr.responseType = "arraybuffer";
  5187. xhr.send( null );
  5188. };
  5189. // Binary AJAX parser
  5190. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  5191. var Model = function ( texturePath ) {
  5192. var scope = this,
  5193. currentOffset = 0,
  5194. md,
  5195. normals = [],
  5196. uvs = [],
  5197. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  5198. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  5199. tri_size, quad_size,
  5200. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  5201. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  5202. THREE.Geometry.call( this );
  5203. md = parseMetaData( data, currentOffset );
  5204. currentOffset += md.header_bytes;
  5205. /*
  5206. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5207. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  5208. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5209. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5210. */
  5211. // buffers sizes
  5212. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  5213. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  5214. len_tri_flat = md.ntri_flat * ( tri_size );
  5215. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  5216. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  5217. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  5218. len_quad_flat = md.nquad_flat * ( quad_size );
  5219. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  5220. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  5221. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  5222. // read buffers
  5223. currentOffset += init_vertices( currentOffset );
  5224. currentOffset += init_normals( currentOffset );
  5225. currentOffset += handlePadding( md.nnormals * 3 );
  5226. currentOffset += init_uvs( currentOffset );
  5227. start_tri_flat = currentOffset;
  5228. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  5229. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  5230. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  5231. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  5232. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  5233. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  5234. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  5235. // have to first process faces with uvs
  5236. // so that face and uv indices match
  5237. init_triangles_flat_uv( start_tri_flat_uv );
  5238. init_triangles_smooth_uv( start_tri_smooth_uv );
  5239. init_quads_flat_uv( start_quad_flat_uv );
  5240. init_quads_smooth_uv( start_quad_smooth_uv );
  5241. // now we can process untextured faces
  5242. init_triangles_flat( start_tri_flat );
  5243. init_triangles_smooth( start_tri_smooth );
  5244. init_quads_flat( start_quad_flat );
  5245. init_quads_smooth( start_quad_smooth );
  5246. this.computeCentroids();
  5247. this.computeFaceNormals();
  5248. function handlePadding( n ) {
  5249. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  5250. };
  5251. function parseMetaData( data, offset ) {
  5252. var metaData = {
  5253. 'signature' :parseString( data, offset, 12 ),
  5254. 'header_bytes' :parseUChar8( data, offset + 12 ),
  5255. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  5256. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  5257. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  5258. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  5259. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  5260. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  5261. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  5262. 'nvertices' :parseUInt32( data, offset + 20 ),
  5263. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  5264. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  5265. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  5266. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  5267. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  5268. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  5269. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  5270. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  5271. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  5272. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  5273. };
  5274. /*
  5275. console.log( "signature: " + metaData.signature );
  5276. console.log( "header_bytes: " + metaData.header_bytes );
  5277. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  5278. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  5279. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  5280. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  5281. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  5282. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  5283. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  5284. console.log( "nvertices: " + metaData.nvertices );
  5285. console.log( "nnormals: " + metaData.nnormals );
  5286. console.log( "nuvs: " + metaData.nuvs );
  5287. console.log( "ntri_flat: " + metaData.ntri_flat );
  5288. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  5289. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  5290. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  5291. console.log( "nquad_flat: " + metaData.nquad_flat );
  5292. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  5293. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  5294. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  5295. var total = metaData.header_bytes
  5296. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  5297. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  5298. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  5299. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  5300. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  5301. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  5302. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  5303. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  5304. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  5305. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  5306. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  5307. console.log( "total bytes: " + total );
  5308. */
  5309. return metaData;
  5310. };
  5311. function parseString( data, offset, length ) {
  5312. var charArray = new Uint8Array( data, offset, length );
  5313. var text = "";
  5314. for ( var i = 0; i < length; i ++ ) {
  5315. text += String.fromCharCode( charArray[ offset + i ] );
  5316. }
  5317. return text;
  5318. };
  5319. function parseUChar8( data, offset ) {
  5320. var charArray = new Uint8Array( data, offset, 1 );
  5321. return charArray[ 0 ];
  5322. };
  5323. function parseUInt32( data, offset ) {
  5324. var intArray = new Uint32Array( data, offset, 1 );
  5325. return intArray[ 0 ];
  5326. };
  5327. function init_vertices( start ) {
  5328. var nElements = md.nvertices;
  5329. var coordArray = new Float32Array( data, start, nElements * 3 );
  5330. var i, x, y, z;
  5331. for( i = 0; i < nElements; i ++ ) {
  5332. x = coordArray[ i * 3 ];
  5333. y = coordArray[ i * 3 + 1 ];
  5334. z = coordArray[ i * 3 + 2 ];
  5335. vertex( scope, x, y, z );
  5336. }
  5337. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  5338. };
  5339. function init_normals( start ) {
  5340. var nElements = md.nnormals;
  5341. if ( nElements ) {
  5342. var normalArray = new Int8Array( data, start, nElements * 3 );
  5343. var i, x, y, z;
  5344. for( i = 0; i < nElements; i ++ ) {
  5345. x = normalArray[ i * 3 ];
  5346. y = normalArray[ i * 3 + 1 ];
  5347. z = normalArray[ i * 3 + 2 ];
  5348. normals.push( x/127, y/127, z/127 );
  5349. }
  5350. }
  5351. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  5352. };
  5353. function init_uvs( start ) {
  5354. var nElements = md.nuvs;
  5355. if ( nElements ) {
  5356. var uvArray = new Float32Array( data, start, nElements * 2 );
  5357. var i, u, v;
  5358. for( i = 0; i < nElements; i ++ ) {
  5359. u = uvArray[ i * 2 ];
  5360. v = uvArray[ i * 2 + 1 ];
  5361. uvs.push( u, v );
  5362. }
  5363. }
  5364. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  5365. };
  5366. function init_uvs3( nElements, offset ) {
  5367. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  5368. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  5369. for( i = 0; i < nElements; i ++ ) {
  5370. uva = uvIndexBuffer[ i * 3 ];
  5371. uvb = uvIndexBuffer[ i * 3 + 1 ];
  5372. uvc = uvIndexBuffer[ i * 3 + 2 ];
  5373. u1 = uvs[ uva*2 ];
  5374. v1 = uvs[ uva*2 + 1 ];
  5375. u2 = uvs[ uvb*2 ];
  5376. v2 = uvs[ uvb*2 + 1 ];
  5377. u3 = uvs[ uvc*2 ];
  5378. v3 = uvs[ uvc*2 + 1 ];
  5379. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  5380. }
  5381. };
  5382. function init_uvs4( nElements, offset ) {
  5383. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  5384. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  5385. for( i = 0; i < nElements; i ++ ) {
  5386. uva = uvIndexBuffer[ i * 4 ];
  5387. uvb = uvIndexBuffer[ i * 4 + 1 ];
  5388. uvc = uvIndexBuffer[ i * 4 + 2 ];
  5389. uvd = uvIndexBuffer[ i * 4 + 3 ];
  5390. u1 = uvs[ uva*2 ];
  5391. v1 = uvs[ uva*2 + 1 ];
  5392. u2 = uvs[ uvb*2 ];
  5393. v2 = uvs[ uvb*2 + 1 ];
  5394. u3 = uvs[ uvc*2 ];
  5395. v3 = uvs[ uvc*2 + 1 ];
  5396. u4 = uvs[ uvd*2 ];
  5397. v4 = uvs[ uvd*2 + 1 ];
  5398. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  5399. }
  5400. };
  5401. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  5402. var i, a, b, c, m;
  5403. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  5404. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5405. for( i = 0; i < nElements; i ++ ) {
  5406. a = vertexIndexBuffer[ i * 3 ];
  5407. b = vertexIndexBuffer[ i * 3 + 1 ];
  5408. c = vertexIndexBuffer[ i * 3 + 2 ];
  5409. m = materialIndexBuffer[ i ];
  5410. f3( scope, a, b, c, m );
  5411. }
  5412. };
  5413. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  5414. var i, a, b, c, d, m;
  5415. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  5416. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5417. for( i = 0; i < nElements; i ++ ) {
  5418. a = vertexIndexBuffer[ i * 4 ];
  5419. b = vertexIndexBuffer[ i * 4 + 1 ];
  5420. c = vertexIndexBuffer[ i * 4 + 2 ];
  5421. d = vertexIndexBuffer[ i * 4 + 3 ];
  5422. m = materialIndexBuffer[ i ];
  5423. f4( scope, a, b, c, d, m );
  5424. }
  5425. };
  5426. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  5427. var i, a, b, c, m;
  5428. var na, nb, nc;
  5429. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  5430. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  5431. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5432. for( i = 0; i < nElements; i ++ ) {
  5433. a = vertexIndexBuffer[ i * 3 ];
  5434. b = vertexIndexBuffer[ i * 3 + 1 ];
  5435. c = vertexIndexBuffer[ i * 3 + 2 ];
  5436. na = normalIndexBuffer[ i * 3 ];
  5437. nb = normalIndexBuffer[ i * 3 + 1 ];
  5438. nc = normalIndexBuffer[ i * 3 + 2 ];
  5439. m = materialIndexBuffer[ i ];
  5440. f3n( scope, normals, a, b, c, m, na, nb, nc );
  5441. }
  5442. };
  5443. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  5444. var i, a, b, c, d, m;
  5445. var na, nb, nc, nd;
  5446. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  5447. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  5448. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5449. for( i = 0; i < nElements; i ++ ) {
  5450. a = vertexIndexBuffer[ i * 4 ];
  5451. b = vertexIndexBuffer[ i * 4 + 1 ];
  5452. c = vertexIndexBuffer[ i * 4 + 2 ];
  5453. d = vertexIndexBuffer[ i * 4 + 3 ];
  5454. na = normalIndexBuffer[ i * 4 ];
  5455. nb = normalIndexBuffer[ i * 4 + 1 ];
  5456. nc = normalIndexBuffer[ i * 4 + 2 ];
  5457. nd = normalIndexBuffer[ i * 4 + 3 ];
  5458. m = materialIndexBuffer[ i ];
  5459. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  5460. }
  5461. };
  5462. function init_triangles_flat( start ) {
  5463. var nElements = md.ntri_flat;
  5464. if ( nElements ) {
  5465. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5466. init_faces3_flat( nElements, start, offsetMaterials );
  5467. }
  5468. };
  5469. function init_triangles_flat_uv( start ) {
  5470. var nElements = md.ntri_flat_uv;
  5471. if ( nElements ) {
  5472. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5473. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5474. init_faces3_flat( nElements, start, offsetMaterials );
  5475. init_uvs3( nElements, offsetUvs );
  5476. }
  5477. };
  5478. function init_triangles_smooth( start ) {
  5479. var nElements = md.ntri_smooth;
  5480. if ( nElements ) {
  5481. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5482. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5483. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  5484. }
  5485. };
  5486. function init_triangles_smooth_uv( start ) {
  5487. var nElements = md.ntri_smooth_uv;
  5488. if ( nElements ) {
  5489. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5490. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5491. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5492. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  5493. init_uvs3( nElements, offsetUvs );
  5494. }
  5495. };
  5496. function init_quads_flat( start ) {
  5497. var nElements = md.nquad_flat;
  5498. if ( nElements ) {
  5499. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5500. init_faces4_flat( nElements, start, offsetMaterials );
  5501. }
  5502. };
  5503. function init_quads_flat_uv( start ) {
  5504. var nElements = md.nquad_flat_uv;
  5505. if ( nElements ) {
  5506. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5507. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5508. init_faces4_flat( nElements, start, offsetMaterials );
  5509. init_uvs4( nElements, offsetUvs );
  5510. }
  5511. };
  5512. function init_quads_smooth( start ) {
  5513. var nElements = md.nquad_smooth;
  5514. if ( nElements ) {
  5515. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5516. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5517. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  5518. }
  5519. };
  5520. function init_quads_smooth_uv( start ) {
  5521. var nElements = md.nquad_smooth_uv;
  5522. if ( nElements ) {
  5523. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5524. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5525. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5526. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  5527. init_uvs4( nElements, offsetUvs );
  5528. }
  5529. };
  5530. };
  5531. function vertex ( scope, x, y, z ) {
  5532. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  5533. };
  5534. function f3 ( scope, a, b, c, mi ) {
  5535. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  5536. };
  5537. function f4 ( scope, a, b, c, d, mi ) {
  5538. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  5539. };
  5540. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  5541. var nax = normals[ na*3 ],
  5542. nay = normals[ na*3 + 1 ],
  5543. naz = normals[ na*3 + 2 ],
  5544. nbx = normals[ nb*3 ],
  5545. nby = normals[ nb*3 + 1 ],
  5546. nbz = normals[ nb*3 + 2 ],
  5547. ncx = normals[ nc*3 ],
  5548. ncy = normals[ nc*3 + 1 ],
  5549. ncz = normals[ nc*3 + 2 ];
  5550. scope.faces.push( new THREE.Face3( a, b, c,
  5551. [new THREE.Vector3( nax, nay, naz ),
  5552. new THREE.Vector3( nbx, nby, nbz ),
  5553. new THREE.Vector3( ncx, ncy, ncz )],
  5554. null,
  5555. mi ) );
  5556. };
  5557. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  5558. var nax = normals[ na*3 ],
  5559. nay = normals[ na*3 + 1 ],
  5560. naz = normals[ na*3 + 2 ],
  5561. nbx = normals[ nb*3 ],
  5562. nby = normals[ nb*3 + 1 ],
  5563. nbz = normals[ nb*3 + 2 ],
  5564. ncx = normals[ nc*3 ],
  5565. ncy = normals[ nc*3 + 1 ],
  5566. ncz = normals[ nc*3 + 2 ],
  5567. ndx = normals[ nd*3 ],
  5568. ndy = normals[ nd*3 + 1 ],
  5569. ndz = normals[ nd*3 + 2 ];
  5570. scope.faces.push( new THREE.Face4( a, b, c, d,
  5571. [new THREE.Vector3( nax, nay, naz ),
  5572. new THREE.Vector3( nbx, nby, nbz ),
  5573. new THREE.Vector3( ncx, ncy, ncz ),
  5574. new THREE.Vector3( ndx, ndy, ndz )],
  5575. null,
  5576. mi ) );
  5577. };
  5578. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  5579. where.push( [
  5580. new THREE.Vector2( u1, v1 ),
  5581. new THREE.Vector2( u2, v2 ),
  5582. new THREE.Vector2( u3, v3 )
  5583. ] );
  5584. };
  5585. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  5586. where.push( [
  5587. new THREE.Vector2( u1, v1 ),
  5588. new THREE.Vector2( u2, v2 ),
  5589. new THREE.Vector2( u3, v3 ),
  5590. new THREE.Vector2( u4, v4 )
  5591. ] );
  5592. };
  5593. Model.prototype = Object.create( THREE.Geometry.prototype );
  5594. var geometry = new Model( texturePath );
  5595. var materials = this.initMaterials( jsonMaterials, texturePath );
  5596. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5597. callback( geometry, materials );
  5598. };
  5599. /**
  5600. * @author mrdoob / http://mrdoob.com/
  5601. */
  5602. THREE.ImageLoader = function () {
  5603. THREE.EventTarget.call( this );
  5604. this.crossOrigin = null;
  5605. };
  5606. THREE.ImageLoader.prototype = {
  5607. constructor: THREE.ImageLoader,
  5608. load: function ( url, image ) {
  5609. var scope = this;
  5610. if ( image === undefined ) image = new Image();
  5611. image.addEventListener( 'load', function () {
  5612. scope.dispatchEvent( { type: 'load', content: image } );
  5613. }, false );
  5614. image.addEventListener( 'error', function () {
  5615. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5616. }, false );
  5617. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5618. image.src = url;
  5619. }
  5620. }
  5621. /**
  5622. * @author mrdoob / http://mrdoob.com/
  5623. * @author alteredq / http://alteredqualia.com/
  5624. */
  5625. THREE.JSONLoader = function ( showStatus ) {
  5626. THREE.Loader.call( this, showStatus );
  5627. this.withCredentials = false;
  5628. };
  5629. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5630. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5631. var scope = this;
  5632. // todo: unify load API to for easier SceneLoader use
  5633. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5634. this.onLoadStart();
  5635. this.loadAjaxJSON( this, url, callback, texturePath );
  5636. };
  5637. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5638. var xhr = new XMLHttpRequest();
  5639. var length = 0;
  5640. xhr.withCredentials = this.withCredentials;
  5641. xhr.onreadystatechange = function () {
  5642. if ( xhr.readyState === xhr.DONE ) {
  5643. if ( xhr.status === 200 || xhr.status === 0 ) {
  5644. if ( xhr.responseText ) {
  5645. var json = JSON.parse( xhr.responseText );
  5646. context.createModel( json, callback, texturePath );
  5647. } else {
  5648. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5649. }
  5650. // in context of more complex asset initialization
  5651. // do not block on single failed file
  5652. // maybe should go even one more level up
  5653. context.onLoadComplete();
  5654. } else {
  5655. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5656. }
  5657. } else if ( xhr.readyState === xhr.LOADING ) {
  5658. if ( callbackProgress ) {
  5659. if ( length === 0 ) {
  5660. length = xhr.getResponseHeader( "Content-Length" );
  5661. }
  5662. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5663. }
  5664. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5665. length = xhr.getResponseHeader( "Content-Length" );
  5666. }
  5667. };
  5668. xhr.open( "GET", url, true );
  5669. xhr.send( null );
  5670. };
  5671. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5672. var scope = this,
  5673. geometry = new THREE.Geometry(),
  5674. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5675. parseModel( scale );
  5676. parseSkin();
  5677. parseMorphing( scale );
  5678. geometry.computeCentroids();
  5679. geometry.computeFaceNormals();
  5680. function parseModel( scale ) {
  5681. function isBitSet( value, position ) {
  5682. return value & ( 1 << position );
  5683. }
  5684. var i, j, fi,
  5685. offset, zLength, nVertices,
  5686. colorIndex, normalIndex, uvIndex, materialIndex,
  5687. type,
  5688. isQuad,
  5689. hasMaterial,
  5690. hasFaceUv, hasFaceVertexUv,
  5691. hasFaceNormal, hasFaceVertexNormal,
  5692. hasFaceColor, hasFaceVertexColor,
  5693. vertex, face, color, normal,
  5694. uvLayer, uvs, u, v,
  5695. faces = json.faces,
  5696. vertices = json.vertices,
  5697. normals = json.normals,
  5698. colors = json.colors,
  5699. nUvLayers = 0;
  5700. // disregard empty arrays
  5701. for ( i = 0; i < json.uvs.length; i++ ) {
  5702. if ( json.uvs[ i ].length ) nUvLayers ++;
  5703. }
  5704. for ( i = 0; i < nUvLayers; i++ ) {
  5705. geometry.faceUvs[ i ] = [];
  5706. geometry.faceVertexUvs[ i ] = [];
  5707. }
  5708. offset = 0;
  5709. zLength = vertices.length;
  5710. while ( offset < zLength ) {
  5711. vertex = new THREE.Vector3();
  5712. vertex.x = vertices[ offset ++ ] * scale;
  5713. vertex.y = vertices[ offset ++ ] * scale;
  5714. vertex.z = vertices[ offset ++ ] * scale;
  5715. geometry.vertices.push( vertex );
  5716. }
  5717. offset = 0;
  5718. zLength = faces.length;
  5719. while ( offset < zLength ) {
  5720. type = faces[ offset ++ ];
  5721. isQuad = isBitSet( type, 0 );
  5722. hasMaterial = isBitSet( type, 1 );
  5723. hasFaceUv = isBitSet( type, 2 );
  5724. hasFaceVertexUv = isBitSet( type, 3 );
  5725. hasFaceNormal = isBitSet( type, 4 );
  5726. hasFaceVertexNormal = isBitSet( type, 5 );
  5727. hasFaceColor = isBitSet( type, 6 );
  5728. hasFaceVertexColor = isBitSet( type, 7 );
  5729. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5730. if ( isQuad ) {
  5731. face = new THREE.Face4();
  5732. face.a = faces[ offset ++ ];
  5733. face.b = faces[ offset ++ ];
  5734. face.c = faces[ offset ++ ];
  5735. face.d = faces[ offset ++ ];
  5736. nVertices = 4;
  5737. } else {
  5738. face = new THREE.Face3();
  5739. face.a = faces[ offset ++ ];
  5740. face.b = faces[ offset ++ ];
  5741. face.c = faces[ offset ++ ];
  5742. nVertices = 3;
  5743. }
  5744. if ( hasMaterial ) {
  5745. materialIndex = faces[ offset ++ ];
  5746. face.materialIndex = materialIndex;
  5747. }
  5748. // to get face <=> uv index correspondence
  5749. fi = geometry.faces.length;
  5750. if ( hasFaceUv ) {
  5751. for ( i = 0; i < nUvLayers; i++ ) {
  5752. uvLayer = json.uvs[ i ];
  5753. uvIndex = faces[ offset ++ ];
  5754. u = uvLayer[ uvIndex * 2 ];
  5755. v = uvLayer[ uvIndex * 2 + 1 ];
  5756. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5757. }
  5758. }
  5759. if ( hasFaceVertexUv ) {
  5760. for ( i = 0; i < nUvLayers; i++ ) {
  5761. uvLayer = json.uvs[ i ];
  5762. uvs = [];
  5763. for ( j = 0; j < nVertices; j ++ ) {
  5764. uvIndex = faces[ offset ++ ];
  5765. u = uvLayer[ uvIndex * 2 ];
  5766. v = uvLayer[ uvIndex * 2 + 1 ];
  5767. uvs[ j ] = new THREE.Vector2( u, v );
  5768. }
  5769. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5770. }
  5771. }
  5772. if ( hasFaceNormal ) {
  5773. normalIndex = faces[ offset ++ ] * 3;
  5774. normal = new THREE.Vector3();
  5775. normal.x = normals[ normalIndex ++ ];
  5776. normal.y = normals[ normalIndex ++ ];
  5777. normal.z = normals[ normalIndex ];
  5778. face.normal = normal;
  5779. }
  5780. if ( hasFaceVertexNormal ) {
  5781. for ( i = 0; i < nVertices; i++ ) {
  5782. normalIndex = faces[ offset ++ ] * 3;
  5783. normal = new THREE.Vector3();
  5784. normal.x = normals[ normalIndex ++ ];
  5785. normal.y = normals[ normalIndex ++ ];
  5786. normal.z = normals[ normalIndex ];
  5787. face.vertexNormals.push( normal );
  5788. }
  5789. }
  5790. if ( hasFaceColor ) {
  5791. colorIndex = faces[ offset ++ ];
  5792. color = new THREE.Color( colors[ colorIndex ] );
  5793. face.color = color;
  5794. }
  5795. if ( hasFaceVertexColor ) {
  5796. for ( i = 0; i < nVertices; i++ ) {
  5797. colorIndex = faces[ offset ++ ];
  5798. color = new THREE.Color( colors[ colorIndex ] );
  5799. face.vertexColors.push( color );
  5800. }
  5801. }
  5802. geometry.faces.push( face );
  5803. }
  5804. };
  5805. function parseSkin() {
  5806. var i, l, x, y, z, w, a, b, c, d;
  5807. if ( json.skinWeights ) {
  5808. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5809. x = json.skinWeights[ i ];
  5810. y = json.skinWeights[ i + 1 ];
  5811. z = 0;
  5812. w = 0;
  5813. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5814. }
  5815. }
  5816. if ( json.skinIndices ) {
  5817. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5818. a = json.skinIndices[ i ];
  5819. b = json.skinIndices[ i + 1 ];
  5820. c = 0;
  5821. d = 0;
  5822. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5823. }
  5824. }
  5825. geometry.bones = json.bones;
  5826. geometry.animation = json.animation;
  5827. };
  5828. function parseMorphing( scale ) {
  5829. if ( json.morphTargets !== undefined ) {
  5830. var i, l, v, vl, dstVertices, srcVertices;
  5831. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5832. geometry.morphTargets[ i ] = {};
  5833. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5834. geometry.morphTargets[ i ].vertices = [];
  5835. dstVertices = geometry.morphTargets[ i ].vertices;
  5836. srcVertices = json.morphTargets [ i ].vertices;
  5837. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5838. var vertex = new THREE.Vector3();
  5839. vertex.x = srcVertices[ v ] * scale;
  5840. vertex.y = srcVertices[ v + 1 ] * scale;
  5841. vertex.z = srcVertices[ v + 2 ] * scale;
  5842. dstVertices.push( vertex );
  5843. }
  5844. }
  5845. }
  5846. if ( json.morphColors !== undefined ) {
  5847. var i, l, c, cl, dstColors, srcColors, color;
  5848. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5849. geometry.morphColors[ i ] = {};
  5850. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5851. geometry.morphColors[ i ].colors = [];
  5852. dstColors = geometry.morphColors[ i ].colors;
  5853. srcColors = json.morphColors [ i ].colors;
  5854. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5855. color = new THREE.Color( 0xffaa00 );
  5856. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5857. dstColors.push( color );
  5858. }
  5859. }
  5860. }
  5861. };
  5862. var materials = this.initMaterials( json.materials, texturePath );
  5863. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5864. callback( geometry, materials );
  5865. };
  5866. /**
  5867. * @author mrdoob / http://mrdoob.com/
  5868. */
  5869. THREE.LoadingMonitor = function () {
  5870. THREE.EventTarget.call( this );
  5871. var scope = this;
  5872. var loaded = 0;
  5873. var total = 0;
  5874. var onLoad = function ( event ) {
  5875. loaded ++;
  5876. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5877. if ( loaded === total ) {
  5878. scope.dispatchEvent( { type: 'load' } );
  5879. }
  5880. };
  5881. this.add = function ( loader ) {
  5882. total ++;
  5883. loader.addEventListener( 'load', onLoad, false );
  5884. };
  5885. };
  5886. /**
  5887. * @author alteredq / http://alteredqualia.com/
  5888. */
  5889. THREE.SceneLoader = function () {
  5890. this.onLoadStart = function () {};
  5891. this.onLoadProgress = function() {};
  5892. this.onLoadComplete = function () {};
  5893. this.callbackSync = function () {};
  5894. this.callbackProgress = function () {};
  5895. this.geometryHandlerMap = {};
  5896. this.hierarchyHandlerMap = {};
  5897. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5898. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5899. };
  5900. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5901. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5902. var scope = this;
  5903. var xhr = new XMLHttpRequest();
  5904. xhr.onreadystatechange = function () {
  5905. if ( xhr.readyState === 4 ) {
  5906. if ( xhr.status === 200 || xhr.status === 0 ) {
  5907. var json = JSON.parse( xhr.responseText );
  5908. scope.parse( json, callbackFinished, url );
  5909. } else {
  5910. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5911. }
  5912. }
  5913. };
  5914. xhr.open( "GET", url, true );
  5915. xhr.send( null );
  5916. };
  5917. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5918. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5919. };
  5920. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5921. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5922. };
  5923. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5924. var scope = this;
  5925. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5926. var geometry, material, camera, fog,
  5927. texture, images, color,
  5928. light, hex, intensity,
  5929. counter_models, counter_textures,
  5930. total_models, total_textures,
  5931. result;
  5932. var target_array = [];
  5933. var data = json;
  5934. // async geometry loaders
  5935. for ( var typeID in this.geometryHandlerMap ) {
  5936. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5937. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5938. }
  5939. // async hierachy loaders
  5940. for ( var typeID in this.hierarchyHandlerMap ) {
  5941. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5942. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5943. }
  5944. counter_models = 0;
  5945. counter_textures = 0;
  5946. result = {
  5947. scene: new THREE.Scene(),
  5948. geometries: {},
  5949. face_materials: {},
  5950. materials: {},
  5951. textures: {},
  5952. objects: {},
  5953. cameras: {},
  5954. lights: {},
  5955. fogs: {},
  5956. empties: {}
  5957. };
  5958. if ( data.transform ) {
  5959. var position = data.transform.position,
  5960. rotation = data.transform.rotation,
  5961. scale = data.transform.scale;
  5962. if ( position )
  5963. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5964. if ( rotation )
  5965. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5966. if ( scale )
  5967. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5968. if ( position || rotation || scale ) {
  5969. result.scene.updateMatrix();
  5970. result.scene.updateMatrixWorld();
  5971. }
  5972. }
  5973. function get_url( source_url, url_type ) {
  5974. if ( url_type == "relativeToHTML" ) {
  5975. return source_url;
  5976. } else {
  5977. return urlBase + "/" + source_url;
  5978. }
  5979. };
  5980. // toplevel loader function, delegates to handle_children
  5981. function handle_objects() {
  5982. handle_children( result.scene, data.objects );
  5983. }
  5984. // handle all the children from the loaded json and attach them to given parent
  5985. function handle_children( parent, children ) {
  5986. var mat, dst, pos, rot, scl, quat;
  5987. for ( var objID in children ) {
  5988. // check by id if child has already been handled,
  5989. // if not, create new object
  5990. if ( result.objects[ objID ] === undefined ) {
  5991. var objJSON = children[ objID ];
  5992. var object = null;
  5993. // meshes
  5994. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) && objJSON.loading === undefined ) {
  5995. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  5996. "position": 1, "rotation": 1, "scale" : 1,
  5997. "visible": 1, "children": 1, "properties": 1,
  5998. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  5999. var loaderParameters = {};
  6000. for ( var parType in objJSON ) {
  6001. if ( ! ( parType in reservedTypes ) ) {
  6002. loaderParameters[ parType ] = objJSON[ parType ];
  6003. }
  6004. }
  6005. material = result.materials[ objJSON.material ];
  6006. objJSON.loading = true;
  6007. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6008. // OBJLoader
  6009. if ( loader.addEventListener ) {
  6010. loader.addEventListener( 'load', create_callback_hierachy( objID, parent, material, objJSON ) );
  6011. loader.load( get_url( objJSON.url, data.urlBaseType ) );
  6012. } else {
  6013. // ColladaLoader
  6014. if ( loader.options ) {
  6015. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6016. // UTF8Loader
  6017. } else {
  6018. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6019. }
  6020. }
  6021. } else if ( objJSON.geometry !== undefined ) {
  6022. geometry = result.geometries[ objJSON.geometry ];
  6023. // geometry already loaded
  6024. if ( geometry ) {
  6025. var needsTangents = false;
  6026. material = result.materials[ objJSON.material ];
  6027. needsTangents = material instanceof THREE.ShaderMaterial;
  6028. pos = objJSON.position;
  6029. rot = objJSON.rotation;
  6030. scl = objJSON.scale;
  6031. mat = objJSON.matrix;
  6032. quat = objJSON.quaternion;
  6033. // turn off quaternions, for the moment
  6034. quat = 0;
  6035. // use materials from the model file
  6036. // if there is no material specified in the object
  6037. if ( ! objJSON.material ) {
  6038. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6039. }
  6040. // use materials from the model file
  6041. // if there is just empty face material
  6042. // (must create new material as each model has its own face material)
  6043. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6044. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6045. }
  6046. if ( material instanceof THREE.MeshFaceMaterial ) {
  6047. for ( var i = 0; i < material.materials.length; i ++ ) {
  6048. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6049. }
  6050. }
  6051. if ( needsTangents ) {
  6052. geometry.computeTangents();
  6053. }
  6054. if ( objJSON.skin ) {
  6055. object = new THREE.SkinnedMesh( geometry, material );
  6056. } else if ( objJSON.morph ) {
  6057. object = new THREE.MorphAnimMesh( geometry, material );
  6058. if ( objJSON.duration !== undefined ) {
  6059. object.duration = objJSON.duration;
  6060. }
  6061. if ( objJSON.time !== undefined ) {
  6062. object.time = objJSON.time;
  6063. }
  6064. if ( objJSON.mirroredLoop !== undefined ) {
  6065. object.mirroredLoop = objJSON.mirroredLoop;
  6066. }
  6067. if ( material.morphNormals ) {
  6068. geometry.computeMorphNormals();
  6069. }
  6070. } else {
  6071. object = new THREE.Mesh( geometry, material );
  6072. }
  6073. object.name = objID;
  6074. if ( mat ) {
  6075. object.matrixAutoUpdate = false;
  6076. object.matrix.set(
  6077. mat[0], mat[1], mat[2], mat[3],
  6078. mat[4], mat[5], mat[6], mat[7],
  6079. mat[8], mat[9], mat[10], mat[11],
  6080. mat[12], mat[13], mat[14], mat[15]
  6081. );
  6082. } else {
  6083. object.position.set( pos[0], pos[1], pos[2] );
  6084. if ( quat ) {
  6085. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6086. object.useQuaternion = true;
  6087. } else {
  6088. object.rotation.set( rot[0], rot[1], rot[2] );
  6089. }
  6090. object.scale.set( scl[0], scl[1], scl[2] );
  6091. }
  6092. object.visible = objJSON.visible;
  6093. object.castShadow = objJSON.castShadow;
  6094. object.receiveShadow = objJSON.receiveShadow;
  6095. parent.add( object );
  6096. result.objects[ objID ] = object;
  6097. }
  6098. // lights
  6099. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6100. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6101. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6102. if ( objJSON.type === "DirectionalLight" ) {
  6103. pos = objJSON.direction;
  6104. light = new THREE.DirectionalLight( hex, intensity );
  6105. light.position.set( pos[0], pos[1], pos[2] );
  6106. if ( objJSON.target ) {
  6107. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6108. // kill existing default target
  6109. // otherwise it gets added to scene when parent gets added
  6110. light.target = null;
  6111. }
  6112. } else if ( objJSON.type === "PointLight" ) {
  6113. pos = objJSON.position;
  6114. dst = objJSON.distance;
  6115. light = new THREE.PointLight( hex, intensity, dst );
  6116. light.position.set( pos[0], pos[1], pos[2] );
  6117. } else if ( objJSON.type === "AmbientLight" ) {
  6118. light = new THREE.AmbientLight( hex );
  6119. }
  6120. parent.add( light );
  6121. light.name = objID;
  6122. result.lights[ objID ] = light;
  6123. result.objects[ objID ] = light;
  6124. // cameras
  6125. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6126. if ( objJSON.type === "PerspectiveCamera" ) {
  6127. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6128. } else if ( objJSON.type === "OrthographicCamera" ) {
  6129. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6130. }
  6131. pos = objJSON.position;
  6132. camera.position.set( pos[0], pos[1], pos[2] );
  6133. parent.add( camera );
  6134. camera.name = objID;
  6135. result.cameras[ objID ] = camera;
  6136. result.objects[ objID ] = camera;
  6137. // pure Object3D
  6138. } else {
  6139. pos = objJSON.position;
  6140. rot = objJSON.rotation;
  6141. scl = objJSON.scale;
  6142. quat = objJSON.quaternion;
  6143. // turn off quaternions, for the moment
  6144. quat = 0;
  6145. object = new THREE.Object3D();
  6146. object.name = objID;
  6147. object.position.set( pos[0], pos[1], pos[2] );
  6148. if ( quat ) {
  6149. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6150. object.useQuaternion = true;
  6151. } else {
  6152. object.rotation.set( rot[0], rot[1], rot[2] );
  6153. }
  6154. object.scale.set( scl[0], scl[1], scl[2] );
  6155. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6156. parent.add( object );
  6157. result.objects[ objID ] = object;
  6158. result.empties[ objID ] = object;
  6159. }
  6160. if ( object ) {
  6161. if ( objJSON.properties !== undefined ) {
  6162. for ( var key in objJSON.properties ) {
  6163. var value = objJSON.properties[ key ];
  6164. object.properties[ key ] = value;
  6165. }
  6166. }
  6167. if ( objJSON.children !== undefined ) {
  6168. handle_children( object, objJSON.children );
  6169. }
  6170. }
  6171. }
  6172. }
  6173. };
  6174. function handle_mesh( geo, mat, id ) {
  6175. result.geometries[ id ] = geo;
  6176. result.face_materials[ id ] = mat;
  6177. handle_objects();
  6178. };
  6179. function handle_hierarchy( node, id, parent, material, obj ) {
  6180. var p = obj.position;
  6181. var r = obj.rotation;
  6182. var q = obj.quaternion;
  6183. var s = obj.scale;
  6184. node.position.set( p[0], p[1], p[2] );
  6185. if ( q ) {
  6186. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6187. node.useQuaternion = true;
  6188. } else {
  6189. node.rotation.set( r[0], r[1], r[2] );
  6190. }
  6191. node.scale.set( s[0], s[1], s[2] );
  6192. if ( material ) {
  6193. node.traverse( function ( child ) {
  6194. child.material = material;
  6195. } );
  6196. }
  6197. parent.add( node );
  6198. result.objects[ id ] = node;
  6199. handle_objects();
  6200. };
  6201. function create_callback_geometry( id ) {
  6202. return function( geo, mat ) {
  6203. handle_mesh( geo, mat, id );
  6204. counter_models -= 1;
  6205. scope.onLoadComplete();
  6206. async_callback_gate();
  6207. }
  6208. };
  6209. function create_callback_hierachy( id, parent, material, obj ) {
  6210. return function( event ) {
  6211. var result;
  6212. // loaders which use EventTarget
  6213. if ( event.content ) {
  6214. result = event.content;
  6215. // ColladaLoader
  6216. } else if ( event.dae ) {
  6217. result = event.scene;
  6218. // UTF8Loader
  6219. } else {
  6220. result = event;
  6221. }
  6222. handle_hierarchy( result, id, parent, material, obj );
  6223. counter_models -= 1;
  6224. scope.onLoadComplete();
  6225. async_callback_gate();
  6226. }
  6227. };
  6228. function create_callback_embed( id ) {
  6229. return function( geo, mat ) {
  6230. result.geometries[ id ] = geo;
  6231. result.face_materials[ id ] = mat;
  6232. }
  6233. };
  6234. function async_callback_gate() {
  6235. var progress = {
  6236. totalModels : total_models,
  6237. totalTextures : total_textures,
  6238. loadedModels : total_models - counter_models,
  6239. loadedTextures : total_textures - counter_textures
  6240. };
  6241. scope.callbackProgress( progress, result );
  6242. scope.onLoadProgress();
  6243. if ( counter_models === 0 && counter_textures === 0 ) {
  6244. finalize();
  6245. callbackFinished( result );
  6246. }
  6247. };
  6248. function finalize() {
  6249. // take care of targets which could be asynchronously loaded objects
  6250. for ( var i = 0; i < target_array.length; i ++ ) {
  6251. var ta = target_array[ i ];
  6252. var target = result.objects[ ta.targetName ];
  6253. if ( target ) {
  6254. ta.object.target = target;
  6255. } else {
  6256. // if there was error and target of specified name doesn't exist in the scene file
  6257. // create instead dummy target
  6258. // (target must be added to scene explicitly as parent is already added)
  6259. ta.object.target = new THREE.Object3D();
  6260. result.scene.add( ta.object.target );
  6261. }
  6262. ta.object.target.properties.targetInverse = ta.object;
  6263. }
  6264. };
  6265. var callbackTexture = function ( count ) {
  6266. counter_textures -= count;
  6267. async_callback_gate();
  6268. scope.onLoadComplete();
  6269. };
  6270. // must use this instead of just directly calling callbackTexture
  6271. // because of closure in the calling context loop
  6272. var generateTextureCallback = function ( count ) {
  6273. return function() {
  6274. callbackTexture( count );
  6275. };
  6276. };
  6277. // first go synchronous elements
  6278. // fogs
  6279. var fogID, fogJSON;
  6280. for ( fogID in data.fogs ) {
  6281. fogJSON = data.fogs[ fogID ];
  6282. if ( fogJSON.type === "linear" ) {
  6283. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6284. } else if ( fogJSON.type === "exp2" ) {
  6285. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6286. }
  6287. color = fogJSON.color;
  6288. fog.color.setRGB( color[0], color[1], color[2] );
  6289. result.fogs[ fogID ] = fog;
  6290. }
  6291. // now come potentially asynchronous elements
  6292. // geometries
  6293. // count how many geometries will be loaded asynchronously
  6294. var geoID, geoJSON;
  6295. for ( geoID in data.geometries ) {
  6296. geoJSON = data.geometries[ geoID ];
  6297. if ( geoJSON.type in this.geometryHandlerMap ) {
  6298. counter_models += 1;
  6299. scope.onLoadStart();
  6300. }
  6301. }
  6302. // count how many hierarchies will be loaded asynchronously
  6303. var objID, objJSON;
  6304. for ( objID in data.objects ) {
  6305. objJSON = data.objects[ objID ];
  6306. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6307. counter_models += 1;
  6308. scope.onLoadStart();
  6309. }
  6310. }
  6311. total_models = counter_models;
  6312. for ( geoID in data.geometries ) {
  6313. geoJSON = data.geometries[ geoID ];
  6314. if ( geoJSON.type === "cube" ) {
  6315. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6316. result.geometries[ geoID ] = geometry;
  6317. } else if ( geoJSON.type === "plane" ) {
  6318. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6319. result.geometries[ geoID ] = geometry;
  6320. } else if ( geoJSON.type === "sphere" ) {
  6321. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6322. result.geometries[ geoID ] = geometry;
  6323. } else if ( geoJSON.type === "cylinder" ) {
  6324. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6325. result.geometries[ geoID ] = geometry;
  6326. } else if ( geoJSON.type === "torus" ) {
  6327. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6328. result.geometries[ geoID ] = geometry;
  6329. } else if ( geoJSON.type === "icosahedron" ) {
  6330. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6331. result.geometries[ geoID ] = geometry;
  6332. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6333. var loaderParameters = {};
  6334. for ( var parType in geoJSON ) {
  6335. if ( parType !== "type" && parType !== "url" ) {
  6336. loaderParameters[ parType ] = geoJSON[ parType ];
  6337. }
  6338. }
  6339. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6340. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6341. } else if ( geoJSON.type === "embedded" ) {
  6342. var modelJson = data.embeds[ geoJSON.id ],
  6343. texture_path = "";
  6344. // pass metadata along to jsonLoader so it knows the format version
  6345. modelJson.metadata = data.metadata;
  6346. if ( modelJson ) {
  6347. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6348. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6349. }
  6350. }
  6351. }
  6352. // textures
  6353. // count how many textures will be loaded asynchronously
  6354. var textureID, textureJSON;
  6355. for ( textureID in data.textures ) {
  6356. textureJSON = data.textures[ textureID ];
  6357. if ( textureJSON.url instanceof Array ) {
  6358. counter_textures += textureJSON.url.length;
  6359. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6360. scope.onLoadStart();
  6361. }
  6362. } else {
  6363. counter_textures += 1;
  6364. scope.onLoadStart();
  6365. }
  6366. }
  6367. total_textures = counter_textures;
  6368. for ( textureID in data.textures ) {
  6369. textureJSON = data.textures[ textureID ];
  6370. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6371. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6372. }
  6373. if ( textureJSON.url instanceof Array ) {
  6374. var count = textureJSON.url.length;
  6375. var url_array = [];
  6376. for( var i = 0; i < count; i ++ ) {
  6377. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6378. }
  6379. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6380. if ( isCompressed ) {
  6381. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6382. } else {
  6383. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6384. }
  6385. } else {
  6386. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6387. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6388. var textureCallback = generateTextureCallback( 1 );
  6389. if ( isCompressed ) {
  6390. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6391. } else {
  6392. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6393. }
  6394. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6395. texture.minFilter = THREE[ textureJSON.minFilter ];
  6396. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6397. texture.magFilter = THREE[ textureJSON.magFilter ];
  6398. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6399. if ( textureJSON.repeat ) {
  6400. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6401. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6402. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6403. }
  6404. if ( textureJSON.offset ) {
  6405. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6406. }
  6407. // handle wrap after repeat so that default repeat can be overriden
  6408. if ( textureJSON.wrap ) {
  6409. var wrapMap = {
  6410. "repeat" : THREE.RepeatWrapping,
  6411. "mirror" : THREE.MirroredRepeatWrapping
  6412. }
  6413. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6414. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6415. }
  6416. }
  6417. result.textures[ textureID ] = texture;
  6418. }
  6419. // materials
  6420. var matID, matJSON;
  6421. var parID;
  6422. for ( matID in data.materials ) {
  6423. matJSON = data.materials[ matID ];
  6424. for ( parID in matJSON.parameters ) {
  6425. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6426. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6427. } else if ( parID === "shading" ) {
  6428. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6429. } else if ( parID === "side" ) {
  6430. if ( matJSON.parameters[ parID ] == "double" ) {
  6431. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6432. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6433. matJSON.parameters[ parID ] = THREE.BackSide;
  6434. } else {
  6435. matJSON.parameters[ parID ] = THREE.FrontSide;
  6436. }
  6437. } else if ( parID === "blending" ) {
  6438. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6439. } else if ( parID === "combine" ) {
  6440. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  6441. } else if ( parID === "vertexColors" ) {
  6442. if ( matJSON.parameters[ parID ] == "face" ) {
  6443. matJSON.parameters[ parID ] = THREE.FaceColors;
  6444. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6445. } else if ( matJSON.parameters[ parID ] ) {
  6446. matJSON.parameters[ parID ] = THREE.VertexColors;
  6447. }
  6448. } else if ( parID === "wrapRGB" ) {
  6449. var v3 = matJSON.parameters[ parID ];
  6450. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6451. }
  6452. }
  6453. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6454. matJSON.parameters.transparent = true;
  6455. }
  6456. if ( matJSON.parameters.normalMap ) {
  6457. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6458. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6459. var diffuse = matJSON.parameters.color;
  6460. var specular = matJSON.parameters.specular;
  6461. var ambient = matJSON.parameters.ambient;
  6462. var shininess = matJSON.parameters.shininess;
  6463. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6464. if ( matJSON.parameters.normalScale ) {
  6465. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6466. }
  6467. if ( matJSON.parameters.map ) {
  6468. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6469. uniforms[ "enableDiffuse" ].value = true;
  6470. }
  6471. if ( matJSON.parameters.envMap ) {
  6472. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6473. uniforms[ "enableReflection" ].value = true;
  6474. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6475. }
  6476. if ( matJSON.parameters.lightMap ) {
  6477. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6478. uniforms[ "enableAO" ].value = true;
  6479. }
  6480. if ( matJSON.parameters.specularMap ) {
  6481. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6482. uniforms[ "enableSpecular" ].value = true;
  6483. }
  6484. if ( matJSON.parameters.displacementMap ) {
  6485. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6486. uniforms[ "enableDisplacement" ].value = true;
  6487. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6488. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6489. }
  6490. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6491. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6492. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6493. uniforms[ "uShininess" ].value = shininess;
  6494. if ( matJSON.parameters.opacity ) {
  6495. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6496. }
  6497. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6498. material = new THREE.ShaderMaterial( parameters );
  6499. } else {
  6500. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6501. }
  6502. result.materials[ matID ] = material;
  6503. }
  6504. // second pass through all materials to initialize MeshFaceMaterials
  6505. // that could be referring to other materials out of order
  6506. for ( matID in data.materials ) {
  6507. matJSON = data.materials[ matID ];
  6508. if ( matJSON.parameters.materials ) {
  6509. var materialArray = [];
  6510. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6511. var label = matJSON.parameters.materials[ i ];
  6512. materialArray.push( result.materials[ label ] );
  6513. }
  6514. result.materials[ matID ].materials = materialArray;
  6515. }
  6516. }
  6517. // objects ( synchronous init of procedural primitives )
  6518. handle_objects();
  6519. // defaults
  6520. if ( result.cameras && data.defaults.camera ) {
  6521. result.currentCamera = result.cameras[ data.defaults.camera ];
  6522. }
  6523. if ( result.fogs && data.defaults.fog ) {
  6524. result.scene.fog = result.fogs[ data.defaults.fog ];
  6525. }
  6526. color = data.defaults.bgcolor;
  6527. result.bgColor = new THREE.Color();
  6528. result.bgColor.setRGB( color[0], color[1], color[2] );
  6529. result.bgColorAlpha = data.defaults.bgalpha;
  6530. // synchronous callback
  6531. scope.callbackSync( result );
  6532. // just in case there are no async elements
  6533. async_callback_gate();
  6534. };
  6535. /**
  6536. * @author mrdoob / http://mrdoob.com/
  6537. */
  6538. THREE.TextureLoader = function () {
  6539. THREE.EventTarget.call( this );
  6540. this.crossOrigin = null;
  6541. };
  6542. THREE.TextureLoader.prototype = {
  6543. constructor: THREE.TextureLoader,
  6544. load: function ( url ) {
  6545. var scope = this;
  6546. var image = new Image();
  6547. image.addEventListener( 'load', function () {
  6548. var texture = new THREE.Texture( image );
  6549. texture.needsUpdate = true;
  6550. scope.dispatchEvent( { type: 'load', content: texture } );
  6551. }, false );
  6552. image.addEventListener( 'error', function () {
  6553. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6554. }, false );
  6555. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6556. image.src = url;
  6557. }
  6558. }
  6559. /**
  6560. * @author mrdoob / http://mrdoob.com/
  6561. * @author alteredq / http://alteredqualia.com/
  6562. */
  6563. THREE.Material = function () {
  6564. this.id = THREE.MaterialIdCount ++;
  6565. this.name = '';
  6566. this.side = THREE.FrontSide;
  6567. this.opacity = 1;
  6568. this.transparent = false;
  6569. this.blending = THREE.NormalBlending;
  6570. this.blendSrc = THREE.SrcAlphaFactor;
  6571. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6572. this.blendEquation = THREE.AddEquation;
  6573. this.depthTest = true;
  6574. this.depthWrite = true;
  6575. this.polygonOffset = false;
  6576. this.polygonOffsetFactor = 0;
  6577. this.polygonOffsetUnits = 0;
  6578. this.alphaTest = 0;
  6579. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6580. this.visible = true;
  6581. this.needsUpdate = true;
  6582. };
  6583. THREE.Material.prototype.setValues = function ( values ) {
  6584. if ( values === undefined ) return;
  6585. for ( var key in values ) {
  6586. var newValue = values[ key ];
  6587. if ( newValue === undefined ) {
  6588. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6589. continue;
  6590. }
  6591. if ( key in this ) {
  6592. var currentValue = this[ key ];
  6593. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6594. currentValue.copy( newValue );
  6595. } else if ( currentValue instanceof THREE.Color ) {
  6596. currentValue.set( newValue );
  6597. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6598. currentValue.copy( newValue );
  6599. } else {
  6600. this[ key ] = newValue;
  6601. }
  6602. }
  6603. }
  6604. };
  6605. THREE.Material.prototype.clone = function ( material ) {
  6606. if ( material === undefined ) material = new THREE.Material();
  6607. material.name = this.name;
  6608. material.side = this.side;
  6609. material.opacity = this.opacity;
  6610. material.transparent = this.transparent;
  6611. material.blending = this.blending;
  6612. material.blendSrc = this.blendSrc;
  6613. material.blendDst = this.blendDst;
  6614. material.blendEquation = this.blendEquation;
  6615. material.depthTest = this.depthTest;
  6616. material.depthWrite = this.depthWrite;
  6617. material.polygonOffset = this.polygonOffset;
  6618. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6619. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6620. material.alphaTest = this.alphaTest;
  6621. material.overdraw = this.overdraw;
  6622. material.visible = this.visible;
  6623. return material;
  6624. };
  6625. THREE.MaterialIdCount = 0;
  6626. /**
  6627. * @author mrdoob / http://mrdoob.com/
  6628. * @author alteredq / http://alteredqualia.com/
  6629. *
  6630. * parameters = {
  6631. * color: <hex>,
  6632. * opacity: <float>,
  6633. *
  6634. * blending: THREE.NormalBlending,
  6635. * depthTest: <bool>,
  6636. * depthWrite: <bool>,
  6637. *
  6638. * linewidth: <float>,
  6639. * linecap: "round",
  6640. * linejoin: "round",
  6641. *
  6642. * vertexColors: <bool>
  6643. *
  6644. * fog: <bool>
  6645. * }
  6646. */
  6647. THREE.LineBasicMaterial = function ( parameters ) {
  6648. THREE.Material.call( this );
  6649. this.color = new THREE.Color( 0xffffff );
  6650. this.linewidth = 1;
  6651. this.linecap = 'round';
  6652. this.linejoin = 'round';
  6653. this.vertexColors = false;
  6654. this.fog = true;
  6655. this.setValues( parameters );
  6656. };
  6657. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6658. THREE.LineBasicMaterial.prototype.clone = function () {
  6659. var material = new THREE.LineBasicMaterial();
  6660. THREE.Material.prototype.clone.call( this, material );
  6661. material.color.copy( this.color );
  6662. material.linewidth = this.linewidth;
  6663. material.linecap = this.linecap;
  6664. material.linejoin = this.linejoin;
  6665. material.vertexColors = this.vertexColors;
  6666. material.fog = this.fog;
  6667. return material;
  6668. };
  6669. /**
  6670. * @author alteredq / http://alteredqualia.com/
  6671. *
  6672. * parameters = {
  6673. * color: <hex>,
  6674. * opacity: <float>,
  6675. *
  6676. * blending: THREE.NormalBlending,
  6677. * depthTest: <bool>,
  6678. * depthWrite: <bool>,
  6679. *
  6680. * linewidth: <float>,
  6681. *
  6682. * scale: <float>,
  6683. * dashSize: <float>,
  6684. * gapSize: <float>,
  6685. *
  6686. * vertexColors: <bool>
  6687. *
  6688. * fog: <bool>
  6689. * }
  6690. */
  6691. THREE.LineDashedMaterial = function ( parameters ) {
  6692. THREE.Material.call( this );
  6693. this.color = new THREE.Color( 0xffffff );
  6694. this.linewidth = 1;
  6695. this.scale = 1;
  6696. this.dashSize = 3;
  6697. this.gapSize = 1;
  6698. this.vertexColors = false;
  6699. this.fog = true;
  6700. this.setValues( parameters );
  6701. };
  6702. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6703. THREE.LineDashedMaterial.prototype.clone = function () {
  6704. var material = new THREE.LineDashedMaterial();
  6705. THREE.Material.prototype.clone.call( this, material );
  6706. material.color.copy( this.color );
  6707. material.linewidth = this.linewidth;
  6708. material.scale = this.scale;
  6709. material.dashSize = this.dashSize;
  6710. material.gapSize = this.gapSize;
  6711. material.vertexColors = this.vertexColors;
  6712. material.fog = this.fog;
  6713. return material;
  6714. };
  6715. /**
  6716. * @author mrdoob / http://mrdoob.com/
  6717. * @author alteredq / http://alteredqualia.com/
  6718. *
  6719. * parameters = {
  6720. * color: <hex>,
  6721. * opacity: <float>,
  6722. * map: new THREE.Texture( <Image> ),
  6723. *
  6724. * lightMap: new THREE.Texture( <Image> ),
  6725. *
  6726. * specularMap: new THREE.Texture( <Image> ),
  6727. *
  6728. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6729. * combine: THREE.Multiply,
  6730. * reflectivity: <float>,
  6731. * refractionRatio: <float>,
  6732. *
  6733. * shading: THREE.SmoothShading,
  6734. * blending: THREE.NormalBlending,
  6735. * depthTest: <bool>,
  6736. * depthWrite: <bool>,
  6737. *
  6738. * wireframe: <boolean>,
  6739. * wireframeLinewidth: <float>,
  6740. *
  6741. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6742. *
  6743. * skinning: <bool>,
  6744. * morphTargets: <bool>,
  6745. *
  6746. * fog: <bool>
  6747. * }
  6748. */
  6749. THREE.MeshBasicMaterial = function ( parameters ) {
  6750. THREE.Material.call( this );
  6751. this.color = new THREE.Color( 0xffffff ); // emissive
  6752. this.map = null;
  6753. this.lightMap = null;
  6754. this.specularMap = null;
  6755. this.envMap = null;
  6756. this.combine = THREE.MultiplyOperation;
  6757. this.reflectivity = 1;
  6758. this.refractionRatio = 0.98;
  6759. this.fog = true;
  6760. this.shading = THREE.SmoothShading;
  6761. this.wireframe = false;
  6762. this.wireframeLinewidth = 1;
  6763. this.wireframeLinecap = 'round';
  6764. this.wireframeLinejoin = 'round';
  6765. this.vertexColors = THREE.NoColors;
  6766. this.skinning = false;
  6767. this.morphTargets = false;
  6768. this.setValues( parameters );
  6769. };
  6770. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6771. THREE.MeshBasicMaterial.prototype.clone = function () {
  6772. var material = new THREE.MeshBasicMaterial();
  6773. THREE.Material.prototype.clone.call( this, material );
  6774. material.color.copy( this.color );
  6775. material.map = this.map;
  6776. material.lightMap = this.lightMap;
  6777. material.specularMap = this.specularMap;
  6778. material.envMap = this.envMap;
  6779. material.combine = this.combine;
  6780. material.reflectivity = this.reflectivity;
  6781. material.refractionRatio = this.refractionRatio;
  6782. material.fog = this.fog;
  6783. material.shading = this.shading;
  6784. material.wireframe = this.wireframe;
  6785. material.wireframeLinewidth = this.wireframeLinewidth;
  6786. material.wireframeLinecap = this.wireframeLinecap;
  6787. material.wireframeLinejoin = this.wireframeLinejoin;
  6788. material.vertexColors = this.vertexColors;
  6789. material.skinning = this.skinning;
  6790. material.morphTargets = this.morphTargets;
  6791. return material;
  6792. };
  6793. /**
  6794. * @author mrdoob / http://mrdoob.com/
  6795. * @author alteredq / http://alteredqualia.com/
  6796. *
  6797. * parameters = {
  6798. * color: <hex>,
  6799. * ambient: <hex>,
  6800. * emissive: <hex>,
  6801. * opacity: <float>,
  6802. *
  6803. * map: new THREE.Texture( <Image> ),
  6804. *
  6805. * lightMap: new THREE.Texture( <Image> ),
  6806. *
  6807. * specularMap: new THREE.Texture( <Image> ),
  6808. *
  6809. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6810. * combine: THREE.Multiply,
  6811. * reflectivity: <float>,
  6812. * refractionRatio: <float>,
  6813. *
  6814. * shading: THREE.SmoothShading,
  6815. * blending: THREE.NormalBlending,
  6816. * depthTest: <bool>,
  6817. * depthWrite: <bool>,
  6818. *
  6819. * wireframe: <boolean>,
  6820. * wireframeLinewidth: <float>,
  6821. *
  6822. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6823. *
  6824. * skinning: <bool>,
  6825. * morphTargets: <bool>,
  6826. * morphNormals: <bool>,
  6827. *
  6828. * fog: <bool>
  6829. * }
  6830. */
  6831. THREE.MeshLambertMaterial = function ( parameters ) {
  6832. THREE.Material.call( this );
  6833. this.color = new THREE.Color( 0xffffff ); // diffuse
  6834. this.ambient = new THREE.Color( 0xffffff );
  6835. this.emissive = new THREE.Color( 0x000000 );
  6836. this.wrapAround = false;
  6837. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6838. this.map = null;
  6839. this.lightMap = null;
  6840. this.specularMap = null;
  6841. this.envMap = null;
  6842. this.combine = THREE.MultiplyOperation;
  6843. this.reflectivity = 1;
  6844. this.refractionRatio = 0.98;
  6845. this.fog = true;
  6846. this.shading = THREE.SmoothShading;
  6847. this.wireframe = false;
  6848. this.wireframeLinewidth = 1;
  6849. this.wireframeLinecap = 'round';
  6850. this.wireframeLinejoin = 'round';
  6851. this.vertexColors = THREE.NoColors;
  6852. this.skinning = false;
  6853. this.morphTargets = false;
  6854. this.morphNormals = false;
  6855. this.setValues( parameters );
  6856. };
  6857. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6858. THREE.MeshLambertMaterial.prototype.clone = function () {
  6859. var material = new THREE.MeshLambertMaterial();
  6860. THREE.Material.prototype.clone.call( this, material );
  6861. material.color.copy( this.color );
  6862. material.ambient.copy( this.ambient );
  6863. material.emissive.copy( this.emissive );
  6864. material.wrapAround = this.wrapAround;
  6865. material.wrapRGB.copy( this.wrapRGB );
  6866. material.map = this.map;
  6867. material.lightMap = this.lightMap;
  6868. material.specularMap = this.specularMap;
  6869. material.envMap = this.envMap;
  6870. material.combine = this.combine;
  6871. material.reflectivity = this.reflectivity;
  6872. material.refractionRatio = this.refractionRatio;
  6873. material.fog = this.fog;
  6874. material.shading = this.shading;
  6875. material.wireframe = this.wireframe;
  6876. material.wireframeLinewidth = this.wireframeLinewidth;
  6877. material.wireframeLinecap = this.wireframeLinecap;
  6878. material.wireframeLinejoin = this.wireframeLinejoin;
  6879. material.vertexColors = this.vertexColors;
  6880. material.skinning = this.skinning;
  6881. material.morphTargets = this.morphTargets;
  6882. material.morphNormals = this.morphNormals;
  6883. return material;
  6884. };
  6885. /**
  6886. * @author mrdoob / http://mrdoob.com/
  6887. * @author alteredq / http://alteredqualia.com/
  6888. *
  6889. * parameters = {
  6890. * color: <hex>,
  6891. * ambient: <hex>,
  6892. * emissive: <hex>,
  6893. * specular: <hex>,
  6894. * shininess: <float>,
  6895. * opacity: <float>,
  6896. *
  6897. * map: new THREE.Texture( <Image> ),
  6898. *
  6899. * lightMap: new THREE.Texture( <Image> ),
  6900. *
  6901. * bumpMap: new THREE.Texture( <Image> ),
  6902. * bumpScale: <float>,
  6903. *
  6904. * normalMap: new THREE.Texture( <Image> ),
  6905. * normalScale: <Vector2>,
  6906. *
  6907. * specularMap: new THREE.Texture( <Image> ),
  6908. *
  6909. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6910. * combine: THREE.Multiply,
  6911. * reflectivity: <float>,
  6912. * refractionRatio: <float>,
  6913. *
  6914. * shading: THREE.SmoothShading,
  6915. * blending: THREE.NormalBlending,
  6916. * depthTest: <bool>,
  6917. * depthWrite: <bool>,
  6918. *
  6919. * wireframe: <boolean>,
  6920. * wireframeLinewidth: <float>,
  6921. *
  6922. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6923. *
  6924. * skinning: <bool>,
  6925. * morphTargets: <bool>,
  6926. * morphNormals: <bool>,
  6927. *
  6928. * fog: <bool>
  6929. * }
  6930. */
  6931. THREE.MeshPhongMaterial = function ( parameters ) {
  6932. THREE.Material.call( this );
  6933. this.color = new THREE.Color( 0xffffff ); // diffuse
  6934. this.ambient = new THREE.Color( 0xffffff );
  6935. this.emissive = new THREE.Color( 0x000000 );
  6936. this.specular = new THREE.Color( 0x111111 );
  6937. this.shininess = 30;
  6938. this.metal = false;
  6939. this.perPixel = true;
  6940. this.wrapAround = false;
  6941. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6942. this.map = null;
  6943. this.lightMap = null;
  6944. this.bumpMap = null;
  6945. this.bumpScale = 1;
  6946. this.normalMap = null;
  6947. this.normalScale = new THREE.Vector2( 1, 1 );
  6948. this.specularMap = null;
  6949. this.envMap = null;
  6950. this.combine = THREE.MultiplyOperation;
  6951. this.reflectivity = 1;
  6952. this.refractionRatio = 0.98;
  6953. this.fog = true;
  6954. this.shading = THREE.SmoothShading;
  6955. this.wireframe = false;
  6956. this.wireframeLinewidth = 1;
  6957. this.wireframeLinecap = 'round';
  6958. this.wireframeLinejoin = 'round';
  6959. this.vertexColors = THREE.NoColors;
  6960. this.skinning = false;
  6961. this.morphTargets = false;
  6962. this.morphNormals = false;
  6963. this.setValues( parameters );
  6964. };
  6965. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6966. THREE.MeshPhongMaterial.prototype.clone = function () {
  6967. var material = new THREE.MeshPhongMaterial();
  6968. THREE.Material.prototype.clone.call( this, material );
  6969. material.color.copy( this.color );
  6970. material.ambient.copy( this.ambient );
  6971. material.emissive.copy( this.emissive );
  6972. material.specular.copy( this.specular );
  6973. material.shininess = this.shininess;
  6974. material.metal = this.metal;
  6975. material.perPixel = this.perPixel;
  6976. material.wrapAround = this.wrapAround;
  6977. material.wrapRGB.copy( this.wrapRGB );
  6978. material.map = this.map;
  6979. material.lightMap = this.lightMap;
  6980. material.bumpMap = this.bumpMap;
  6981. material.bumpScale = this.bumpScale;
  6982. material.normalMap = this.normalMap;
  6983. material.normalScale.copy( this.normalScale );
  6984. material.specularMap = this.specularMap;
  6985. material.envMap = this.envMap;
  6986. material.combine = this.combine;
  6987. material.reflectivity = this.reflectivity;
  6988. material.refractionRatio = this.refractionRatio;
  6989. material.fog = this.fog;
  6990. material.shading = this.shading;
  6991. material.wireframe = this.wireframe;
  6992. material.wireframeLinewidth = this.wireframeLinewidth;
  6993. material.wireframeLinecap = this.wireframeLinecap;
  6994. material.wireframeLinejoin = this.wireframeLinejoin;
  6995. material.vertexColors = this.vertexColors;
  6996. material.skinning = this.skinning;
  6997. material.morphTargets = this.morphTargets;
  6998. material.morphNormals = this.morphNormals;
  6999. return material;
  7000. };
  7001. /**
  7002. * @author mrdoob / http://mrdoob.com/
  7003. * @author alteredq / http://alteredqualia.com/
  7004. *
  7005. * parameters = {
  7006. * opacity: <float>,
  7007. *
  7008. * blending: THREE.NormalBlending,
  7009. * depthTest: <bool>,
  7010. * depthWrite: <bool>,
  7011. *
  7012. * wireframe: <boolean>,
  7013. * wireframeLinewidth: <float>
  7014. * }
  7015. */
  7016. THREE.MeshDepthMaterial = function ( parameters ) {
  7017. THREE.Material.call( this );
  7018. this.wireframe = false;
  7019. this.wireframeLinewidth = 1;
  7020. this.setValues( parameters );
  7021. };
  7022. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7023. THREE.MeshDepthMaterial.prototype.clone = function () {
  7024. var material = new THREE.LineBasicMaterial();
  7025. THREE.Material.prototype.clone.call( this, material );
  7026. material.wireframe = this.wireframe;
  7027. material.wireframeLinewidth = this.wireframeLinewidth;
  7028. return material;
  7029. };
  7030. /**
  7031. * @author mrdoob / http://mrdoob.com/
  7032. *
  7033. * parameters = {
  7034. * opacity: <float>,
  7035. *
  7036. * shading: THREE.FlatShading,
  7037. * blending: THREE.NormalBlending,
  7038. * depthTest: <bool>,
  7039. * depthWrite: <bool>,
  7040. *
  7041. * wireframe: <boolean>,
  7042. * wireframeLinewidth: <float>
  7043. * }
  7044. */
  7045. THREE.MeshNormalMaterial = function ( parameters ) {
  7046. THREE.Material.call( this, parameters );
  7047. this.shading = THREE.FlatShading;
  7048. this.wireframe = false;
  7049. this.wireframeLinewidth = 1;
  7050. this.setValues( parameters );
  7051. };
  7052. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7053. THREE.MeshNormalMaterial.prototype.clone = function () {
  7054. var material = new THREE.MeshNormalMaterial();
  7055. THREE.Material.prototype.clone.call( this, material );
  7056. material.shading = this.shading;
  7057. material.wireframe = this.wireframe;
  7058. material.wireframeLinewidth = this.wireframeLinewidth;
  7059. return material;
  7060. };
  7061. /**
  7062. * @author mrdoob / http://mrdoob.com/
  7063. */
  7064. THREE.MeshFaceMaterial = function ( materials ) {
  7065. this.materials = materials instanceof Array ? materials : [];
  7066. };
  7067. THREE.MeshFaceMaterial.prototype.clone = function () {
  7068. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7069. };
  7070. /**
  7071. * @author mrdoob / http://mrdoob.com/
  7072. * @author alteredq / http://alteredqualia.com/
  7073. *
  7074. * parameters = {
  7075. * color: <hex>,
  7076. * opacity: <float>,
  7077. * map: new THREE.Texture( <Image> ),
  7078. *
  7079. * size: <float>,
  7080. *
  7081. * blending: THREE.NormalBlending,
  7082. * depthTest: <bool>,
  7083. * depthWrite: <bool>,
  7084. *
  7085. * vertexColors: <bool>,
  7086. *
  7087. * fog: <bool>
  7088. * }
  7089. */
  7090. THREE.ParticleBasicMaterial = function ( parameters ) {
  7091. THREE.Material.call( this );
  7092. this.color = new THREE.Color( 0xffffff );
  7093. this.map = null;
  7094. this.size = 1;
  7095. this.sizeAttenuation = true;
  7096. this.vertexColors = false;
  7097. this.fog = true;
  7098. this.setValues( parameters );
  7099. };
  7100. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7101. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7102. var material = new THREE.ParticleBasicMaterial();
  7103. THREE.Material.prototype.clone.call( this, material );
  7104. material.color.copy( this.color );
  7105. material.map = this.map;
  7106. material.size = this.size;
  7107. material.sizeAttenuation = this.sizeAttenuation;
  7108. material.vertexColors = this.vertexColors;
  7109. material.fog = this.fog;
  7110. return material;
  7111. };
  7112. /**
  7113. * @author mrdoob / http://mrdoob.com/
  7114. *
  7115. * parameters = {
  7116. * color: <hex>,
  7117. * program: <function>,
  7118. * opacity: <float>,
  7119. * blending: THREE.NormalBlending
  7120. * }
  7121. */
  7122. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7123. THREE.Material.call( this );
  7124. this.color = new THREE.Color( 0xffffff );
  7125. this.program = function ( context, color ) {};
  7126. this.setValues( parameters );
  7127. };
  7128. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7129. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7130. var material = new THREE.ParticleCanvasMaterial();
  7131. THREE.Material.prototype.clone.call( this, material );
  7132. material.color.copy( this.color );
  7133. material.program = this.program;
  7134. return material;
  7135. };
  7136. /**
  7137. * @author mrdoob / http://mrdoob.com/
  7138. */
  7139. THREE.ParticleDOMMaterial = function ( element ) {
  7140. this.element = element;
  7141. };
  7142. THREE.ParticleDOMMaterial.prototype.clone = function(){
  7143. return new THREE.ParticleDOMMaterial( this.element );
  7144. };
  7145. /**
  7146. * @author alteredq / http://alteredqualia.com/
  7147. *
  7148. * parameters = {
  7149. * fragmentShader: <string>,
  7150. * vertexShader: <string>,
  7151. *
  7152. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7153. *
  7154. * defines: { "label" : "value" },
  7155. *
  7156. * shading: THREE.SmoothShading,
  7157. * blending: THREE.NormalBlending,
  7158. * depthTest: <bool>,
  7159. * depthWrite: <bool>,
  7160. *
  7161. * wireframe: <boolean>,
  7162. * wireframeLinewidth: <float>,
  7163. *
  7164. * lights: <bool>,
  7165. *
  7166. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7167. *
  7168. * skinning: <bool>,
  7169. * morphTargets: <bool>,
  7170. * morphNormals: <bool>,
  7171. *
  7172. * fog: <bool>
  7173. * }
  7174. */
  7175. THREE.ShaderMaterial = function ( parameters ) {
  7176. THREE.Material.call( this );
  7177. this.fragmentShader = "void main() {}";
  7178. this.vertexShader = "void main() {}";
  7179. this.uniforms = {};
  7180. this.defines = {};
  7181. this.attributes = null;
  7182. this.shading = THREE.SmoothShading;
  7183. this.wireframe = false;
  7184. this.wireframeLinewidth = 1;
  7185. this.fog = false; // set to use scene fog
  7186. this.lights = false; // set to use scene lights
  7187. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7188. this.skinning = false; // set to use skinning attribute streams
  7189. this.morphTargets = false; // set to use morph targets
  7190. this.morphNormals = false; // set to use morph normals
  7191. this.setValues( parameters );
  7192. };
  7193. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7194. THREE.ShaderMaterial.prototype.clone = function () {
  7195. var material = new THREE.ShaderMaterial();
  7196. THREE.Material.prototype.clone.call( this, material );
  7197. material.fragmentShader = this.fragmentShader;
  7198. material.vertexShader = this.vertexShader;
  7199. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7200. material.attributes = this.attributes;
  7201. material.defines = this.defines;
  7202. material.shading = this.shading;
  7203. material.wireframe = this.wireframe;
  7204. material.wireframeLinewidth = this.wireframeLinewidth;
  7205. material.fog = this.fog;
  7206. material.lights = this.lights;
  7207. material.vertexColors = this.vertexColors;
  7208. material.skinning = this.skinning;
  7209. material.morphTargets = this.morphTargets;
  7210. material.morphNormals = this.morphNormals;
  7211. return material;
  7212. };
  7213. /**
  7214. * @author alteredq / http://alteredqualia.com/
  7215. *
  7216. * parameters = {
  7217. * color: <hex>,
  7218. * opacity: <float>,
  7219. * map: new THREE.Texture( <Image> ),
  7220. *
  7221. * blending: THREE.NormalBlending,
  7222. * depthTest: <bool>,
  7223. * depthWrite: <bool>,
  7224. *
  7225. * useScreenCoordinates: <bool>,
  7226. * sizeAttenuation: <bool>,
  7227. * scaleByViewport: <bool>,
  7228. * alignment: THREE.SpriteAlignment.center,
  7229. *
  7230. * uvOffset: new THREE.Vector2(),
  7231. * uvScale: new THREE.Vector2(),
  7232. *
  7233. * fog: <bool>
  7234. * }
  7235. */
  7236. THREE.SpriteMaterial = function ( parameters ) {
  7237. THREE.Material.call( this );
  7238. // defaults
  7239. this.color = new THREE.Color( 0xffffff );
  7240. this.map = new THREE.Texture();
  7241. this.useScreenCoordinates = true;
  7242. this.depthTest = !this.useScreenCoordinates;
  7243. this.sizeAttenuation = !this.useScreenCoordinates;
  7244. this.scaleByViewport = !this.sizeAttenuation;
  7245. this.alignment = THREE.SpriteAlignment.center.clone();
  7246. this.fog = false;
  7247. this.uvOffset = new THREE.Vector2( 0, 0 );
  7248. this.uvScale = new THREE.Vector2( 1, 1 );
  7249. // set parameters
  7250. this.setValues( parameters );
  7251. // override coupled defaults if not specified explicitly by parameters
  7252. parameters = parameters || {};
  7253. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7254. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7255. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7256. };
  7257. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7258. THREE.SpriteMaterial.prototype.clone = function () {
  7259. var material = new THREE.SpriteMaterial();
  7260. THREE.Material.prototype.clone.call( this, material );
  7261. material.color.copy( this.color );
  7262. material.map = this.map;
  7263. material.useScreenCoordinates = this.useScreenCoordinates;
  7264. material.sizeAttenuation = this.sizeAttenuation;
  7265. material.scaleByViewport = this.scaleByViewport;
  7266. material.alignment.copy( this.alignment );
  7267. material.uvOffset.copy( this.uvOffset );
  7268. material.uvScale.copy( this.uvScale );
  7269. material.fog = this.fog;
  7270. return material;
  7271. };
  7272. // Alignment enums
  7273. THREE.SpriteAlignment = {};
  7274. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7275. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7276. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7277. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7278. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7279. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7280. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7281. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7282. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7283. /**
  7284. * @author mrdoob / http://mrdoob.com/
  7285. * @author alteredq / http://alteredqualia.com/
  7286. * @author szimek / https://github.com/szimek/
  7287. */
  7288. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7289. this.id = THREE.TextureIdCount ++;
  7290. this.name = '';
  7291. this.image = image;
  7292. this.mipmaps = [];
  7293. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7294. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7295. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7296. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7297. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7298. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7299. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7300. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7301. this.offset = new THREE.Vector2( 0, 0 );
  7302. this.repeat = new THREE.Vector2( 1, 1 );
  7303. this.generateMipmaps = true;
  7304. this.premultiplyAlpha = false;
  7305. this.flipY = true;
  7306. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7307. this.needsUpdate = false;
  7308. this.onUpdate = null;
  7309. };
  7310. THREE.Texture.prototype = {
  7311. constructor: THREE.Texture,
  7312. clone: function ( texture ) {
  7313. if ( texture === undefined ) texture = new THREE.Texture();
  7314. texture.image = this.image;
  7315. texture.mipmaps = this.mipmaps.slice(0);
  7316. texture.mapping = this.mapping;
  7317. texture.wrapS = this.wrapS;
  7318. texture.wrapT = this.wrapT;
  7319. texture.magFilter = this.magFilter;
  7320. texture.minFilter = this.minFilter;
  7321. texture.anisotropy = this.anisotropy;
  7322. texture.format = this.format;
  7323. texture.type = this.type;
  7324. texture.offset.copy( this.offset );
  7325. texture.repeat.copy( this.repeat );
  7326. texture.generateMipmaps = this.generateMipmaps;
  7327. texture.premultiplyAlpha = this.premultiplyAlpha;
  7328. texture.flipY = this.flipY;
  7329. texture.unpackAlignment = this.unpackAlignment;
  7330. return texture;
  7331. }
  7332. };
  7333. THREE.TextureIdCount = 0;
  7334. /**
  7335. * @author alteredq / http://alteredqualia.com/
  7336. */
  7337. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7338. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7339. this.image = { width: width, height: height };
  7340. this.mipmaps = mipmaps;
  7341. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7342. };
  7343. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7344. THREE.CompressedTexture.prototype.clone = function () {
  7345. var texture = new THREE.CompressedTexture();
  7346. THREE.Texture.prototype.clone.call( this, texture );
  7347. return texture;
  7348. };
  7349. /**
  7350. * @author alteredq / http://alteredqualia.com/
  7351. */
  7352. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7353. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7354. this.image = { data: data, width: width, height: height };
  7355. };
  7356. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7357. THREE.DataTexture.prototype.clone = function () {
  7358. var texture = new THREE.DataTexture();
  7359. THREE.Texture.prototype.clone.call( this, texture );
  7360. return texture;
  7361. };
  7362. /**
  7363. * @author mrdoob / http://mrdoob.com/
  7364. */
  7365. THREE.Particle = function ( material ) {
  7366. THREE.Object3D.call( this );
  7367. this.material = material;
  7368. };
  7369. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7370. THREE.Particle.prototype.clone = function ( object ) {
  7371. if ( object === undefined ) object = new THREE.Particle( this.material );
  7372. THREE.Object3D.prototype.clone.call( this, object );
  7373. return object;
  7374. };
  7375. /**
  7376. * @author alteredq / http://alteredqualia.com/
  7377. */
  7378. THREE.ParticleSystem = function ( geometry, material ) {
  7379. THREE.Object3D.call( this );
  7380. this.geometry = geometry;
  7381. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7382. this.sortParticles = false;
  7383. if ( this.geometry ) {
  7384. // calc bound radius
  7385. if( this.geometry.boundingSphere === null ) {
  7386. this.geometry.computeBoundingSphere();
  7387. }
  7388. }
  7389. this.frustumCulled = false;
  7390. };
  7391. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7392. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7393. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7394. object.sortParticles = this.sortParticles;
  7395. THREE.Object3D.prototype.clone.call( this, object );
  7396. return object;
  7397. };
  7398. /**
  7399. * @author mrdoob / http://mrdoob.com/
  7400. */
  7401. THREE.Line = function ( geometry, material, type ) {
  7402. THREE.Object3D.call( this );
  7403. this.geometry = geometry;
  7404. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7405. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7406. if ( this.geometry ) {
  7407. if ( ! this.geometry.boundingSphere ) {
  7408. this.geometry.computeBoundingSphere();
  7409. }
  7410. }
  7411. };
  7412. THREE.LineStrip = 0;
  7413. THREE.LinePieces = 1;
  7414. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7415. THREE.Line.prototype.clone = function ( object ) {
  7416. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7417. THREE.Object3D.prototype.clone.call( this, object );
  7418. return object;
  7419. };
  7420. /**
  7421. * @author mrdoob / http://mrdoob.com/
  7422. * @author alteredq / http://alteredqualia.com/
  7423. * @author mikael emtinger / http://gomo.se/
  7424. */
  7425. THREE.Mesh = function ( geometry, material ) {
  7426. THREE.Object3D.call( this );
  7427. this.geometry = geometry;
  7428. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7429. if ( this.geometry ) {
  7430. // calc bound radius
  7431. if ( this.geometry.boundingSphere === null ) {
  7432. this.geometry.computeBoundingSphere();
  7433. }
  7434. // setup morph targets
  7435. if ( this.geometry.morphTargets.length ) {
  7436. this.morphTargetBase = -1;
  7437. this.morphTargetForcedOrder = [];
  7438. this.morphTargetInfluences = [];
  7439. this.morphTargetDictionary = {};
  7440. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  7441. this.morphTargetInfluences.push( 0 );
  7442. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7443. }
  7444. }
  7445. }
  7446. }
  7447. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7448. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7449. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7450. return this.morphTargetDictionary[ name ];
  7451. }
  7452. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7453. return 0;
  7454. };
  7455. THREE.Mesh.prototype.clone = function ( object ) {
  7456. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7457. THREE.Object3D.prototype.clone.call( this, object );
  7458. return object;
  7459. };
  7460. /**
  7461. * @author mikael emtinger / http://gomo.se/
  7462. * @author alteredq / http://alteredqualia.com/
  7463. */
  7464. THREE.Bone = function( belongsToSkin ) {
  7465. THREE.Object3D.call( this );
  7466. this.skin = belongsToSkin;
  7467. this.skinMatrix = new THREE.Matrix4();
  7468. };
  7469. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7470. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  7471. // update local
  7472. if ( this.matrixAutoUpdate ) {
  7473. forceUpdate |= this.updateMatrix();
  7474. }
  7475. // update skin matrix
  7476. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7477. if( parentSkinMatrix ) {
  7478. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  7479. } else {
  7480. this.skinMatrix.copy( this.matrix );
  7481. }
  7482. this.matrixWorldNeedsUpdate = false;
  7483. forceUpdate = true;
  7484. }
  7485. // update children
  7486. var child, i, l = this.children.length;
  7487. for ( i = 0; i < l; i ++ ) {
  7488. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7489. }
  7490. };
  7491. /**
  7492. * @author mikael emtinger / http://gomo.se/
  7493. * @author alteredq / http://alteredqualia.com/
  7494. */
  7495. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7496. THREE.Mesh.call( this, geometry, material );
  7497. //
  7498. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7499. // init bones
  7500. this.identityMatrix = new THREE.Matrix4();
  7501. this.bones = [];
  7502. this.boneMatrices = [];
  7503. var b, bone, gbone, p, q, s;
  7504. if ( this.geometry && this.geometry.bones !== undefined ) {
  7505. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7506. gbone = this.geometry.bones[ b ];
  7507. p = gbone.pos;
  7508. q = gbone.rotq;
  7509. s = gbone.scl;
  7510. bone = this.addBone();
  7511. bone.name = gbone.name;
  7512. bone.position.set( p[0], p[1], p[2] );
  7513. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7514. bone.useQuaternion = true;
  7515. if ( s !== undefined ) {
  7516. bone.scale.set( s[0], s[1], s[2] );
  7517. } else {
  7518. bone.scale.set( 1, 1, 1 );
  7519. }
  7520. }
  7521. for ( b = 0; b < this.bones.length; b ++ ) {
  7522. gbone = this.geometry.bones[ b ];
  7523. bone = this.bones[ b ];
  7524. if ( gbone.parent === -1 ) {
  7525. this.add( bone );
  7526. } else {
  7527. this.bones[ gbone.parent ].add( bone );
  7528. }
  7529. }
  7530. //
  7531. var nBones = this.bones.length;
  7532. if ( this.useVertexTexture ) {
  7533. // layout (1 matrix = 4 pixels)
  7534. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7535. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7536. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7537. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7538. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7539. var size;
  7540. if ( nBones > 256 )
  7541. size = 64;
  7542. else if ( nBones > 64 )
  7543. size = 32;
  7544. else if ( nBones > 16 )
  7545. size = 16;
  7546. else
  7547. size = 8;
  7548. this.boneTextureWidth = size;
  7549. this.boneTextureHeight = size;
  7550. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7551. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7552. this.boneTexture.minFilter = THREE.NearestFilter;
  7553. this.boneTexture.magFilter = THREE.NearestFilter;
  7554. this.boneTexture.generateMipmaps = false;
  7555. this.boneTexture.flipY = false;
  7556. } else {
  7557. this.boneMatrices = new Float32Array( 16 * nBones );
  7558. }
  7559. this.pose();
  7560. }
  7561. };
  7562. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7563. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7564. if ( bone === undefined ) {
  7565. bone = new THREE.Bone( this );
  7566. }
  7567. this.bones.push( bone );
  7568. return bone;
  7569. };
  7570. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7571. this.matrixAutoUpdate && this.updateMatrix();
  7572. // update matrixWorld
  7573. if ( this.matrixWorldNeedsUpdate || force ) {
  7574. if ( this.parent ) {
  7575. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  7576. } else {
  7577. this.matrixWorld.copy( this.matrix );
  7578. }
  7579. this.matrixWorldNeedsUpdate = false;
  7580. force = true;
  7581. }
  7582. // update children
  7583. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7584. var child = this.children[ i ];
  7585. if ( child instanceof THREE.Bone ) {
  7586. child.update( this.identityMatrix, false );
  7587. } else {
  7588. child.updateMatrixWorld( true );
  7589. }
  7590. }
  7591. // make a snapshot of the bones' rest position
  7592. if ( this.boneInverses == undefined ) {
  7593. this.boneInverses = [];
  7594. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7595. var inverse = new THREE.Matrix4();
  7596. inverse.getInverse( this.bones[ b ].skinMatrix );
  7597. this.boneInverses.push( inverse );
  7598. }
  7599. }
  7600. // flatten bone matrices to array
  7601. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7602. // compute the offset between the current and the original transform;
  7603. //TODO: we could get rid of this multiplication step if the skinMatrix
  7604. // was already representing the offset; however, this requires some
  7605. // major changes to the animation system
  7606. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7607. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7608. }
  7609. if ( this.useVertexTexture ) {
  7610. this.boneTexture.needsUpdate = true;
  7611. }
  7612. };
  7613. THREE.SkinnedMesh.prototype.pose = function() {
  7614. this.updateMatrixWorld( true );
  7615. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7616. // normalize weights
  7617. var sw = this.geometry.skinWeights[ i ];
  7618. var scale = 1.0 / sw.lengthManhattan();
  7619. if ( scale !== Infinity ) {
  7620. sw.multiplyScalar( scale );
  7621. } else {
  7622. sw.set( 1 ); // this will be normalized by the shader anyway
  7623. }
  7624. }
  7625. };
  7626. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7627. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7628. THREE.Mesh.prototype.clone.call( this, object );
  7629. return object;
  7630. };
  7631. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7632. /**
  7633. * @author alteredq / http://alteredqualia.com/
  7634. */
  7635. THREE.MorphAnimMesh = function ( geometry, material ) {
  7636. THREE.Mesh.call( this, geometry, material );
  7637. // API
  7638. this.duration = 1000; // milliseconds
  7639. this.mirroredLoop = false;
  7640. this.time = 0;
  7641. // internals
  7642. this.lastKeyframe = 0;
  7643. this.currentKeyframe = 0;
  7644. this.direction = 1;
  7645. this.directionBackwards = false;
  7646. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7647. };
  7648. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7649. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7650. this.startKeyframe = start;
  7651. this.endKeyframe = end;
  7652. this.length = this.endKeyframe - this.startKeyframe + 1;
  7653. };
  7654. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7655. this.direction = 1;
  7656. this.directionBackwards = false;
  7657. };
  7658. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7659. this.direction = -1;
  7660. this.directionBackwards = true;
  7661. };
  7662. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7663. var geometry = this.geometry;
  7664. if ( ! geometry.animations ) geometry.animations = {};
  7665. var firstAnimation, animations = geometry.animations;
  7666. var pattern = /([a-z]+)(\d+)/;
  7667. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7668. var morph = geometry.morphTargets[ i ];
  7669. var parts = morph.name.match( pattern );
  7670. if ( parts && parts.length > 1 ) {
  7671. var label = parts[ 1 ];
  7672. var num = parts[ 2 ];
  7673. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7674. var animation = animations[ label ];
  7675. if ( i < animation.start ) animation.start = i;
  7676. if ( i > animation.end ) animation.end = i;
  7677. if ( ! firstAnimation ) firstAnimation = label;
  7678. }
  7679. }
  7680. geometry.firstAnimation = firstAnimation;
  7681. };
  7682. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7683. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7684. this.geometry.animations[ label ] = { start: start, end: end };
  7685. };
  7686. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7687. var animation = this.geometry.animations[ label ];
  7688. if ( animation ) {
  7689. this.setFrameRange( animation.start, animation.end );
  7690. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7691. this.time = 0;
  7692. } else {
  7693. console.warn( "animation[" + label + "] undefined" );
  7694. }
  7695. };
  7696. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7697. var frameTime = this.duration / this.length;
  7698. this.time += this.direction * delta;
  7699. if ( this.mirroredLoop ) {
  7700. if ( this.time > this.duration || this.time < 0 ) {
  7701. this.direction *= -1;
  7702. if ( this.time > this.duration ) {
  7703. this.time = this.duration;
  7704. this.directionBackwards = true;
  7705. }
  7706. if ( this.time < 0 ) {
  7707. this.time = 0;
  7708. this.directionBackwards = false;
  7709. }
  7710. }
  7711. } else {
  7712. this.time = this.time % this.duration;
  7713. if ( this.time < 0 ) this.time += this.duration;
  7714. }
  7715. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7716. if ( keyframe !== this.currentKeyframe ) {
  7717. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7718. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7719. this.morphTargetInfluences[ keyframe ] = 0;
  7720. this.lastKeyframe = this.currentKeyframe;
  7721. this.currentKeyframe = keyframe;
  7722. }
  7723. var mix = ( this.time % frameTime ) / frameTime;
  7724. if ( this.directionBackwards ) {
  7725. mix = 1 - mix;
  7726. }
  7727. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7728. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7729. };
  7730. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7731. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7732. object.duration = this.duration;
  7733. object.mirroredLoop = this.mirroredLoop;
  7734. object.time = this.time;
  7735. object.lastKeyframe = this.lastKeyframe;
  7736. object.currentKeyframe = this.currentKeyframe;
  7737. object.direction = this.direction;
  7738. object.directionBackwards = this.directionBackwards;
  7739. THREE.Mesh.prototype.clone.call( this, object );
  7740. return object;
  7741. };
  7742. /**
  7743. * @author alteredq / http://alteredqualia.com/
  7744. */
  7745. THREE.Ribbon = function ( geometry, material ) {
  7746. THREE.Object3D.call( this );
  7747. this.geometry = geometry;
  7748. this.material = material;
  7749. };
  7750. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7751. THREE.Ribbon.prototype.clone = function ( object ) {
  7752. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7753. THREE.Object3D.prototype.clone.call( this, object );
  7754. return object;
  7755. };
  7756. /**
  7757. * @author mikael emtinger / http://gomo.se/
  7758. * @author alteredq / http://alteredqualia.com/
  7759. * @author mrdoob / http://mrdoob.com/
  7760. */
  7761. THREE.LOD = function () {
  7762. THREE.Object3D.call( this );
  7763. this.LODs = [];
  7764. };
  7765. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7766. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7767. if ( visibleAtDistance === undefined ) {
  7768. visibleAtDistance = 0;
  7769. }
  7770. visibleAtDistance = Math.abs( visibleAtDistance );
  7771. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7772. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7773. break;
  7774. }
  7775. }
  7776. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7777. this.add( object3D );
  7778. };
  7779. THREE.LOD.prototype.update = function ( camera ) {
  7780. if ( this.LODs.length > 1 ) {
  7781. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7782. var inverse = camera.matrixWorldInverse;
  7783. var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );
  7784. this.LODs[ 0 ].object3D.visible = true;
  7785. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7786. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7787. this.LODs[ l - 1 ].object3D.visible = false;
  7788. this.LODs[ l ].object3D.visible = true;
  7789. } else {
  7790. break;
  7791. }
  7792. }
  7793. for( ; l < this.LODs.length; l ++ ) {
  7794. this.LODs[ l ].object3D.visible = false;
  7795. }
  7796. }
  7797. };
  7798. THREE.LOD.prototype.clone = function () {
  7799. // TODO
  7800. };
  7801. /**
  7802. * @author mikael emtinger / http://gomo.se/
  7803. * @author alteredq / http://alteredqualia.com/
  7804. */
  7805. THREE.Sprite = function ( material ) {
  7806. THREE.Object3D.call( this );
  7807. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7808. this.rotation3d = this.rotation;
  7809. this.rotation = 0;
  7810. };
  7811. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7812. /*
  7813. * Custom update matrix
  7814. */
  7815. THREE.Sprite.prototype.updateMatrix = function () {
  7816. this.matrix.setPosition( this.position );
  7817. this.rotation3d.set( 0, 0, this.rotation );
  7818. this.matrix.setRotationFromEuler( this.rotation3d );
  7819. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7820. this.matrix.scale( this.scale );
  7821. }
  7822. this.matrixWorldNeedsUpdate = true;
  7823. };
  7824. THREE.Sprite.prototype.clone = function ( object ) {
  7825. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7826. THREE.Object3D.prototype.clone.call( this, object );
  7827. return object;
  7828. };
  7829. /**
  7830. * @author mrdoob / http://mrdoob.com/
  7831. */
  7832. THREE.Scene = function () {
  7833. THREE.Object3D.call( this );
  7834. this.fog = null;
  7835. this.overrideMaterial = null;
  7836. this.matrixAutoUpdate = false;
  7837. this.__objects = [];
  7838. this.__lights = [];
  7839. this.__objectsAdded = [];
  7840. this.__objectsRemoved = [];
  7841. };
  7842. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7843. THREE.Scene.prototype.__addObject = function ( object ) {
  7844. if ( object instanceof THREE.Light ) {
  7845. if ( this.__lights.indexOf( object ) === - 1 ) {
  7846. this.__lights.push( object );
  7847. }
  7848. if ( object.target && object.target.parent === undefined ) {
  7849. this.add( object.target );
  7850. }
  7851. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7852. if ( this.__objects.indexOf( object ) === - 1 ) {
  7853. this.__objects.push( object );
  7854. this.__objectsAdded.push( object );
  7855. // check if previously removed
  7856. var i = this.__objectsRemoved.indexOf( object );
  7857. if ( i !== -1 ) {
  7858. this.__objectsRemoved.splice( i, 1 );
  7859. }
  7860. }
  7861. }
  7862. for ( var c = 0; c < object.children.length; c ++ ) {
  7863. this.__addObject( object.children[ c ] );
  7864. }
  7865. };
  7866. THREE.Scene.prototype.__removeObject = function ( object ) {
  7867. if ( object instanceof THREE.Light ) {
  7868. var i = this.__lights.indexOf( object );
  7869. if ( i !== -1 ) {
  7870. this.__lights.splice( i, 1 );
  7871. }
  7872. } else if ( !( object instanceof THREE.Camera ) ) {
  7873. var i = this.__objects.indexOf( object );
  7874. if( i !== -1 ) {
  7875. this.__objects.splice( i, 1 );
  7876. this.__objectsRemoved.push( object );
  7877. // check if previously added
  7878. var ai = this.__objectsAdded.indexOf( object );
  7879. if ( ai !== -1 ) {
  7880. this.__objectsAdded.splice( ai, 1 );
  7881. }
  7882. }
  7883. }
  7884. for ( var c = 0; c < object.children.length; c ++ ) {
  7885. this.__removeObject( object.children[ c ] );
  7886. }
  7887. };
  7888. /**
  7889. * @author mrdoob / http://mrdoob.com/
  7890. * @author alteredq / http://alteredqualia.com/
  7891. */
  7892. THREE.Fog = function ( hex, near, far ) {
  7893. this.name = '';
  7894. this.color = new THREE.Color( hex );
  7895. this.near = ( near !== undefined ) ? near : 1;
  7896. this.far = ( far !== undefined ) ? far : 1000;
  7897. };
  7898. THREE.Fog.prototype.clone = function () {
  7899. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7900. };
  7901. /**
  7902. * @author mrdoob / http://mrdoob.com/
  7903. * @author alteredq / http://alteredqualia.com/
  7904. */
  7905. THREE.FogExp2 = function ( hex, density ) {
  7906. this.name = '';
  7907. this.color = new THREE.Color( hex );
  7908. this.density = ( density !== undefined ) ? density : 0.00025;
  7909. };
  7910. THREE.FogExp2.prototype.clone = function () {
  7911. return new THREE.FogExp2( this.color.getHex(), this.density );
  7912. };
  7913. /**
  7914. * @author mrdoob / http://mrdoob.com/
  7915. */
  7916. THREE.CanvasRenderer = function ( parameters ) {
  7917. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7918. parameters = parameters || {};
  7919. var _this = this,
  7920. _renderData, _elements, _lights,
  7921. _projector = new THREE.Projector(),
  7922. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7923. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7924. _context = _canvas.getContext( '2d' ),
  7925. _clearColor = new THREE.Color( 0x000000 ),
  7926. _clearOpacity = 0,
  7927. _contextGlobalAlpha = 1,
  7928. _contextGlobalCompositeOperation = 0,
  7929. _contextStrokeStyle = null,
  7930. _contextFillStyle = null,
  7931. _contextLineWidth = null,
  7932. _contextLineCap = null,
  7933. _contextLineJoin = null,
  7934. _v1, _v2, _v3, _v4,
  7935. _v5 = new THREE.RenderableVertex(),
  7936. _v6 = new THREE.RenderableVertex(),
  7937. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7938. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7939. _color = new THREE.Color(),
  7940. _color1 = new THREE.Color(),
  7941. _color2 = new THREE.Color(),
  7942. _color3 = new THREE.Color(),
  7943. _color4 = new THREE.Color(),
  7944. _diffuseColor = new THREE.Color(),
  7945. _emissiveColor = new THREE.Color(),
  7946. _patterns = {}, _imagedatas = {},
  7947. _near, _far,
  7948. _image, _uvs,
  7949. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7950. _clipBox = new THREE.Box2(),
  7951. _clearBox = new THREE.Box2(),
  7952. _elemBox = new THREE.Box2(),
  7953. _enableLighting = false,
  7954. _ambientLight = new THREE.Color(),
  7955. _directionalLights = new THREE.Color(),
  7956. _pointLights = new THREE.Color(),
  7957. _pi2 = Math.PI * 2,
  7958. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7959. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7960. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7961. _pixelMap = document.createElement( 'canvas' );
  7962. _pixelMap.width = _pixelMap.height = 2;
  7963. _pixelMapContext = _pixelMap.getContext( '2d' );
  7964. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7965. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7966. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7967. _pixelMapData = _pixelMapImage.data;
  7968. _gradientMap = document.createElement( 'canvas' );
  7969. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7970. _gradientMapContext = _gradientMap.getContext( '2d' );
  7971. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7972. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7973. _gradientMapQuality --; // Fix UVs
  7974. this.domElement = _canvas;
  7975. this.autoClear = true;
  7976. this.sortObjects = true;
  7977. this.sortElements = true;
  7978. this.info = {
  7979. render: {
  7980. vertices: 0,
  7981. faces: 0
  7982. }
  7983. }
  7984. this.setSize = function ( width, height ) {
  7985. _canvasWidth = width;
  7986. _canvasHeight = height;
  7987. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7988. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7989. _canvas.width = _canvasWidth;
  7990. _canvas.height = _canvasHeight;
  7991. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7992. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7993. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7994. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7995. _contextGlobalAlpha = 1;
  7996. _contextGlobalCompositeOperation = 0;
  7997. _contextStrokeStyle = null;
  7998. _contextFillStyle = null;
  7999. _contextLineWidth = null;
  8000. _contextLineCap = null;
  8001. _contextLineJoin = null;
  8002. };
  8003. this.setClearColor = function ( color, opacity ) {
  8004. _clearColor.copy( color );
  8005. _clearOpacity = opacity !== undefined ? opacity : 1;
  8006. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8007. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8008. };
  8009. this.setClearColorHex = function ( hex, opacity ) {
  8010. _clearColor.setHex( hex );
  8011. _clearOpacity = opacity !== undefined ? opacity : 1;
  8012. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  8013. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  8014. };
  8015. this.getMaxAnisotropy = function () {
  8016. return 0;
  8017. };
  8018. this.clear = function () {
  8019. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8020. if ( _clearBox.empty() === false ) {
  8021. _clearBox.intersect( _clipBox );
  8022. _clearBox.expandByScalar( 2 );
  8023. if ( _clearOpacity < 1 ) {
  8024. _context.clearRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  8025. }
  8026. if ( _clearOpacity > 0 ) {
  8027. setBlending( THREE.NormalBlending );
  8028. setOpacity( 1 );
  8029. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8030. _context.fillRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  8031. }
  8032. _clearBox.makeEmpty();
  8033. }
  8034. };
  8035. this.render = function ( scene, camera ) {
  8036. if ( camera instanceof THREE.Camera === false ) {
  8037. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8038. return;
  8039. }
  8040. var e, el, element, material;
  8041. this.autoClear === true
  8042. ? this.clear()
  8043. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8044. _this.info.render.vertices = 0;
  8045. _this.info.render.faces = 0;
  8046. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8047. _elements = _renderData.elements;
  8048. _lights = _renderData.lights;
  8049. /* DEBUG
  8050. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  8051. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8052. */
  8053. _enableLighting = _lights.length > 0;
  8054. if ( _enableLighting === true ) {
  8055. calculateLights();
  8056. }
  8057. for ( e = 0, el = _elements.length; e < el; e++ ) {
  8058. element = _elements[ e ];
  8059. material = element.material;
  8060. if ( material === undefined || material.visible === false ) continue;
  8061. _elemBox.makeEmpty();
  8062. if ( element instanceof THREE.RenderableParticle ) {
  8063. _v1 = element;
  8064. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8065. renderParticle( _v1, element, material, scene );
  8066. } else if ( element instanceof THREE.RenderableLine ) {
  8067. _v1 = element.v1; _v2 = element.v2;
  8068. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8069. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8070. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8071. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8072. renderLine( _v1, _v2, element, material, scene );
  8073. }
  8074. } else if ( element instanceof THREE.RenderableFace3 ) {
  8075. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8076. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8077. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8078. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8079. if ( material.overdraw === true ) {
  8080. expand( _v1.positionScreen, _v2.positionScreen );
  8081. expand( _v2.positionScreen, _v3.positionScreen );
  8082. expand( _v3.positionScreen, _v1.positionScreen );
  8083. }
  8084. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8085. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8086. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  8087. }
  8088. } else if ( element instanceof THREE.RenderableFace4 ) {
  8089. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8090. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8091. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8092. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8093. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8094. _v5.positionScreen.copy( _v2.positionScreen );
  8095. _v6.positionScreen.copy( _v4.positionScreen );
  8096. if ( material.overdraw === true ) {
  8097. expand( _v1.positionScreen, _v2.positionScreen );
  8098. expand( _v2.positionScreen, _v4.positionScreen );
  8099. expand( _v4.positionScreen, _v1.positionScreen );
  8100. expand( _v3.positionScreen, _v5.positionScreen );
  8101. expand( _v3.positionScreen, _v6.positionScreen );
  8102. }
  8103. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8104. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8105. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8106. }
  8107. }
  8108. /* DEBUG
  8109. _context.lineWidth = 1;
  8110. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  8111. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8112. */
  8113. _clearBox.union( _elemBox );
  8114. }
  8115. /* DEBUG
  8116. _context.lineWidth = 1;
  8117. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  8118. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8119. */
  8120. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8121. //
  8122. function calculateLights() {
  8123. _ambientLight.setRGB( 0, 0, 0 );
  8124. _directionalLights.setRGB( 0, 0, 0 );
  8125. _pointLights.setRGB( 0, 0, 0 );
  8126. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8127. var light = _lights[ l ];
  8128. var lightColor = light.color;
  8129. if ( light instanceof THREE.AmbientLight ) {
  8130. _ambientLight.r += lightColor.r;
  8131. _ambientLight.g += lightColor.g;
  8132. _ambientLight.b += lightColor.b;
  8133. } else if ( light instanceof THREE.DirectionalLight ) {
  8134. // for particles
  8135. _directionalLights.r += lightColor.r;
  8136. _directionalLights.g += lightColor.g;
  8137. _directionalLights.b += lightColor.b;
  8138. } else if ( light instanceof THREE.PointLight ) {
  8139. // for particles
  8140. _pointLights.r += lightColor.r;
  8141. _pointLights.g += lightColor.g;
  8142. _pointLights.b += lightColor.b;
  8143. }
  8144. }
  8145. }
  8146. function calculateLight( position, normal, color ) {
  8147. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8148. var light = _lights[ l ];
  8149. var lightColor = light.color;
  8150. if ( light instanceof THREE.DirectionalLight ) {
  8151. var lightPosition = light.matrixWorld.getPosition().normalize();
  8152. var amount = normal.dot( lightPosition );
  8153. if ( amount <= 0 ) continue;
  8154. amount *= light.intensity;
  8155. color.r += lightColor.r * amount;
  8156. color.g += lightColor.g * amount;
  8157. color.b += lightColor.b * amount;
  8158. } else if ( light instanceof THREE.PointLight ) {
  8159. var lightPosition = light.matrixWorld.getPosition();
  8160. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  8161. if ( amount <= 0 ) continue;
  8162. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8163. if ( amount == 0 ) continue;
  8164. amount *= light.intensity;
  8165. color.r += lightColor.r * amount;
  8166. color.g += lightColor.g * amount;
  8167. color.b += lightColor.b * amount;
  8168. }
  8169. }
  8170. }
  8171. function renderParticle( v1, element, material, scene ) {
  8172. setOpacity( material.opacity );
  8173. setBlending( material.blending );
  8174. var width, height, scaleX, scaleY,
  8175. bitmap, bitmapWidth, bitmapHeight;
  8176. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8177. if ( material.map === null ) {
  8178. scaleX = element.object.scale.x;
  8179. scaleY = element.object.scale.y;
  8180. // TODO: Be able to disable this
  8181. scaleX *= element.scale.x * _canvasWidthHalf;
  8182. scaleY *= element.scale.y * _canvasHeightHalf;
  8183. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8184. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8185. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8186. return;
  8187. }
  8188. setFillStyle( material.color.getStyle() );
  8189. _context.save();
  8190. _context.translate( v1.x, v1.y );
  8191. _context.rotate( - element.rotation );
  8192. _context.scale( scaleX, scaleY );
  8193. _context.fillRect( -1, -1, 2, 2 );
  8194. _context.restore();
  8195. } else {
  8196. bitmap = material.map.image;
  8197. bitmapWidth = bitmap.width >> 1;
  8198. bitmapHeight = bitmap.height >> 1;
  8199. scaleX = element.scale.x * _canvasWidthHalf;
  8200. scaleY = element.scale.y * _canvasHeightHalf;
  8201. width = scaleX * bitmapWidth;
  8202. height = scaleY * bitmapHeight;
  8203. // TODO: Rotations break this...
  8204. _elemBox.min.set( v1.x - width, v1.y - height );
  8205. _elemBox.max.set( v1.x + width, v1.y + height );
  8206. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8207. return;
  8208. }
  8209. _context.save();
  8210. _context.translate( v1.x, v1.y );
  8211. _context.rotate( - element.rotation );
  8212. _context.scale( scaleX, - scaleY );
  8213. _context.translate( - bitmapWidth, - bitmapHeight );
  8214. _context.drawImage( bitmap, 0, 0 );
  8215. _context.restore();
  8216. }
  8217. /* DEBUG
  8218. setStrokeStyle( 'rgb(255,255,0)' );
  8219. _context.beginPath();
  8220. _context.moveTo( v1.x - 10, v1.y );
  8221. _context.lineTo( v1.x + 10, v1.y );
  8222. _context.moveTo( v1.x, v1.y - 10 );
  8223. _context.lineTo( v1.x, v1.y + 10 );
  8224. _context.stroke();
  8225. */
  8226. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8227. width = element.scale.x * _canvasWidthHalf;
  8228. height = element.scale.y * _canvasHeightHalf;
  8229. _elemBox.min.set( v1.x - width, v1.y - height );
  8230. _elemBox.max.set( v1.x + width, v1.y + height );
  8231. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8232. return;
  8233. }
  8234. setStrokeStyle( material.color.getStyle() );
  8235. setFillStyle( material.color.getStyle() );
  8236. _context.save();
  8237. _context.translate( v1.x, v1.y );
  8238. _context.rotate( - element.rotation );
  8239. _context.scale( width, height );
  8240. material.program( _context );
  8241. _context.restore();
  8242. }
  8243. }
  8244. function renderLine( v1, v2, element, material, scene ) {
  8245. setOpacity( material.opacity );
  8246. setBlending( material.blending );
  8247. _context.beginPath();
  8248. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8249. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8250. if ( material instanceof THREE.LineBasicMaterial ) {
  8251. setLineWidth( material.linewidth );
  8252. setLineCap( material.linecap );
  8253. setLineJoin( material.linejoin );
  8254. setStrokeStyle( material.color.getStyle() );
  8255. _context.stroke();
  8256. _elemBox.expandByScalar( material.linewidth * 2 );
  8257. }
  8258. }
  8259. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8260. _this.info.render.vertices += 3;
  8261. _this.info.render.faces ++;
  8262. setOpacity( material.opacity );
  8263. setBlending( material.blending );
  8264. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8265. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8266. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8267. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8268. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  8269. _diffuseColor.copy( material.color );
  8270. _emissiveColor.copy( material.emissive );
  8271. if ( material.vertexColors === THREE.FaceColors ) {
  8272. _diffuseColor.r *= element.color.r;
  8273. _diffuseColor.g *= element.color.g;
  8274. _diffuseColor.b *= element.color.b;
  8275. }
  8276. if ( _enableLighting === true ) {
  8277. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8278. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  8279. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  8280. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  8281. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  8282. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  8283. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  8284. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8285. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8286. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8287. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8288. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8289. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8290. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8291. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8292. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8293. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8294. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8295. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8296. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8297. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8298. } else {
  8299. _color.r = _ambientLight.r;
  8300. _color.g = _ambientLight.g;
  8301. _color.b = _ambientLight.b;
  8302. calculateLight( element.centroidWorld, element.normalWorld, _color );
  8303. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8304. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8305. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8306. material.wireframe === true
  8307. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8308. : fillPath( _color );
  8309. }
  8310. } else {
  8311. material.wireframe === true
  8312. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8313. : fillPath( material.color );
  8314. }
  8315. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8316. if ( material.map !== null ) {
  8317. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8318. _uvs = element.uvs[ 0 ];
  8319. 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 );
  8320. }
  8321. } else if ( material.envMap !== null ) {
  8322. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8323. var cameraMatrix = camera.matrixWorldInverse;
  8324. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  8325. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8326. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8327. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  8328. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8329. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8330. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  8331. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8332. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8333. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8334. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8335. }*/
  8336. } else {
  8337. _color.copy( material.color );
  8338. if ( material.vertexColors === THREE.FaceColors ) {
  8339. _color.r *= element.color.r;
  8340. _color.g *= element.color.g;
  8341. _color.b *= element.color.b;
  8342. }
  8343. material.wireframe === true
  8344. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8345. : fillPath( _color );
  8346. }
  8347. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8348. _near = camera.near;
  8349. _far = camera.far;
  8350. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8351. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8352. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8353. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8354. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8355. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8356. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8357. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8358. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8359. _color.r = normalToComponent( element.normalWorld.x );
  8360. _color.g = normalToComponent( element.normalWorld.y );
  8361. _color.b = normalToComponent( element.normalWorld.z );
  8362. material.wireframe === true
  8363. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8364. : fillPath( _color );
  8365. }
  8366. }
  8367. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8368. _this.info.render.vertices += 4;
  8369. _this.info.render.faces ++;
  8370. setOpacity( material.opacity );
  8371. setBlending( material.blending );
  8372. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8373. // Let renderFace3() handle this
  8374. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8375. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8376. return;
  8377. }
  8378. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8379. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8380. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8381. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8382. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8383. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8384. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8385. _diffuseColor.copy( material.color );
  8386. _emissiveColor.copy( material.emissive );
  8387. if ( material.vertexColors === THREE.FaceColors ) {
  8388. _diffuseColor.r *= element.color.r;
  8389. _diffuseColor.g *= element.color.g;
  8390. _diffuseColor.b *= element.color.b;
  8391. }
  8392. if ( _enableLighting === true ) {
  8393. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8394. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  8395. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  8396. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  8397. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  8398. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  8399. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  8400. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  8401. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8402. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8403. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8404. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8405. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8406. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8407. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8408. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8409. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8410. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  8411. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  8412. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  8413. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8414. // TODO: UVs are incorrect, v4->v3?
  8415. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8416. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8417. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8418. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8419. } else {
  8420. _color.r = _ambientLight.r;
  8421. _color.g = _ambientLight.g;
  8422. _color.b = _ambientLight.b;
  8423. calculateLight( element.centroidWorld, element.normalWorld, _color );
  8424. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8425. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8426. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8427. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8428. material.wireframe === true
  8429. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8430. : fillPath( _color );
  8431. }
  8432. } else {
  8433. _color.r = _diffuseColor.r + _emissiveColor.r;
  8434. _color.g = _diffuseColor.g + _emissiveColor.g;
  8435. _color.b = _diffuseColor.b + _emissiveColor.b;
  8436. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8437. material.wireframe === true
  8438. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8439. : fillPath( _color );
  8440. }
  8441. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8442. _color.copy( material.color );
  8443. if ( material.vertexColors === THREE.FaceColors ) {
  8444. _color.r *= element.color.r;
  8445. _color.g *= element.color.g;
  8446. _color.b *= element.color.b;
  8447. }
  8448. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8449. material.wireframe === true
  8450. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8451. : fillPath( _color );
  8452. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8453. _color.r = normalToComponent( element.normalWorld.x );
  8454. _color.g = normalToComponent( element.normalWorld.y );
  8455. _color.b = normalToComponent( element.normalWorld.z );
  8456. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8457. material.wireframe === true
  8458. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8459. : fillPath( _color );
  8460. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8461. _near = camera.near;
  8462. _far = camera.far;
  8463. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8464. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8465. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  8466. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8467. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8468. // TODO: UVs are incorrect, v4->v3?
  8469. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8470. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8471. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8472. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8473. }
  8474. }
  8475. //
  8476. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8477. _context.beginPath();
  8478. _context.moveTo( x0, y0 );
  8479. _context.lineTo( x1, y1 );
  8480. _context.lineTo( x2, y2 );
  8481. _context.closePath();
  8482. }
  8483. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8484. _context.beginPath();
  8485. _context.moveTo( x0, y0 );
  8486. _context.lineTo( x1, y1 );
  8487. _context.lineTo( x2, y2 );
  8488. _context.lineTo( x3, y3 );
  8489. _context.closePath();
  8490. }
  8491. function strokePath( color, linewidth, linecap, linejoin ) {
  8492. setLineWidth( linewidth );
  8493. setLineCap( linecap );
  8494. setLineJoin( linejoin );
  8495. setStrokeStyle( color.getStyle() );
  8496. _context.stroke();
  8497. _elemBox.expandByScalar( linewidth * 2 );
  8498. }
  8499. function fillPath( color ) {
  8500. setFillStyle( color.getStyle() );
  8501. _context.fill();
  8502. }
  8503. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8504. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8505. if ( texture.needsUpdate === true ) {
  8506. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8507. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8508. _patterns[ texture.id ] = _context.createPattern(
  8509. texture.image, repeatX === true && repeatY === true
  8510. ? 'repeat'
  8511. : repeatX === true && repeatY === false
  8512. ? 'repeat-x'
  8513. : repeatX === false && repeatY === true
  8514. ? 'repeat-y'
  8515. : 'no-repeat'
  8516. );
  8517. texture.needsUpdate = false;
  8518. }
  8519. _patterns[ texture.id ] === undefined
  8520. ? setFillStyle( 'rgba(0,0,0,1)' )
  8521. : setFillStyle( _patterns[ texture.id ] );
  8522. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8523. var a, b, c, d, e, f, det, idet,
  8524. offsetX = texture.offset.x / texture.repeat.x,
  8525. offsetY = texture.offset.y / texture.repeat.y,
  8526. width = texture.image.width * texture.repeat.x,
  8527. height = texture.image.height * texture.repeat.y;
  8528. u0 = ( u0 + offsetX ) * width;
  8529. v0 = ( 1.0 - v0 + offsetY ) * height;
  8530. u1 = ( u1 + offsetX ) * width;
  8531. v1 = ( 1.0 - v1 + offsetY ) * height;
  8532. u2 = ( u2 + offsetX ) * width;
  8533. v2 = ( 1.0 - v2 + offsetY ) * height;
  8534. x1 -= x0; y1 -= y0;
  8535. x2 -= x0; y2 -= y0;
  8536. u1 -= u0; v1 -= v0;
  8537. u2 -= u0; v2 -= v0;
  8538. det = u1 * v2 - u2 * v1;
  8539. if ( det === 0 ) {
  8540. if ( _imagedatas[ texture.id ] === undefined ) {
  8541. var canvas = document.createElement( 'canvas' )
  8542. canvas.width = texture.image.width;
  8543. canvas.height = texture.image.height;
  8544. var context = canvas.getContext( '2d' );
  8545. context.drawImage( texture.image, 0, 0 );
  8546. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8547. }
  8548. var data = _imagedatas[ texture.id ];
  8549. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8550. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8551. fillPath( _color );
  8552. return;
  8553. }
  8554. idet = 1 / det;
  8555. a = ( v2 * x1 - v1 * x2 ) * idet;
  8556. b = ( v2 * y1 - v1 * y2 ) * idet;
  8557. c = ( u1 * x2 - u2 * x1 ) * idet;
  8558. d = ( u1 * y2 - u2 * y1 ) * idet;
  8559. e = x0 - a * u0 - c * v0;
  8560. f = y0 - b * u0 - d * v0;
  8561. _context.save();
  8562. _context.transform( a, b, c, d, e, f );
  8563. _context.fill();
  8564. _context.restore();
  8565. }
  8566. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8567. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8568. var a, b, c, d, e, f, det, idet,
  8569. width = image.width - 1,
  8570. height = image.height - 1;
  8571. u0 *= width; v0 *= height;
  8572. u1 *= width; v1 *= height;
  8573. u2 *= width; v2 *= height;
  8574. x1 -= x0; y1 -= y0;
  8575. x2 -= x0; y2 -= y0;
  8576. u1 -= u0; v1 -= v0;
  8577. u2 -= u0; v2 -= v0;
  8578. det = u1 * v2 - u2 * v1;
  8579. idet = 1 / det;
  8580. a = ( v2 * x1 - v1 * x2 ) * idet;
  8581. b = ( v2 * y1 - v1 * y2 ) * idet;
  8582. c = ( u1 * x2 - u2 * x1 ) * idet;
  8583. d = ( u1 * y2 - u2 * y1 ) * idet;
  8584. e = x0 - a * u0 - c * v0;
  8585. f = y0 - b * u0 - d * v0;
  8586. _context.save();
  8587. _context.transform( a, b, c, d, e, f );
  8588. _context.clip();
  8589. _context.drawImage( image, 0, 0 );
  8590. _context.restore();
  8591. }
  8592. function getGradientTexture( color1, color2, color3, color4 ) {
  8593. // http://mrdoob.com/blog/post/710
  8594. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8595. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8596. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8597. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8598. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8599. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8600. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8601. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8602. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8603. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8604. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8605. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8606. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8607. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8608. return _gradientMap;
  8609. }
  8610. function smoothstep( value, min, max ) {
  8611. var x = ( value - min ) / ( max - min );
  8612. return x * x * ( 3 - 2 * x );
  8613. }
  8614. function normalToComponent( normal ) {
  8615. var component = ( normal + 1 ) * 0.5;
  8616. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  8617. }
  8618. // Hide anti-alias gaps
  8619. function expand( v1, v2 ) {
  8620. var x = v2.x - v1.x, y = v2.y - v1.y,
  8621. det = x * x + y * y, idet;
  8622. if ( det === 0 ) return;
  8623. idet = 1 / Math.sqrt( det );
  8624. x *= idet; y *= idet;
  8625. v2.x += x; v2.y += y;
  8626. v1.x -= x; v1.y -= y;
  8627. }
  8628. };
  8629. // Context cached methods.
  8630. function setOpacity( value ) {
  8631. if ( _contextGlobalAlpha !== value ) {
  8632. _context.globalAlpha = value;
  8633. _contextGlobalAlpha = value;
  8634. }
  8635. }
  8636. function setBlending( value ) {
  8637. if ( _contextGlobalCompositeOperation !== value ) {
  8638. if ( value === THREE.NormalBlending ) {
  8639. _context.globalCompositeOperation = 'source-over';
  8640. } else if ( value === THREE.AdditiveBlending ) {
  8641. _context.globalCompositeOperation = 'lighter';
  8642. } else if ( value === THREE.SubtractiveBlending ) {
  8643. _context.globalCompositeOperation = 'darker';
  8644. }
  8645. _contextGlobalCompositeOperation = value;
  8646. }
  8647. }
  8648. function setLineWidth( value ) {
  8649. if ( _contextLineWidth !== value ) {
  8650. _context.lineWidth = value;
  8651. _contextLineWidth = value;
  8652. }
  8653. }
  8654. function setLineCap( value ) {
  8655. // "butt", "round", "square"
  8656. if ( _contextLineCap !== value ) {
  8657. _context.lineCap = value;
  8658. _contextLineCap = value;
  8659. }
  8660. }
  8661. function setLineJoin( value ) {
  8662. // "round", "bevel", "miter"
  8663. if ( _contextLineJoin !== value ) {
  8664. _context.lineJoin = value;
  8665. _contextLineJoin = value;
  8666. }
  8667. }
  8668. function setStrokeStyle( value ) {
  8669. if ( _contextStrokeStyle !== value ) {
  8670. _context.strokeStyle = value;
  8671. _contextStrokeStyle = value;
  8672. }
  8673. }
  8674. function setFillStyle( value ) {
  8675. if ( _contextFillStyle !== value ) {
  8676. _context.fillStyle = value;
  8677. _contextFillStyle = value;
  8678. }
  8679. }
  8680. };
  8681. /**
  8682. * @author alteredq / http://alteredqualia.com/
  8683. * @author mrdoob / http://mrdoob.com/
  8684. * @author mikael emtinger / http://gomo.se/
  8685. */
  8686. THREE.ShaderChunk = {
  8687. // FOG
  8688. fog_pars_fragment: [
  8689. "#ifdef USE_FOG",
  8690. "uniform vec3 fogColor;",
  8691. "#ifdef FOG_EXP2",
  8692. "uniform float fogDensity;",
  8693. "#else",
  8694. "uniform float fogNear;",
  8695. "uniform float fogFar;",
  8696. "#endif",
  8697. "#endif"
  8698. ].join("\n"),
  8699. fog_fragment: [
  8700. "#ifdef USE_FOG",
  8701. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8702. "#ifdef FOG_EXP2",
  8703. "const float LOG2 = 1.442695;",
  8704. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8705. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8706. "#else",
  8707. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8708. "#endif",
  8709. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8710. "#endif"
  8711. ].join("\n"),
  8712. // ENVIRONMENT MAP
  8713. envmap_pars_fragment: [
  8714. "#ifdef USE_ENVMAP",
  8715. "uniform float reflectivity;",
  8716. "uniform samplerCube envMap;",
  8717. "uniform float flipEnvMap;",
  8718. "uniform int combine;",
  8719. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8720. "uniform bool useRefract;",
  8721. "uniform float refractionRatio;",
  8722. "#else",
  8723. "varying vec3 vReflect;",
  8724. "#endif",
  8725. "#endif"
  8726. ].join("\n"),
  8727. envmap_fragment: [
  8728. "#ifdef USE_ENVMAP",
  8729. "vec3 reflectVec;",
  8730. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8731. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8732. "if ( useRefract ) {",
  8733. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8734. "} else { ",
  8735. "reflectVec = reflect( cameraToVertex, normal );",
  8736. "}",
  8737. "#else",
  8738. "reflectVec = vReflect;",
  8739. "#endif",
  8740. "#ifdef DOUBLE_SIDED",
  8741. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8742. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8743. "#else",
  8744. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8745. "#endif",
  8746. "#ifdef GAMMA_INPUT",
  8747. "cubeColor.xyz *= cubeColor.xyz;",
  8748. "#endif",
  8749. "if ( combine == 1 ) {",
  8750. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8751. "} else if ( combine == 2 ) {",
  8752. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8753. "} else {",
  8754. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8755. "}",
  8756. "#endif"
  8757. ].join("\n"),
  8758. envmap_pars_vertex: [
  8759. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8760. "varying vec3 vReflect;",
  8761. "uniform float refractionRatio;",
  8762. "uniform bool useRefract;",
  8763. "#endif"
  8764. ].join("\n"),
  8765. worldpos_vertex : [
  8766. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8767. "#ifdef USE_SKINNING",
  8768. "vec4 worldPosition = modelMatrix * skinned;",
  8769. "#endif",
  8770. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8771. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8772. "#endif",
  8773. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8774. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8775. "#endif",
  8776. "#endif"
  8777. ].join("\n"),
  8778. envmap_vertex : [
  8779. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8780. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8781. "worldNormal = normalize( worldNormal );",
  8782. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8783. "if ( useRefract ) {",
  8784. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8785. "} else {",
  8786. "vReflect = reflect( cameraToVertex, worldNormal );",
  8787. "}",
  8788. "#endif"
  8789. ].join("\n"),
  8790. // COLOR MAP (particles)
  8791. map_particle_pars_fragment: [
  8792. "#ifdef USE_MAP",
  8793. "uniform sampler2D map;",
  8794. "#endif"
  8795. ].join("\n"),
  8796. map_particle_fragment: [
  8797. "#ifdef USE_MAP",
  8798. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8799. "#endif"
  8800. ].join("\n"),
  8801. // COLOR MAP (triangles)
  8802. map_pars_vertex: [
  8803. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8804. "varying vec2 vUv;",
  8805. "uniform vec4 offsetRepeat;",
  8806. "#endif"
  8807. ].join("\n"),
  8808. map_pars_fragment: [
  8809. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8810. "varying vec2 vUv;",
  8811. "#endif",
  8812. "#ifdef USE_MAP",
  8813. "uniform sampler2D map;",
  8814. "#endif"
  8815. ].join("\n"),
  8816. map_vertex: [
  8817. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8818. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8819. "#endif"
  8820. ].join("\n"),
  8821. map_fragment: [
  8822. "#ifdef USE_MAP",
  8823. "vec4 texelColor = texture2D( map, vUv );",
  8824. "#ifdef GAMMA_INPUT",
  8825. "texelColor.xyz *= texelColor.xyz;",
  8826. "#endif",
  8827. "gl_FragColor = gl_FragColor * texelColor;",
  8828. "#endif"
  8829. ].join("\n"),
  8830. // LIGHT MAP
  8831. lightmap_pars_fragment: [
  8832. "#ifdef USE_LIGHTMAP",
  8833. "varying vec2 vUv2;",
  8834. "uniform sampler2D lightMap;",
  8835. "#endif"
  8836. ].join("\n"),
  8837. lightmap_pars_vertex: [
  8838. "#ifdef USE_LIGHTMAP",
  8839. "varying vec2 vUv2;",
  8840. "#endif"
  8841. ].join("\n"),
  8842. lightmap_fragment: [
  8843. "#ifdef USE_LIGHTMAP",
  8844. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8845. "#endif"
  8846. ].join("\n"),
  8847. lightmap_vertex: [
  8848. "#ifdef USE_LIGHTMAP",
  8849. "vUv2 = uv2;",
  8850. "#endif"
  8851. ].join("\n"),
  8852. // BUMP MAP
  8853. bumpmap_pars_fragment: [
  8854. "#ifdef USE_BUMPMAP",
  8855. "uniform sampler2D bumpMap;",
  8856. "uniform float bumpScale;",
  8857. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8858. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8859. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8860. "vec2 dHdxy_fwd() {",
  8861. "vec2 dSTdx = dFdx( vUv );",
  8862. "vec2 dSTdy = dFdy( vUv );",
  8863. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8864. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8865. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8866. "return vec2( dBx, dBy );",
  8867. "}",
  8868. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8869. "vec3 vSigmaX = dFdx( surf_pos );",
  8870. "vec3 vSigmaY = dFdy( surf_pos );",
  8871. "vec3 vN = surf_norm;", // normalized
  8872. "vec3 R1 = cross( vSigmaY, vN );",
  8873. "vec3 R2 = cross( vN, vSigmaX );",
  8874. "float fDet = dot( vSigmaX, R1 );",
  8875. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8876. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8877. "}",
  8878. "#endif"
  8879. ].join("\n"),
  8880. // NORMAL MAP
  8881. normalmap_pars_fragment: [
  8882. "#ifdef USE_NORMALMAP",
  8883. "uniform sampler2D normalMap;",
  8884. "uniform vec2 normalScale;",
  8885. // Per-Pixel Tangent Space Normal Mapping
  8886. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8887. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8888. "vec3 q0 = dFdx( eye_pos.xyz );",
  8889. "vec3 q1 = dFdy( eye_pos.xyz );",
  8890. "vec2 st0 = dFdx( vUv.st );",
  8891. "vec2 st1 = dFdy( vUv.st );",
  8892. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8893. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8894. "vec3 N = normalize( surf_norm );",
  8895. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8896. "mapN.xy = normalScale * mapN.xy;",
  8897. "mat3 tsn = mat3( S, T, N );",
  8898. "return normalize( tsn * mapN );",
  8899. "}",
  8900. "#endif"
  8901. ].join("\n"),
  8902. // SPECULAR MAP
  8903. specularmap_pars_fragment: [
  8904. "#ifdef USE_SPECULARMAP",
  8905. "uniform sampler2D specularMap;",
  8906. "#endif"
  8907. ].join("\n"),
  8908. specularmap_fragment: [
  8909. "float specularStrength;",
  8910. "#ifdef USE_SPECULARMAP",
  8911. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8912. "specularStrength = texelSpecular.r;",
  8913. "#else",
  8914. "specularStrength = 1.0;",
  8915. "#endif"
  8916. ].join("\n"),
  8917. // LIGHTS LAMBERT
  8918. lights_lambert_pars_vertex: [
  8919. "uniform vec3 ambient;",
  8920. "uniform vec3 diffuse;",
  8921. "uniform vec3 emissive;",
  8922. "uniform vec3 ambientLightColor;",
  8923. "#if MAX_DIR_LIGHTS > 0",
  8924. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8925. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8926. "#endif",
  8927. "#if MAX_HEMI_LIGHTS > 0",
  8928. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8929. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8930. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8931. "#endif",
  8932. "#if MAX_POINT_LIGHTS > 0",
  8933. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8934. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8935. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8936. "#endif",
  8937. "#if MAX_SPOT_LIGHTS > 0",
  8938. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8939. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8940. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8941. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8942. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8943. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8944. "#endif",
  8945. "#ifdef WRAP_AROUND",
  8946. "uniform vec3 wrapRGB;",
  8947. "#endif"
  8948. ].join("\n"),
  8949. lights_lambert_vertex: [
  8950. "vLightFront = vec3( 0.0 );",
  8951. "#ifdef DOUBLE_SIDED",
  8952. "vLightBack = vec3( 0.0 );",
  8953. "#endif",
  8954. "transformedNormal = normalize( transformedNormal );",
  8955. "#if MAX_DIR_LIGHTS > 0",
  8956. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8957. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8958. "vec3 dirVector = normalize( lDirection.xyz );",
  8959. "float dotProduct = dot( transformedNormal, dirVector );",
  8960. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8961. "#ifdef DOUBLE_SIDED",
  8962. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8963. "#ifdef WRAP_AROUND",
  8964. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8965. "#endif",
  8966. "#endif",
  8967. "#ifdef WRAP_AROUND",
  8968. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8969. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8970. "#ifdef DOUBLE_SIDED",
  8971. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8972. "#endif",
  8973. "#endif",
  8974. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8975. "#ifdef DOUBLE_SIDED",
  8976. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8977. "#endif",
  8978. "}",
  8979. "#endif",
  8980. "#if MAX_POINT_LIGHTS > 0",
  8981. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8982. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8983. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8984. "float lDistance = 1.0;",
  8985. "if ( pointLightDistance[ i ] > 0.0 )",
  8986. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8987. "lVector = normalize( lVector );",
  8988. "float dotProduct = dot( transformedNormal, lVector );",
  8989. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8990. "#ifdef DOUBLE_SIDED",
  8991. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8992. "#ifdef WRAP_AROUND",
  8993. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8994. "#endif",
  8995. "#endif",
  8996. "#ifdef WRAP_AROUND",
  8997. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8998. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8999. "#ifdef DOUBLE_SIDED",
  9000. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9001. "#endif",
  9002. "#endif",
  9003. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9004. "#ifdef DOUBLE_SIDED",
  9005. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9006. "#endif",
  9007. "}",
  9008. "#endif",
  9009. "#if MAX_SPOT_LIGHTS > 0",
  9010. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9011. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9012. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9013. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9014. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9015. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9016. "float lDistance = 1.0;",
  9017. "if ( spotLightDistance[ i ] > 0.0 )",
  9018. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9019. "lVector = normalize( lVector );",
  9020. "float dotProduct = dot( transformedNormal, lVector );",
  9021. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9022. "#ifdef DOUBLE_SIDED",
  9023. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9024. "#ifdef WRAP_AROUND",
  9025. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9026. "#endif",
  9027. "#endif",
  9028. "#ifdef WRAP_AROUND",
  9029. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9030. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9031. "#ifdef DOUBLE_SIDED",
  9032. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9033. "#endif",
  9034. "#endif",
  9035. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9036. "#ifdef DOUBLE_SIDED",
  9037. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9038. "#endif",
  9039. "}",
  9040. "}",
  9041. "#endif",
  9042. "#if MAX_HEMI_LIGHTS > 0",
  9043. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9044. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9045. "vec3 lVector = normalize( lDirection.xyz );",
  9046. "float dotProduct = dot( transformedNormal, lVector );",
  9047. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9048. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9049. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9050. "#ifdef DOUBLE_SIDED",
  9051. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9052. "#endif",
  9053. "}",
  9054. "#endif",
  9055. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9056. "#ifdef DOUBLE_SIDED",
  9057. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9058. "#endif"
  9059. ].join("\n"),
  9060. // LIGHTS PHONG
  9061. lights_phong_pars_vertex: [
  9062. "#ifndef PHONG_PER_PIXEL",
  9063. "#if MAX_POINT_LIGHTS > 0",
  9064. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9065. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9066. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9067. "#endif",
  9068. "#if MAX_SPOT_LIGHTS > 0",
  9069. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9070. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9071. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9072. "#endif",
  9073. "#endif",
  9074. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9075. "varying vec3 vWorldPosition;",
  9076. "#endif"
  9077. ].join("\n"),
  9078. lights_phong_vertex: [
  9079. "#ifndef PHONG_PER_PIXEL",
  9080. "#if MAX_POINT_LIGHTS > 0",
  9081. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9082. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9083. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9084. "float lDistance = 1.0;",
  9085. "if ( pointLightDistance[ i ] > 0.0 )",
  9086. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9087. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9088. "}",
  9089. "#endif",
  9090. "#if MAX_SPOT_LIGHTS > 0",
  9091. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9092. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9093. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9094. "float lDistance = 1.0;",
  9095. "if ( spotLightDistance[ i ] > 0.0 )",
  9096. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9097. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9098. "}",
  9099. "#endif",
  9100. "#endif",
  9101. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9102. "vWorldPosition = worldPosition.xyz;",
  9103. "#endif"
  9104. ].join("\n"),
  9105. lights_phong_pars_fragment: [
  9106. "uniform vec3 ambientLightColor;",
  9107. "#if MAX_DIR_LIGHTS > 0",
  9108. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9109. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9110. "#endif",
  9111. "#if MAX_HEMI_LIGHTS > 0",
  9112. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9113. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9114. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9115. "#endif",
  9116. "#if MAX_POINT_LIGHTS > 0",
  9117. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9118. "#ifdef PHONG_PER_PIXEL",
  9119. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9120. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9121. "#else",
  9122. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9123. "#endif",
  9124. "#endif",
  9125. "#if MAX_SPOT_LIGHTS > 0",
  9126. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9127. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9128. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9129. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9130. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9131. "#ifdef PHONG_PER_PIXEL",
  9132. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9133. "#else",
  9134. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9135. "#endif",
  9136. "#endif",
  9137. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9138. "varying vec3 vWorldPosition;",
  9139. "#endif",
  9140. "#ifdef WRAP_AROUND",
  9141. "uniform vec3 wrapRGB;",
  9142. "#endif",
  9143. "varying vec3 vViewPosition;",
  9144. "varying vec3 vNormal;"
  9145. ].join("\n"),
  9146. lights_phong_fragment: [
  9147. "vec3 normal = normalize( vNormal );",
  9148. "vec3 viewPosition = normalize( vViewPosition );",
  9149. "#ifdef DOUBLE_SIDED",
  9150. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9151. "#endif",
  9152. "#ifdef USE_NORMALMAP",
  9153. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9154. "#elif defined( USE_BUMPMAP )",
  9155. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9156. "#endif",
  9157. "#if MAX_POINT_LIGHTS > 0",
  9158. "vec3 pointDiffuse = vec3( 0.0 );",
  9159. "vec3 pointSpecular = vec3( 0.0 );",
  9160. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9161. "#ifdef PHONG_PER_PIXEL",
  9162. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9163. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9164. "float lDistance = 1.0;",
  9165. "if ( pointLightDistance[ i ] > 0.0 )",
  9166. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9167. "lVector = normalize( lVector );",
  9168. "#else",
  9169. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9170. "float lDistance = vPointLight[ i ].w;",
  9171. "#endif",
  9172. // diffuse
  9173. "float dotProduct = dot( normal, lVector );",
  9174. "#ifdef WRAP_AROUND",
  9175. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9176. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9177. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9178. "#else",
  9179. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9180. "#endif",
  9181. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9182. // specular
  9183. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9184. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9185. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9186. "#ifdef PHYSICALLY_BASED_SHADING",
  9187. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9188. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9189. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9190. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9191. "#else",
  9192. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9193. "#endif",
  9194. "}",
  9195. "#endif",
  9196. "#if MAX_SPOT_LIGHTS > 0",
  9197. "vec3 spotDiffuse = vec3( 0.0 );",
  9198. "vec3 spotSpecular = vec3( 0.0 );",
  9199. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9200. "#ifdef PHONG_PER_PIXEL",
  9201. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9202. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9203. "float lDistance = 1.0;",
  9204. "if ( spotLightDistance[ i ] > 0.0 )",
  9205. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9206. "lVector = normalize( lVector );",
  9207. "#else",
  9208. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9209. "float lDistance = vSpotLight[ i ].w;",
  9210. "#endif",
  9211. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9212. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9213. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9214. // diffuse
  9215. "float dotProduct = dot( normal, lVector );",
  9216. "#ifdef WRAP_AROUND",
  9217. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9218. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9219. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9220. "#else",
  9221. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9222. "#endif",
  9223. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9224. // specular
  9225. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9226. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9227. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9228. "#ifdef PHYSICALLY_BASED_SHADING",
  9229. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9230. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9231. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9232. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9233. "#else",
  9234. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9235. "#endif",
  9236. "}",
  9237. "}",
  9238. "#endif",
  9239. "#if MAX_DIR_LIGHTS > 0",
  9240. "vec3 dirDiffuse = vec3( 0.0 );",
  9241. "vec3 dirSpecular = vec3( 0.0 );" ,
  9242. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9243. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9244. "vec3 dirVector = normalize( lDirection.xyz );",
  9245. // diffuse
  9246. "float dotProduct = dot( normal, dirVector );",
  9247. "#ifdef WRAP_AROUND",
  9248. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9249. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9250. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9251. "#else",
  9252. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9253. "#endif",
  9254. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9255. // specular
  9256. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9257. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9258. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9259. "#ifdef PHYSICALLY_BASED_SHADING",
  9260. /*
  9261. // fresnel term from skin shader
  9262. "const float F0 = 0.128;",
  9263. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9264. "float exponential = pow( base, 5.0 );",
  9265. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9266. */
  9267. /*
  9268. // fresnel term from fresnel shader
  9269. "const float mFresnelBias = 0.08;",
  9270. "const float mFresnelScale = 0.3;",
  9271. "const float mFresnelPower = 5.0;",
  9272. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9273. */
  9274. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9275. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9276. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9277. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9278. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9279. "#else",
  9280. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9281. "#endif",
  9282. "}",
  9283. "#endif",
  9284. "#if MAX_HEMI_LIGHTS > 0",
  9285. "vec3 hemiDiffuse = vec3( 0.0 );",
  9286. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9287. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9288. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9289. "vec3 lVector = normalize( lDirection.xyz );",
  9290. // diffuse
  9291. "float dotProduct = dot( normal, lVector );",
  9292. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9293. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9294. "hemiDiffuse += diffuse * hemiColor;",
  9295. // specular (sky light)
  9296. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9297. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9298. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9299. // specular (ground light)
  9300. "vec3 lVectorGround = -lVector;",
  9301. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9302. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9303. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9304. "#ifdef PHYSICALLY_BASED_SHADING",
  9305. "float dotProductGround = dot( normal, lVectorGround );",
  9306. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9307. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9308. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9309. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9310. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9311. "#else",
  9312. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9313. "#endif",
  9314. "}",
  9315. "#endif",
  9316. "vec3 totalDiffuse = vec3( 0.0 );",
  9317. "vec3 totalSpecular = vec3( 0.0 );",
  9318. "#if MAX_DIR_LIGHTS > 0",
  9319. "totalDiffuse += dirDiffuse;",
  9320. "totalSpecular += dirSpecular;",
  9321. "#endif",
  9322. "#if MAX_HEMI_LIGHTS > 0",
  9323. "totalDiffuse += hemiDiffuse;",
  9324. "totalSpecular += hemiSpecular;",
  9325. "#endif",
  9326. "#if MAX_POINT_LIGHTS > 0",
  9327. "totalDiffuse += pointDiffuse;",
  9328. "totalSpecular += pointSpecular;",
  9329. "#endif",
  9330. "#if MAX_SPOT_LIGHTS > 0",
  9331. "totalDiffuse += spotDiffuse;",
  9332. "totalSpecular += spotSpecular;",
  9333. "#endif",
  9334. "#ifdef METAL",
  9335. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9336. "#else",
  9337. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9338. "#endif"
  9339. ].join("\n"),
  9340. // VERTEX COLORS
  9341. color_pars_fragment: [
  9342. "#ifdef USE_COLOR",
  9343. "varying vec3 vColor;",
  9344. "#endif"
  9345. ].join("\n"),
  9346. color_fragment: [
  9347. "#ifdef USE_COLOR",
  9348. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9349. "#endif"
  9350. ].join("\n"),
  9351. color_pars_vertex: [
  9352. "#ifdef USE_COLOR",
  9353. "varying vec3 vColor;",
  9354. "#endif"
  9355. ].join("\n"),
  9356. color_vertex: [
  9357. "#ifdef USE_COLOR",
  9358. "#ifdef GAMMA_INPUT",
  9359. "vColor = color * color;",
  9360. "#else",
  9361. "vColor = color;",
  9362. "#endif",
  9363. "#endif"
  9364. ].join("\n"),
  9365. // SKINNING
  9366. skinning_pars_vertex: [
  9367. "#ifdef USE_SKINNING",
  9368. "#ifdef BONE_TEXTURE",
  9369. "uniform sampler2D boneTexture;",
  9370. "mat4 getBoneMatrix( const in float i ) {",
  9371. "float j = i * 4.0;",
  9372. "float x = mod( j, N_BONE_PIXEL_X );",
  9373. "float y = floor( j / N_BONE_PIXEL_X );",
  9374. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9375. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9376. "y = dy * ( y + 0.5 );",
  9377. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9378. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9379. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9380. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9381. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9382. "return bone;",
  9383. "}",
  9384. "#else",
  9385. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9386. "mat4 getBoneMatrix( const in float i ) {",
  9387. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9388. "return bone;",
  9389. "}",
  9390. "#endif",
  9391. "#endif"
  9392. ].join("\n"),
  9393. skinbase_vertex: [
  9394. "#ifdef USE_SKINNING",
  9395. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9396. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9397. "#endif"
  9398. ].join("\n"),
  9399. skinning_vertex: [
  9400. "#ifdef USE_SKINNING",
  9401. "#ifdef USE_MORPHTARGETS",
  9402. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9403. "#else",
  9404. "vec4 skinVertex = vec4( position, 1.0 );",
  9405. "#endif",
  9406. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9407. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9408. "#endif"
  9409. ].join("\n"),
  9410. // MORPHING
  9411. morphtarget_pars_vertex: [
  9412. "#ifdef USE_MORPHTARGETS",
  9413. "#ifndef USE_MORPHNORMALS",
  9414. "uniform float morphTargetInfluences[ 8 ];",
  9415. "#else",
  9416. "uniform float morphTargetInfluences[ 4 ];",
  9417. "#endif",
  9418. "#endif"
  9419. ].join("\n"),
  9420. morphtarget_vertex: [
  9421. "#ifdef USE_MORPHTARGETS",
  9422. "vec3 morphed = vec3( 0.0 );",
  9423. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9424. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9425. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9426. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9427. "#ifndef USE_MORPHNORMALS",
  9428. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9429. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9430. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9431. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9432. "#endif",
  9433. "morphed += position;",
  9434. "#endif"
  9435. ].join("\n"),
  9436. default_vertex : [
  9437. "vec4 mvPosition;",
  9438. "#ifdef USE_SKINNING",
  9439. "mvPosition = modelViewMatrix * skinned;",
  9440. "#endif",
  9441. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9442. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9443. "#endif",
  9444. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9445. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9446. "#endif",
  9447. "gl_Position = projectionMatrix * mvPosition;"
  9448. ].join("\n"),
  9449. morphnormal_vertex: [
  9450. "#ifdef USE_MORPHNORMALS",
  9451. "vec3 morphedNormal = vec3( 0.0 );",
  9452. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9453. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9454. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9455. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9456. "morphedNormal += normal;",
  9457. "#endif"
  9458. ].join("\n"),
  9459. skinnormal_vertex: [
  9460. "#ifdef USE_SKINNING",
  9461. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9462. "skinMatrix += skinWeight.y * boneMatY;",
  9463. "#ifdef USE_MORPHNORMALS",
  9464. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9465. "#else",
  9466. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9467. "#endif",
  9468. "#endif"
  9469. ].join("\n"),
  9470. defaultnormal_vertex: [
  9471. "vec3 objectNormal;",
  9472. "#ifdef USE_SKINNING",
  9473. "objectNormal = skinnedNormal.xyz;",
  9474. "#endif",
  9475. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9476. "objectNormal = morphedNormal;",
  9477. "#endif",
  9478. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9479. "objectNormal = normal;",
  9480. "#endif",
  9481. "#ifdef FLIP_SIDED",
  9482. "objectNormal = -objectNormal;",
  9483. "#endif",
  9484. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9485. ].join("\n"),
  9486. // SHADOW MAP
  9487. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9488. // http://spidergl.org/example.php?id=6
  9489. // http://fabiensanglard.net/shadowmapping
  9490. shadowmap_pars_fragment: [
  9491. "#ifdef USE_SHADOWMAP",
  9492. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9493. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9494. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9495. "uniform float shadowBias[ MAX_SHADOWS ];",
  9496. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9497. "float unpackDepth( const in vec4 rgba_depth ) {",
  9498. "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 );",
  9499. "float depth = dot( rgba_depth, bit_shift );",
  9500. "return depth;",
  9501. "}",
  9502. "#endif"
  9503. ].join("\n"),
  9504. shadowmap_fragment: [
  9505. "#ifdef USE_SHADOWMAP",
  9506. "#ifdef SHADOWMAP_DEBUG",
  9507. "vec3 frustumColors[3];",
  9508. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9509. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9510. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9511. "#endif",
  9512. "#ifdef SHADOWMAP_CASCADE",
  9513. "int inFrustumCount = 0;",
  9514. "#endif",
  9515. "float fDepth;",
  9516. "vec3 shadowColor = vec3( 1.0 );",
  9517. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9518. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9519. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9520. // "if ( all( something, something ) )" using this instead
  9521. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9522. "bool inFrustum = all( inFrustumVec );",
  9523. // don't shadow pixels outside of light frustum
  9524. // use just first frustum (for cascades)
  9525. // don't shadow pixels behind far plane of light frustum
  9526. "#ifdef SHADOWMAP_CASCADE",
  9527. "inFrustumCount += int( inFrustum );",
  9528. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9529. "#else",
  9530. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9531. "#endif",
  9532. "bool frustumTest = all( frustumTestVec );",
  9533. "if ( frustumTest ) {",
  9534. "shadowCoord.z += shadowBias[ i ];",
  9535. "#if defined( SHADOWMAP_TYPE_PCF )",
  9536. // Percentage-close filtering
  9537. // (9 pixel kernel)
  9538. // http://fabiensanglard.net/shadowmappingPCF/
  9539. "float shadow = 0.0;",
  9540. /*
  9541. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9542. // must enroll loop manually
  9543. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9544. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9545. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9546. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9547. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9548. "float fDepth = unpackDepth( rgbaDepth );",
  9549. "if ( fDepth < shadowCoord.z )",
  9550. "shadow += 1.0;",
  9551. "}",
  9552. "shadow /= 9.0;",
  9553. */
  9554. "const float shadowDelta = 1.0 / 9.0;",
  9555. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9556. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9557. "float dx0 = -1.25 * xPixelOffset;",
  9558. "float dy0 = -1.25 * yPixelOffset;",
  9559. "float dx1 = 1.25 * xPixelOffset;",
  9560. "float dy1 = 1.25 * yPixelOffset;",
  9561. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9562. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9563. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9564. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9565. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9566. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9567. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9568. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9569. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9570. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9571. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9572. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9573. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9574. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9575. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9576. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9577. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9578. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9579. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9580. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9581. // Percentage-close filtering
  9582. // (9 pixel kernel)
  9583. // http://fabiensanglard.net/shadowmappingPCF/
  9584. "float shadow = 0.0;",
  9585. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9586. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9587. "float dx0 = -1.0 * xPixelOffset;",
  9588. "float dy0 = -1.0 * yPixelOffset;",
  9589. "float dx1 = 1.0 * xPixelOffset;",
  9590. "float dy1 = 1.0 * yPixelOffset;",
  9591. "mat3 shadowKernel;",
  9592. "mat3 depthKernel;",
  9593. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9594. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9595. "else shadowKernel[0][0] = 0.0;",
  9596. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9597. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9598. "else shadowKernel[0][1] = 0.0;",
  9599. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9600. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9601. "else shadowKernel[0][2] = 0.0;",
  9602. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9603. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9604. "else shadowKernel[1][0] = 0.0;",
  9605. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9606. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9607. "else shadowKernel[1][1] = 0.0;",
  9608. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9609. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9610. "else shadowKernel[1][2] = 0.0;",
  9611. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9612. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9613. "else shadowKernel[2][0] = 0.0;",
  9614. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9615. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9616. "else shadowKernel[2][1] = 0.0;",
  9617. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9618. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9619. "else shadowKernel[2][2] = 0.0;",
  9620. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9621. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9622. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9623. "vec4 shadowValues;",
  9624. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9625. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9626. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9627. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9628. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9629. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9630. "#else",
  9631. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9632. "float fDepth = unpackDepth( rgbaDepth );",
  9633. "if ( fDepth < shadowCoord.z )",
  9634. // spot with multiple shadows is darker
  9635. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9636. // spot with multiple shadows has the same color as single shadow spot
  9637. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9638. "#endif",
  9639. "}",
  9640. "#ifdef SHADOWMAP_DEBUG",
  9641. "#ifdef SHADOWMAP_CASCADE",
  9642. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9643. "#else",
  9644. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9645. "#endif",
  9646. "#endif",
  9647. "}",
  9648. "#ifdef GAMMA_OUTPUT",
  9649. "shadowColor *= shadowColor;",
  9650. "#endif",
  9651. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9652. "#endif"
  9653. ].join("\n"),
  9654. shadowmap_pars_vertex: [
  9655. "#ifdef USE_SHADOWMAP",
  9656. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9657. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9658. "#endif"
  9659. ].join("\n"),
  9660. shadowmap_vertex: [
  9661. "#ifdef USE_SHADOWMAP",
  9662. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9663. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9664. "}",
  9665. "#endif"
  9666. ].join("\n"),
  9667. // ALPHATEST
  9668. alphatest_fragment: [
  9669. "#ifdef ALPHATEST",
  9670. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9671. "#endif"
  9672. ].join("\n"),
  9673. // LINEAR SPACE
  9674. linear_to_gamma_fragment: [
  9675. "#ifdef GAMMA_OUTPUT",
  9676. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9677. "#endif"
  9678. ].join("\n")
  9679. };
  9680. THREE.UniformsUtils = {
  9681. merge: function ( uniforms ) {
  9682. var u, p, tmp, merged = {};
  9683. for ( u = 0; u < uniforms.length; u ++ ) {
  9684. tmp = this.clone( uniforms[ u ] );
  9685. for ( p in tmp ) {
  9686. merged[ p ] = tmp[ p ];
  9687. }
  9688. }
  9689. return merged;
  9690. },
  9691. clone: function ( uniforms_src ) {
  9692. var u, p, parameter, parameter_src, uniforms_dst = {};
  9693. for ( u in uniforms_src ) {
  9694. uniforms_dst[ u ] = {};
  9695. for ( p in uniforms_src[ u ] ) {
  9696. parameter_src = uniforms_src[ u ][ p ];
  9697. if ( parameter_src instanceof THREE.Color ||
  9698. parameter_src instanceof THREE.Vector2 ||
  9699. parameter_src instanceof THREE.Vector3 ||
  9700. parameter_src instanceof THREE.Vector4 ||
  9701. parameter_src instanceof THREE.Matrix4 ||
  9702. parameter_src instanceof THREE.Texture ) {
  9703. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9704. } else if ( parameter_src instanceof Array ) {
  9705. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9706. } else {
  9707. uniforms_dst[ u ][ p ] = parameter_src;
  9708. }
  9709. }
  9710. }
  9711. return uniforms_dst;
  9712. }
  9713. };
  9714. THREE.UniformsLib = {
  9715. common: {
  9716. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9717. "opacity" : { type: "f", value: 1.0 },
  9718. "map" : { type: "t", value: null },
  9719. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9720. "lightMap" : { type: "t", value: null },
  9721. "specularMap" : { type: "t", value: null },
  9722. "envMap" : { type: "t", value: null },
  9723. "flipEnvMap" : { type: "f", value: -1 },
  9724. "useRefract" : { type: "i", value: 0 },
  9725. "reflectivity" : { type: "f", value: 1.0 },
  9726. "refractionRatio" : { type: "f", value: 0.98 },
  9727. "combine" : { type: "i", value: 0 },
  9728. "morphTargetInfluences" : { type: "f", value: 0 }
  9729. },
  9730. bump: {
  9731. "bumpMap" : { type: "t", value: null },
  9732. "bumpScale" : { type: "f", value: 1 }
  9733. },
  9734. normalmap: {
  9735. "normalMap" : { type: "t", value: null },
  9736. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9737. },
  9738. fog : {
  9739. "fogDensity" : { type: "f", value: 0.00025 },
  9740. "fogNear" : { type: "f", value: 1 },
  9741. "fogFar" : { type: "f", value: 2000 },
  9742. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9743. },
  9744. lights: {
  9745. "ambientLightColor" : { type: "fv", value: [] },
  9746. "directionalLightDirection" : { type: "fv", value: [] },
  9747. "directionalLightColor" : { type: "fv", value: [] },
  9748. "hemisphereLightDirection" : { type: "fv", value: [] },
  9749. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9750. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9751. "pointLightColor" : { type: "fv", value: [] },
  9752. "pointLightPosition" : { type: "fv", value: [] },
  9753. "pointLightDistance" : { type: "fv1", value: [] },
  9754. "spotLightColor" : { type: "fv", value: [] },
  9755. "spotLightPosition" : { type: "fv", value: [] },
  9756. "spotLightDirection" : { type: "fv", value: [] },
  9757. "spotLightDistance" : { type: "fv1", value: [] },
  9758. "spotLightAngleCos" : { type: "fv1", value: [] },
  9759. "spotLightExponent" : { type: "fv1", value: [] }
  9760. },
  9761. particle: {
  9762. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9763. "opacity" : { type: "f", value: 1.0 },
  9764. "size" : { type: "f", value: 1.0 },
  9765. "scale" : { type: "f", value: 1.0 },
  9766. "map" : { type: "t", value: null },
  9767. "fogDensity" : { type: "f", value: 0.00025 },
  9768. "fogNear" : { type: "f", value: 1 },
  9769. "fogFar" : { type: "f", value: 2000 },
  9770. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9771. },
  9772. shadowmap: {
  9773. "shadowMap": { type: "tv", value: [] },
  9774. "shadowMapSize": { type: "v2v", value: [] },
  9775. "shadowBias" : { type: "fv1", value: [] },
  9776. "shadowDarkness": { type: "fv1", value: [] },
  9777. "shadowMatrix" : { type: "m4v", value: [] }
  9778. }
  9779. };
  9780. THREE.ShaderLib = {
  9781. 'depth': {
  9782. uniforms: {
  9783. "mNear": { type: "f", value: 1.0 },
  9784. "mFar" : { type: "f", value: 2000.0 },
  9785. "opacity" : { type: "f", value: 1.0 }
  9786. },
  9787. vertexShader: [
  9788. "void main() {",
  9789. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9790. "}"
  9791. ].join("\n"),
  9792. fragmentShader: [
  9793. "uniform float mNear;",
  9794. "uniform float mFar;",
  9795. "uniform float opacity;",
  9796. "void main() {",
  9797. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9798. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9799. "gl_FragColor = vec4( vec3( color ), opacity );",
  9800. "}"
  9801. ].join("\n")
  9802. },
  9803. 'normal': {
  9804. uniforms: {
  9805. "opacity" : { type: "f", value: 1.0 }
  9806. },
  9807. vertexShader: [
  9808. "varying vec3 vNormal;",
  9809. "void main() {",
  9810. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9811. "vNormal = normalize( normalMatrix * normal );",
  9812. "gl_Position = projectionMatrix * mvPosition;",
  9813. "}"
  9814. ].join("\n"),
  9815. fragmentShader: [
  9816. "uniform float opacity;",
  9817. "varying vec3 vNormal;",
  9818. "void main() {",
  9819. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9820. "}"
  9821. ].join("\n")
  9822. },
  9823. 'basic': {
  9824. uniforms: THREE.UniformsUtils.merge( [
  9825. THREE.UniformsLib[ "common" ],
  9826. THREE.UniformsLib[ "fog" ],
  9827. THREE.UniformsLib[ "shadowmap" ]
  9828. ] ),
  9829. vertexShader: [
  9830. THREE.ShaderChunk[ "map_pars_vertex" ],
  9831. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9832. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9833. THREE.ShaderChunk[ "color_pars_vertex" ],
  9834. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9835. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9836. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9837. "void main() {",
  9838. THREE.ShaderChunk[ "map_vertex" ],
  9839. THREE.ShaderChunk[ "lightmap_vertex" ],
  9840. THREE.ShaderChunk[ "color_vertex" ],
  9841. "#ifdef USE_ENVMAP",
  9842. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9843. THREE.ShaderChunk[ "skinbase_vertex" ],
  9844. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9845. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9846. "#endif",
  9847. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9848. THREE.ShaderChunk[ "skinning_vertex" ],
  9849. THREE.ShaderChunk[ "default_vertex" ],
  9850. THREE.ShaderChunk[ "worldpos_vertex" ],
  9851. THREE.ShaderChunk[ "envmap_vertex" ],
  9852. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9853. "}"
  9854. ].join("\n"),
  9855. fragmentShader: [
  9856. "uniform vec3 diffuse;",
  9857. "uniform float opacity;",
  9858. THREE.ShaderChunk[ "color_pars_fragment" ],
  9859. THREE.ShaderChunk[ "map_pars_fragment" ],
  9860. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9861. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9862. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9863. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9864. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9865. "void main() {",
  9866. "gl_FragColor = vec4( diffuse, opacity );",
  9867. THREE.ShaderChunk[ "map_fragment" ],
  9868. THREE.ShaderChunk[ "alphatest_fragment" ],
  9869. THREE.ShaderChunk[ "specularmap_fragment" ],
  9870. THREE.ShaderChunk[ "lightmap_fragment" ],
  9871. THREE.ShaderChunk[ "color_fragment" ],
  9872. THREE.ShaderChunk[ "envmap_fragment" ],
  9873. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9874. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9875. THREE.ShaderChunk[ "fog_fragment" ],
  9876. "}"
  9877. ].join("\n")
  9878. },
  9879. 'lambert': {
  9880. uniforms: THREE.UniformsUtils.merge( [
  9881. THREE.UniformsLib[ "common" ],
  9882. THREE.UniformsLib[ "fog" ],
  9883. THREE.UniformsLib[ "lights" ],
  9884. THREE.UniformsLib[ "shadowmap" ],
  9885. {
  9886. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9887. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9888. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9889. }
  9890. ] ),
  9891. vertexShader: [
  9892. "#define LAMBERT",
  9893. "varying vec3 vLightFront;",
  9894. "#ifdef DOUBLE_SIDED",
  9895. "varying vec3 vLightBack;",
  9896. "#endif",
  9897. THREE.ShaderChunk[ "map_pars_vertex" ],
  9898. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9899. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9900. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9901. THREE.ShaderChunk[ "color_pars_vertex" ],
  9902. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9903. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9904. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9905. "void main() {",
  9906. THREE.ShaderChunk[ "map_vertex" ],
  9907. THREE.ShaderChunk[ "lightmap_vertex" ],
  9908. THREE.ShaderChunk[ "color_vertex" ],
  9909. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9910. THREE.ShaderChunk[ "skinbase_vertex" ],
  9911. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9912. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9913. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9914. THREE.ShaderChunk[ "skinning_vertex" ],
  9915. THREE.ShaderChunk[ "default_vertex" ],
  9916. THREE.ShaderChunk[ "worldpos_vertex" ],
  9917. THREE.ShaderChunk[ "envmap_vertex" ],
  9918. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9919. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9920. "}"
  9921. ].join("\n"),
  9922. fragmentShader: [
  9923. "uniform float opacity;",
  9924. "varying vec3 vLightFront;",
  9925. "#ifdef DOUBLE_SIDED",
  9926. "varying vec3 vLightBack;",
  9927. "#endif",
  9928. THREE.ShaderChunk[ "color_pars_fragment" ],
  9929. THREE.ShaderChunk[ "map_pars_fragment" ],
  9930. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9931. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9932. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9933. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9934. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9935. "void main() {",
  9936. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9937. THREE.ShaderChunk[ "map_fragment" ],
  9938. THREE.ShaderChunk[ "alphatest_fragment" ],
  9939. THREE.ShaderChunk[ "specularmap_fragment" ],
  9940. "#ifdef DOUBLE_SIDED",
  9941. //"float isFront = float( gl_FrontFacing );",
  9942. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9943. "if ( gl_FrontFacing )",
  9944. "gl_FragColor.xyz *= vLightFront;",
  9945. "else",
  9946. "gl_FragColor.xyz *= vLightBack;",
  9947. "#else",
  9948. "gl_FragColor.xyz *= vLightFront;",
  9949. "#endif",
  9950. THREE.ShaderChunk[ "lightmap_fragment" ],
  9951. THREE.ShaderChunk[ "color_fragment" ],
  9952. THREE.ShaderChunk[ "envmap_fragment" ],
  9953. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9954. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9955. THREE.ShaderChunk[ "fog_fragment" ],
  9956. "}"
  9957. ].join("\n")
  9958. },
  9959. 'phong': {
  9960. uniforms: THREE.UniformsUtils.merge( [
  9961. THREE.UniformsLib[ "common" ],
  9962. THREE.UniformsLib[ "bump" ],
  9963. THREE.UniformsLib[ "normalmap" ],
  9964. THREE.UniformsLib[ "fog" ],
  9965. THREE.UniformsLib[ "lights" ],
  9966. THREE.UniformsLib[ "shadowmap" ],
  9967. {
  9968. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9969. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9970. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9971. "shininess": { type: "f", value: 30 },
  9972. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9973. }
  9974. ] ),
  9975. vertexShader: [
  9976. "#define PHONG",
  9977. "varying vec3 vViewPosition;",
  9978. "varying vec3 vNormal;",
  9979. THREE.ShaderChunk[ "map_pars_vertex" ],
  9980. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9981. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9982. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9983. THREE.ShaderChunk[ "color_pars_vertex" ],
  9984. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9985. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9986. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9987. "void main() {",
  9988. THREE.ShaderChunk[ "map_vertex" ],
  9989. THREE.ShaderChunk[ "lightmap_vertex" ],
  9990. THREE.ShaderChunk[ "color_vertex" ],
  9991. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9992. THREE.ShaderChunk[ "skinbase_vertex" ],
  9993. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9994. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9995. "vNormal = normalize( transformedNormal );",
  9996. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9997. THREE.ShaderChunk[ "skinning_vertex" ],
  9998. THREE.ShaderChunk[ "default_vertex" ],
  9999. "vViewPosition = -mvPosition.xyz;",
  10000. THREE.ShaderChunk[ "worldpos_vertex" ],
  10001. THREE.ShaderChunk[ "envmap_vertex" ],
  10002. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10003. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10004. "}"
  10005. ].join("\n"),
  10006. fragmentShader: [
  10007. "uniform vec3 diffuse;",
  10008. "uniform float opacity;",
  10009. "uniform vec3 ambient;",
  10010. "uniform vec3 emissive;",
  10011. "uniform vec3 specular;",
  10012. "uniform float shininess;",
  10013. THREE.ShaderChunk[ "color_pars_fragment" ],
  10014. THREE.ShaderChunk[ "map_pars_fragment" ],
  10015. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10016. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10017. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10018. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10019. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10020. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10021. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10022. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10023. "void main() {",
  10024. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10025. THREE.ShaderChunk[ "map_fragment" ],
  10026. THREE.ShaderChunk[ "alphatest_fragment" ],
  10027. THREE.ShaderChunk[ "specularmap_fragment" ],
  10028. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10029. THREE.ShaderChunk[ "lightmap_fragment" ],
  10030. THREE.ShaderChunk[ "color_fragment" ],
  10031. THREE.ShaderChunk[ "envmap_fragment" ],
  10032. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10033. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10034. THREE.ShaderChunk[ "fog_fragment" ],
  10035. "}"
  10036. ].join("\n")
  10037. },
  10038. 'particle_basic': {
  10039. uniforms: THREE.UniformsUtils.merge( [
  10040. THREE.UniformsLib[ "particle" ],
  10041. THREE.UniformsLib[ "shadowmap" ]
  10042. ] ),
  10043. vertexShader: [
  10044. "uniform float size;",
  10045. "uniform float scale;",
  10046. THREE.ShaderChunk[ "color_pars_vertex" ],
  10047. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10048. "void main() {",
  10049. THREE.ShaderChunk[ "color_vertex" ],
  10050. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10051. "#ifdef USE_SIZEATTENUATION",
  10052. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10053. "#else",
  10054. "gl_PointSize = size;",
  10055. "#endif",
  10056. "gl_Position = projectionMatrix * mvPosition;",
  10057. THREE.ShaderChunk[ "worldpos_vertex" ],
  10058. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10059. "}"
  10060. ].join("\n"),
  10061. fragmentShader: [
  10062. "uniform vec3 psColor;",
  10063. "uniform float opacity;",
  10064. THREE.ShaderChunk[ "color_pars_fragment" ],
  10065. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10066. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10067. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10068. "void main() {",
  10069. "gl_FragColor = vec4( psColor, opacity );",
  10070. THREE.ShaderChunk[ "map_particle_fragment" ],
  10071. THREE.ShaderChunk[ "alphatest_fragment" ],
  10072. THREE.ShaderChunk[ "color_fragment" ],
  10073. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10074. THREE.ShaderChunk[ "fog_fragment" ],
  10075. "}"
  10076. ].join("\n")
  10077. },
  10078. 'dashed': {
  10079. uniforms: THREE.UniformsUtils.merge( [
  10080. THREE.UniformsLib[ "common" ],
  10081. THREE.UniformsLib[ "fog" ],
  10082. {
  10083. "scale": { type: "f", value: 1 },
  10084. "dashSize": { type: "f", value: 1 },
  10085. "totalSize": { type: "f", value: 2 }
  10086. }
  10087. ] ),
  10088. vertexShader: [
  10089. "uniform float scale;",
  10090. "attribute float lineDistance;",
  10091. "varying float vLineDistance;",
  10092. THREE.ShaderChunk[ "color_pars_vertex" ],
  10093. "void main() {",
  10094. THREE.ShaderChunk[ "color_vertex" ],
  10095. "vLineDistance = scale * lineDistance;",
  10096. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10097. "gl_Position = projectionMatrix * mvPosition;",
  10098. "}"
  10099. ].join("\n"),
  10100. fragmentShader: [
  10101. "uniform vec3 diffuse;",
  10102. "uniform float opacity;",
  10103. "uniform float dashSize;",
  10104. "uniform float totalSize;",
  10105. "varying float vLineDistance;",
  10106. THREE.ShaderChunk[ "color_pars_fragment" ],
  10107. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10108. "void main() {",
  10109. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10110. "discard;",
  10111. "}",
  10112. "gl_FragColor = vec4( diffuse, opacity );",
  10113. THREE.ShaderChunk[ "color_fragment" ],
  10114. THREE.ShaderChunk[ "fog_fragment" ],
  10115. "}"
  10116. ].join("\n")
  10117. },
  10118. // Depth encoding into RGBA texture
  10119. // based on SpiderGL shadow map example
  10120. // http://spidergl.org/example.php?id=6
  10121. // originally from
  10122. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10123. // see also here:
  10124. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10125. 'depthRGBA': {
  10126. uniforms: {},
  10127. vertexShader: [
  10128. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10129. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10130. "void main() {",
  10131. THREE.ShaderChunk[ "skinbase_vertex" ],
  10132. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10133. THREE.ShaderChunk[ "skinning_vertex" ],
  10134. THREE.ShaderChunk[ "default_vertex" ],
  10135. "}"
  10136. ].join("\n"),
  10137. fragmentShader: [
  10138. "vec4 pack_depth( const in float depth ) {",
  10139. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10140. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10141. "vec4 res = fract( depth * bit_shift );",
  10142. "res -= res.xxyz * bit_mask;",
  10143. "return res;",
  10144. "}",
  10145. "void main() {",
  10146. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10147. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10148. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10149. //"gl_FragData[ 0 ] = pack_depth( z );",
  10150. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10151. "}"
  10152. ].join("\n")
  10153. }
  10154. };
  10155. /**
  10156. * @author supereggbert / http://www.paulbrunt.co.uk/
  10157. * @author mrdoob / http://mrdoob.com/
  10158. * @author alteredq / http://alteredqualia.com/
  10159. * @author szimek / https://github.com/szimek/
  10160. */
  10161. THREE.WebGLRenderer = function ( parameters ) {
  10162. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10163. parameters = parameters || {};
  10164. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10165. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10166. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10167. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10168. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10169. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10170. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10171. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10172. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10173. // public properties
  10174. this.domElement = _canvas;
  10175. this.context = null;
  10176. // clearing
  10177. this.autoClear = true;
  10178. this.autoClearColor = true;
  10179. this.autoClearDepth = true;
  10180. this.autoClearStencil = true;
  10181. // scene graph
  10182. this.sortObjects = true;
  10183. this.autoUpdateObjects = true;
  10184. this.autoUpdateScene = true;
  10185. // physically based shading
  10186. this.gammaInput = false;
  10187. this.gammaOutput = false;
  10188. this.physicallyBasedShading = false;
  10189. // shadow map
  10190. this.shadowMapEnabled = false;
  10191. this.shadowMapAutoUpdate = true;
  10192. this.shadowMapType = THREE.PCFShadowMap;
  10193. this.shadowMapCullFace = THREE.CullFaceFront;
  10194. this.shadowMapDebug = false;
  10195. this.shadowMapCascade = false;
  10196. // morphs
  10197. this.maxMorphTargets = 8;
  10198. this.maxMorphNormals = 4;
  10199. // flags
  10200. this.autoScaleCubemaps = true;
  10201. // custom render plugins
  10202. this.renderPluginsPre = [];
  10203. this.renderPluginsPost = [];
  10204. // info
  10205. this.info = {
  10206. memory: {
  10207. programs: 0,
  10208. geometries: 0,
  10209. textures: 0
  10210. },
  10211. render: {
  10212. calls: 0,
  10213. vertices: 0,
  10214. faces: 0,
  10215. points: 0
  10216. }
  10217. };
  10218. // internal properties
  10219. var _this = this,
  10220. _programs = [],
  10221. _programs_counter = 0,
  10222. // internal state cache
  10223. _currentProgram = null,
  10224. _currentFramebuffer = null,
  10225. _currentMaterialId = -1,
  10226. _currentGeometryGroupHash = null,
  10227. _currentCamera = null,
  10228. _geometryGroupCounter = 0,
  10229. _usedTextureUnits = 0,
  10230. // GL state cache
  10231. _oldDoubleSided = -1,
  10232. _oldFlipSided = -1,
  10233. _oldBlending = -1,
  10234. _oldBlendEquation = -1,
  10235. _oldBlendSrc = -1,
  10236. _oldBlendDst = -1,
  10237. _oldDepthTest = -1,
  10238. _oldDepthWrite = -1,
  10239. _oldPolygonOffset = null,
  10240. _oldPolygonOffsetFactor = null,
  10241. _oldPolygonOffsetUnits = null,
  10242. _oldLineWidth = null,
  10243. _viewportX = 0,
  10244. _viewportY = 0,
  10245. _viewportWidth = 0,
  10246. _viewportHeight = 0,
  10247. _currentWidth = 0,
  10248. _currentHeight = 0,
  10249. _enabledAttributes = {},
  10250. // frustum
  10251. _frustum = new THREE.Frustum(),
  10252. // camera matrices cache
  10253. _projScreenMatrix = new THREE.Matrix4(),
  10254. _projScreenMatrixPS = new THREE.Matrix4(),
  10255. _vector3 = new THREE.Vector3(),
  10256. // light arrays cache
  10257. _direction = new THREE.Vector3(),
  10258. _lightsNeedUpdate = true,
  10259. _lights = {
  10260. ambient: [ 0, 0, 0 ],
  10261. directional: { length: 0, colors: new Array(), positions: new Array() },
  10262. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10263. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10264. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10265. };
  10266. // initialize
  10267. var _gl;
  10268. var _glExtensionTextureFloat;
  10269. var _glExtensionStandardDerivatives;
  10270. var _glExtensionTextureFilterAnisotropic;
  10271. var _glExtensionCompressedTextureS3TC;
  10272. initGL();
  10273. setDefaultGLState();
  10274. this.context = _gl;
  10275. // GPU capabilities
  10276. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10277. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10278. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10279. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10280. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10281. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10282. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10283. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10284. //
  10285. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10286. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10287. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10288. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10289. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10290. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10291. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10292. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10293. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10294. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10295. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10296. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10297. // clamp precision to maximum available
  10298. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10299. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10300. if ( _precision === "highp" && ! highpAvailable ) {
  10301. if ( mediumpAvailable ) {
  10302. _precision = "mediump";
  10303. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10304. } else {
  10305. _precision = "lowp";
  10306. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10307. }
  10308. }
  10309. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10310. _precision = "lowp";
  10311. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10312. }
  10313. // API
  10314. this.getContext = function () {
  10315. return _gl;
  10316. };
  10317. this.supportsVertexTextures = function () {
  10318. return _supportsVertexTextures;
  10319. };
  10320. this.getMaxAnisotropy = function () {
  10321. return _maxAnisotropy;
  10322. };
  10323. this.setSize = function ( width, height ) {
  10324. _canvas.width = width;
  10325. _canvas.height = height;
  10326. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10327. };
  10328. this.setViewport = function ( x, y, width, height ) {
  10329. _viewportX = x !== undefined ? x : 0;
  10330. _viewportY = y !== undefined ? y : 0;
  10331. _viewportWidth = width !== undefined ? width : _canvas.width;
  10332. _viewportHeight = height !== undefined ? height : _canvas.height;
  10333. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10334. };
  10335. this.setScissor = function ( x, y, width, height ) {
  10336. _gl.scissor( x, y, width, height );
  10337. };
  10338. this.enableScissorTest = function ( enable ) {
  10339. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10340. };
  10341. // Clearing
  10342. this.setClearColorHex = function ( hex, alpha ) {
  10343. _clearColor.setHex( hex );
  10344. _clearAlpha = alpha;
  10345. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10346. };
  10347. this.setClearColor = function ( color, alpha ) {
  10348. _clearColor.copy( color );
  10349. _clearAlpha = alpha;
  10350. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10351. };
  10352. this.getClearColor = function () {
  10353. return _clearColor;
  10354. };
  10355. this.getClearAlpha = function () {
  10356. return _clearAlpha;
  10357. };
  10358. this.clear = function ( color, depth, stencil ) {
  10359. var bits = 0;
  10360. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10361. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10362. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10363. _gl.clear( bits );
  10364. };
  10365. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10366. this.setRenderTarget( renderTarget );
  10367. this.clear( color, depth, stencil );
  10368. };
  10369. // Plugins
  10370. this.addPostPlugin = function ( plugin ) {
  10371. plugin.init( this );
  10372. this.renderPluginsPost.push( plugin );
  10373. };
  10374. this.addPrePlugin = function ( plugin ) {
  10375. plugin.init( this );
  10376. this.renderPluginsPre.push( plugin );
  10377. };
  10378. // Deallocation
  10379. this.deallocateObject = function ( object ) {
  10380. if ( ! object.__webglInit ) return;
  10381. object.__webglInit = false;
  10382. delete object._modelViewMatrix;
  10383. delete object._normalMatrix;
  10384. if ( object instanceof THREE.Mesh ) {
  10385. for ( var g in object.geometry.geometryGroups ) {
  10386. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  10387. }
  10388. } else if ( object instanceof THREE.Ribbon ) {
  10389. deleteRibbonBuffers( object.geometry );
  10390. } else if ( object instanceof THREE.Line ) {
  10391. deleteLineBuffers( object.geometry );
  10392. } else if ( object instanceof THREE.ParticleSystem ) {
  10393. deleteParticleBuffers( object.geometry );
  10394. }
  10395. };
  10396. this.deallocateTexture = function ( texture ) {
  10397. // cube texture
  10398. if ( texture.image && texture.image.__webglTextureCube ) {
  10399. _gl.deleteTexture( texture.image.__webglTextureCube );
  10400. // 2D texture
  10401. } else {
  10402. if ( ! texture.__webglInit ) return;
  10403. texture.__webglInit = false;
  10404. _gl.deleteTexture( texture.__webglTexture );
  10405. }
  10406. _this.info.memory.textures --;
  10407. };
  10408. this.deallocateRenderTarget = function ( renderTarget ) {
  10409. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10410. _gl.deleteTexture( renderTarget.__webglTexture );
  10411. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10412. for ( var i = 0; i < 6; i ++ ) {
  10413. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10414. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10415. }
  10416. } else {
  10417. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10418. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10419. }
  10420. };
  10421. this.deallocateMaterial = function ( material ) {
  10422. var program = material.program;
  10423. if ( ! program ) return;
  10424. material.program = undefined;
  10425. // only deallocate GL program if this was the last use of shared program
  10426. // assumed there is only single copy of any program in the _programs list
  10427. // (that's how it's constructed)
  10428. var i, il, programInfo;
  10429. var deleteProgram = false;
  10430. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10431. programInfo = _programs[ i ];
  10432. if ( programInfo.program === program ) {
  10433. programInfo.usedTimes --;
  10434. if ( programInfo.usedTimes === 0 ) {
  10435. deleteProgram = true;
  10436. }
  10437. break;
  10438. }
  10439. }
  10440. if ( deleteProgram ) {
  10441. // avoid using array.splice, this is costlier than creating new array from scratch
  10442. var newPrograms = [];
  10443. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10444. programInfo = _programs[ i ];
  10445. if ( programInfo.program !== program ) {
  10446. newPrograms.push( programInfo );
  10447. }
  10448. }
  10449. _programs = newPrograms;
  10450. _gl.deleteProgram( program );
  10451. _this.info.memory.programs --;
  10452. }
  10453. };
  10454. // Rendering
  10455. this.updateShadowMap = function ( scene, camera ) {
  10456. _currentProgram = null;
  10457. _oldBlending = -1;
  10458. _oldDepthTest = -1;
  10459. _oldDepthWrite = -1;
  10460. _currentGeometryGroupHash = -1;
  10461. _currentMaterialId = -1;
  10462. _lightsNeedUpdate = true;
  10463. _oldDoubleSided = -1;
  10464. _oldFlipSided = -1;
  10465. this.shadowMapPlugin.update( scene, camera );
  10466. };
  10467. // Internal functions
  10468. // Buffer allocation
  10469. function createParticleBuffers ( geometry ) {
  10470. geometry.__webglVertexBuffer = _gl.createBuffer();
  10471. geometry.__webglColorBuffer = _gl.createBuffer();
  10472. _this.info.memory.geometries ++;
  10473. };
  10474. function createLineBuffers ( geometry ) {
  10475. geometry.__webglVertexBuffer = _gl.createBuffer();
  10476. geometry.__webglColorBuffer = _gl.createBuffer();
  10477. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10478. _this.info.memory.geometries ++;
  10479. };
  10480. function createRibbonBuffers ( geometry ) {
  10481. geometry.__webglVertexBuffer = _gl.createBuffer();
  10482. geometry.__webglColorBuffer = _gl.createBuffer();
  10483. geometry.__webglNormalBuffer = _gl.createBuffer();
  10484. _this.info.memory.geometries ++;
  10485. };
  10486. function createMeshBuffers ( geometryGroup ) {
  10487. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10488. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10489. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10490. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10491. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10492. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10493. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10494. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10495. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10496. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10497. var m, ml;
  10498. if ( geometryGroup.numMorphTargets ) {
  10499. geometryGroup.__webglMorphTargetsBuffers = [];
  10500. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10501. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10502. }
  10503. }
  10504. if ( geometryGroup.numMorphNormals ) {
  10505. geometryGroup.__webglMorphNormalsBuffers = [];
  10506. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10507. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10508. }
  10509. }
  10510. _this.info.memory.geometries ++;
  10511. };
  10512. // Buffer deallocation
  10513. function deleteParticleBuffers ( geometry ) {
  10514. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10515. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10516. deleteCustomAttributesBuffers( geometry );
  10517. _this.info.memory.geometries --;
  10518. };
  10519. function deleteLineBuffers ( geometry ) {
  10520. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10521. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10522. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10523. deleteCustomAttributesBuffers( geometry );
  10524. _this.info.memory.geometries --;
  10525. };
  10526. function deleteRibbonBuffers ( geometry ) {
  10527. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10528. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10529. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10530. deleteCustomAttributesBuffers( geometry );
  10531. _this.info.memory.geometries --;
  10532. };
  10533. function deleteMeshBuffers ( geometryGroup ) {
  10534. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  10535. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  10536. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  10537. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  10538. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  10539. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  10540. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  10541. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  10542. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  10543. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  10544. var m, ml;
  10545. if ( geometryGroup.numMorphTargets ) {
  10546. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10547. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10548. }
  10549. }
  10550. if ( geometryGroup.numMorphNormals ) {
  10551. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10552. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10553. }
  10554. }
  10555. deleteCustomAttributesBuffers( geometryGroup );
  10556. _this.info.memory.geometries --;
  10557. };
  10558. function deleteCustomAttributesBuffers( geometry ) {
  10559. if ( geometry.__webglCustomAttributesList ) {
  10560. for ( var id in geometry.__webglCustomAttributesList ) {
  10561. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10562. }
  10563. }
  10564. };
  10565. // Buffer initialization
  10566. function initCustomAttributes ( geometry, object ) {
  10567. var nvertices = geometry.vertices.length;
  10568. var material = object.material;
  10569. if ( material.attributes ) {
  10570. if ( geometry.__webglCustomAttributesList === undefined ) {
  10571. geometry.__webglCustomAttributesList = [];
  10572. }
  10573. for ( var a in material.attributes ) {
  10574. var attribute = material.attributes[ a ];
  10575. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10576. attribute.__webglInitialized = true;
  10577. var size = 1; // "f" and "i"
  10578. if ( attribute.type === "v2" ) size = 2;
  10579. else if ( attribute.type === "v3" ) size = 3;
  10580. else if ( attribute.type === "v4" ) size = 4;
  10581. else if ( attribute.type === "c" ) size = 3;
  10582. attribute.size = size;
  10583. attribute.array = new Float32Array( nvertices * size );
  10584. attribute.buffer = _gl.createBuffer();
  10585. attribute.buffer.belongsToAttribute = a;
  10586. attribute.needsUpdate = true;
  10587. }
  10588. geometry.__webglCustomAttributesList.push( attribute );
  10589. }
  10590. }
  10591. };
  10592. function initParticleBuffers ( geometry, object ) {
  10593. var nvertices = geometry.vertices.length;
  10594. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10595. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10596. geometry.__sortArray = [];
  10597. geometry.__webglParticleCount = nvertices;
  10598. initCustomAttributes ( geometry, object );
  10599. };
  10600. function initLineBuffers ( geometry, object ) {
  10601. var nvertices = geometry.vertices.length;
  10602. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10603. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10604. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  10605. geometry.__webglLineCount = nvertices;
  10606. initCustomAttributes ( geometry, object );
  10607. };
  10608. function initRibbonBuffers ( geometry, object ) {
  10609. var nvertices = geometry.vertices.length;
  10610. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10611. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10612. geometry.__normalArray = new Float32Array( nvertices * 3 );
  10613. geometry.__webglVertexCount = nvertices;
  10614. initCustomAttributes ( geometry, object );
  10615. };
  10616. function initMeshBuffers ( geometryGroup, object ) {
  10617. var geometry = object.geometry,
  10618. faces3 = geometryGroup.faces3,
  10619. faces4 = geometryGroup.faces4,
  10620. nvertices = faces3.length * 3 + faces4.length * 4,
  10621. ntris = faces3.length * 1 + faces4.length * 2,
  10622. nlines = faces3.length * 3 + faces4.length * 4,
  10623. material = getBufferMaterial( object, geometryGroup ),
  10624. uvType = bufferGuessUVType( material ),
  10625. normalType = bufferGuessNormalType( material ),
  10626. vertexColorType = bufferGuessVertexColorType( material );
  10627. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  10628. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  10629. if ( normalType ) {
  10630. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  10631. }
  10632. if ( geometry.hasTangents ) {
  10633. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  10634. }
  10635. if ( vertexColorType ) {
  10636. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  10637. }
  10638. if ( uvType ) {
  10639. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  10640. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  10641. }
  10642. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  10643. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  10644. }
  10645. }
  10646. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  10647. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  10648. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  10649. }
  10650. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  10651. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  10652. var m, ml;
  10653. if ( geometryGroup.numMorphTargets ) {
  10654. geometryGroup.__morphTargetsArrays = [];
  10655. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10656. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  10657. }
  10658. }
  10659. if ( geometryGroup.numMorphNormals ) {
  10660. geometryGroup.__morphNormalsArrays = [];
  10661. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10662. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  10663. }
  10664. }
  10665. geometryGroup.__webglFaceCount = ntris * 3;
  10666. geometryGroup.__webglLineCount = nlines * 2;
  10667. // custom attributes
  10668. if ( material.attributes ) {
  10669. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  10670. geometryGroup.__webglCustomAttributesList = [];
  10671. }
  10672. for ( var a in material.attributes ) {
  10673. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  10674. // attribute buffers which are correctly indexed in the setMeshBuffers function
  10675. var originalAttribute = material.attributes[ a ];
  10676. var attribute = {};
  10677. for ( var property in originalAttribute ) {
  10678. attribute[ property ] = originalAttribute[ property ];
  10679. }
  10680. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10681. attribute.__webglInitialized = true;
  10682. var size = 1; // "f" and "i"
  10683. if( attribute.type === "v2" ) size = 2;
  10684. else if( attribute.type === "v3" ) size = 3;
  10685. else if( attribute.type === "v4" ) size = 4;
  10686. else if( attribute.type === "c" ) size = 3;
  10687. attribute.size = size;
  10688. attribute.array = new Float32Array( nvertices * size );
  10689. attribute.buffer = _gl.createBuffer();
  10690. attribute.buffer.belongsToAttribute = a;
  10691. originalAttribute.needsUpdate = true;
  10692. attribute.__original = originalAttribute;
  10693. }
  10694. geometryGroup.__webglCustomAttributesList.push( attribute );
  10695. }
  10696. }
  10697. geometryGroup.__inittedArrays = true;
  10698. };
  10699. function getBufferMaterial( object, geometryGroup ) {
  10700. return object.material instanceof THREE.MeshFaceMaterial
  10701. ? object.material.materials[ geometryGroup.materialIndex ]
  10702. : object.material;
  10703. };
  10704. function materialNeedsSmoothNormals ( material ) {
  10705. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  10706. };
  10707. function bufferGuessNormalType ( material ) {
  10708. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  10709. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  10710. return false;
  10711. }
  10712. if ( materialNeedsSmoothNormals( material ) ) {
  10713. return THREE.SmoothShading;
  10714. } else {
  10715. return THREE.FlatShading;
  10716. }
  10717. };
  10718. function bufferGuessVertexColorType ( material ) {
  10719. if ( material.vertexColors ) {
  10720. return material.vertexColors;
  10721. }
  10722. return false;
  10723. };
  10724. function bufferGuessUVType ( material ) {
  10725. // material must use some texture to require uvs
  10726. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  10727. return true;
  10728. }
  10729. return false;
  10730. };
  10731. //
  10732. function initDirectBuffers( geometry ) {
  10733. var a, attribute, type;
  10734. for ( a in geometry.attributes ) {
  10735. if ( a === "index" ) {
  10736. type = _gl.ELEMENT_ARRAY_BUFFER;
  10737. } else {
  10738. type = _gl.ARRAY_BUFFER;
  10739. }
  10740. attribute = geometry.attributes[ a ];
  10741. attribute.buffer = _gl.createBuffer();
  10742. _gl.bindBuffer( type, attribute.buffer );
  10743. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  10744. }
  10745. };
  10746. // Buffer setting
  10747. function setParticleBuffers ( geometry, hint, object ) {
  10748. var v, c, vertex, offset, index, color,
  10749. vertices = geometry.vertices,
  10750. vl = vertices.length,
  10751. colors = geometry.colors,
  10752. cl = colors.length,
  10753. vertexArray = geometry.__vertexArray,
  10754. colorArray = geometry.__colorArray,
  10755. sortArray = geometry.__sortArray,
  10756. dirtyVertices = geometry.verticesNeedUpdate,
  10757. dirtyElements = geometry.elementsNeedUpdate,
  10758. dirtyColors = geometry.colorsNeedUpdate,
  10759. customAttributes = geometry.__webglCustomAttributesList,
  10760. i, il,
  10761. a, ca, cal, value,
  10762. customAttribute;
  10763. if ( object.sortParticles ) {
  10764. _projScreenMatrixPS.copy( _projScreenMatrix );
  10765. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  10766. for ( v = 0; v < vl; v ++ ) {
  10767. vertex = vertices[ v ];
  10768. _vector3.copy( vertex );
  10769. _projScreenMatrixPS.multiplyVector3( _vector3 );
  10770. sortArray[ v ] = [ _vector3.z, v ];
  10771. }
  10772. sortArray.sort( numericalSort );
  10773. for ( v = 0; v < vl; v ++ ) {
  10774. vertex = vertices[ sortArray[v][1] ];
  10775. offset = v * 3;
  10776. vertexArray[ offset ] = vertex.x;
  10777. vertexArray[ offset + 1 ] = vertex.y;
  10778. vertexArray[ offset + 2 ] = vertex.z;
  10779. }
  10780. for ( c = 0; c < cl; c ++ ) {
  10781. offset = c * 3;
  10782. color = colors[ sortArray[c][1] ];
  10783. colorArray[ offset ] = color.r;
  10784. colorArray[ offset + 1 ] = color.g;
  10785. colorArray[ offset + 2 ] = color.b;
  10786. }
  10787. if ( customAttributes ) {
  10788. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10789. customAttribute = customAttributes[ i ];
  10790. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10791. offset = 0;
  10792. cal = customAttribute.value.length;
  10793. if ( customAttribute.size === 1 ) {
  10794. for ( ca = 0; ca < cal; ca ++ ) {
  10795. index = sortArray[ ca ][ 1 ];
  10796. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10797. }
  10798. } else if ( customAttribute.size === 2 ) {
  10799. for ( ca = 0; ca < cal; ca ++ ) {
  10800. index = sortArray[ ca ][ 1 ];
  10801. value = customAttribute.value[ index ];
  10802. customAttribute.array[ offset ] = value.x;
  10803. customAttribute.array[ offset + 1 ] = value.y;
  10804. offset += 2;
  10805. }
  10806. } else if ( customAttribute.size === 3 ) {
  10807. if ( customAttribute.type === "c" ) {
  10808. for ( ca = 0; ca < cal; ca ++ ) {
  10809. index = sortArray[ ca ][ 1 ];
  10810. value = customAttribute.value[ index ];
  10811. customAttribute.array[ offset ] = value.r;
  10812. customAttribute.array[ offset + 1 ] = value.g;
  10813. customAttribute.array[ offset + 2 ] = value.b;
  10814. offset += 3;
  10815. }
  10816. } else {
  10817. for ( ca = 0; ca < cal; ca ++ ) {
  10818. index = sortArray[ ca ][ 1 ];
  10819. value = customAttribute.value[ index ];
  10820. customAttribute.array[ offset ] = value.x;
  10821. customAttribute.array[ offset + 1 ] = value.y;
  10822. customAttribute.array[ offset + 2 ] = value.z;
  10823. offset += 3;
  10824. }
  10825. }
  10826. } else if ( customAttribute.size === 4 ) {
  10827. for ( ca = 0; ca < cal; ca ++ ) {
  10828. index = sortArray[ ca ][ 1 ];
  10829. value = customAttribute.value[ index ];
  10830. customAttribute.array[ offset ] = value.x;
  10831. customAttribute.array[ offset + 1 ] = value.y;
  10832. customAttribute.array[ offset + 2 ] = value.z;
  10833. customAttribute.array[ offset + 3 ] = value.w;
  10834. offset += 4;
  10835. }
  10836. }
  10837. }
  10838. }
  10839. } else {
  10840. if ( dirtyVertices ) {
  10841. for ( v = 0; v < vl; v ++ ) {
  10842. vertex = vertices[ v ];
  10843. offset = v * 3;
  10844. vertexArray[ offset ] = vertex.x;
  10845. vertexArray[ offset + 1 ] = vertex.y;
  10846. vertexArray[ offset + 2 ] = vertex.z;
  10847. }
  10848. }
  10849. if ( dirtyColors ) {
  10850. for ( c = 0; c < cl; c ++ ) {
  10851. color = colors[ c ];
  10852. offset = c * 3;
  10853. colorArray[ offset ] = color.r;
  10854. colorArray[ offset + 1 ] = color.g;
  10855. colorArray[ offset + 2 ] = color.b;
  10856. }
  10857. }
  10858. if ( customAttributes ) {
  10859. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10860. customAttribute = customAttributes[ i ];
  10861. if ( customAttribute.needsUpdate &&
  10862. ( customAttribute.boundTo === undefined ||
  10863. customAttribute.boundTo === "vertices") ) {
  10864. cal = customAttribute.value.length;
  10865. offset = 0;
  10866. if ( customAttribute.size === 1 ) {
  10867. for ( ca = 0; ca < cal; ca ++ ) {
  10868. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10869. }
  10870. } else if ( customAttribute.size === 2 ) {
  10871. for ( ca = 0; ca < cal; ca ++ ) {
  10872. value = customAttribute.value[ ca ];
  10873. customAttribute.array[ offset ] = value.x;
  10874. customAttribute.array[ offset + 1 ] = value.y;
  10875. offset += 2;
  10876. }
  10877. } else if ( customAttribute.size === 3 ) {
  10878. if ( customAttribute.type === "c" ) {
  10879. for ( ca = 0; ca < cal; ca ++ ) {
  10880. value = customAttribute.value[ ca ];
  10881. customAttribute.array[ offset ] = value.r;
  10882. customAttribute.array[ offset + 1 ] = value.g;
  10883. customAttribute.array[ offset + 2 ] = value.b;
  10884. offset += 3;
  10885. }
  10886. } else {
  10887. for ( ca = 0; ca < cal; ca ++ ) {
  10888. value = customAttribute.value[ ca ];
  10889. customAttribute.array[ offset ] = value.x;
  10890. customAttribute.array[ offset + 1 ] = value.y;
  10891. customAttribute.array[ offset + 2 ] = value.z;
  10892. offset += 3;
  10893. }
  10894. }
  10895. } else if ( customAttribute.size === 4 ) {
  10896. for ( ca = 0; ca < cal; ca ++ ) {
  10897. value = customAttribute.value[ ca ];
  10898. customAttribute.array[ offset ] = value.x;
  10899. customAttribute.array[ offset + 1 ] = value.y;
  10900. customAttribute.array[ offset + 2 ] = value.z;
  10901. customAttribute.array[ offset + 3 ] = value.w;
  10902. offset += 4;
  10903. }
  10904. }
  10905. }
  10906. }
  10907. }
  10908. }
  10909. if ( dirtyVertices || object.sortParticles ) {
  10910. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10911. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10912. }
  10913. if ( dirtyColors || object.sortParticles ) {
  10914. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10915. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10916. }
  10917. if ( customAttributes ) {
  10918. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10919. customAttribute = customAttributes[ i ];
  10920. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10921. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10922. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10923. }
  10924. }
  10925. }
  10926. };
  10927. function setLineBuffers ( geometry, hint ) {
  10928. var v, c, d, vertex, offset, color,
  10929. vertices = geometry.vertices,
  10930. colors = geometry.colors,
  10931. lineDistances = geometry.lineDistances,
  10932. vl = vertices.length,
  10933. cl = colors.length,
  10934. dl = lineDistances.length,
  10935. vertexArray = geometry.__vertexArray,
  10936. colorArray = geometry.__colorArray,
  10937. lineDistanceArray = geometry.__lineDistanceArray,
  10938. dirtyVertices = geometry.verticesNeedUpdate,
  10939. dirtyColors = geometry.colorsNeedUpdate,
  10940. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10941. customAttributes = geometry.__webglCustomAttributesList,
  10942. i, il,
  10943. a, ca, cal, value,
  10944. customAttribute;
  10945. if ( dirtyVertices ) {
  10946. for ( v = 0; v < vl; v ++ ) {
  10947. vertex = vertices[ v ];
  10948. offset = v * 3;
  10949. vertexArray[ offset ] = vertex.x;
  10950. vertexArray[ offset + 1 ] = vertex.y;
  10951. vertexArray[ offset + 2 ] = vertex.z;
  10952. }
  10953. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10954. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10955. }
  10956. if ( dirtyColors ) {
  10957. for ( c = 0; c < cl; c ++ ) {
  10958. color = colors[ c ];
  10959. offset = c * 3;
  10960. colorArray[ offset ] = color.r;
  10961. colorArray[ offset + 1 ] = color.g;
  10962. colorArray[ offset + 2 ] = color.b;
  10963. }
  10964. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10965. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10966. }
  10967. if ( dirtyLineDistances ) {
  10968. for ( d = 0; d < dl; d ++ ) {
  10969. lineDistanceArray[ d ] = lineDistances[ d ];
  10970. }
  10971. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10972. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10973. }
  10974. if ( customAttributes ) {
  10975. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10976. customAttribute = customAttributes[ i ];
  10977. if ( customAttribute.needsUpdate &&
  10978. ( customAttribute.boundTo === undefined ||
  10979. customAttribute.boundTo === "vertices" ) ) {
  10980. offset = 0;
  10981. cal = customAttribute.value.length;
  10982. if ( customAttribute.size === 1 ) {
  10983. for ( ca = 0; ca < cal; ca ++ ) {
  10984. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10985. }
  10986. } else if ( customAttribute.size === 2 ) {
  10987. for ( ca = 0; ca < cal; ca ++ ) {
  10988. value = customAttribute.value[ ca ];
  10989. customAttribute.array[ offset ] = value.x;
  10990. customAttribute.array[ offset + 1 ] = value.y;
  10991. offset += 2;
  10992. }
  10993. } else if ( customAttribute.size === 3 ) {
  10994. if ( customAttribute.type === "c" ) {
  10995. for ( ca = 0; ca < cal; ca ++ ) {
  10996. value = customAttribute.value[ ca ];
  10997. customAttribute.array[ offset ] = value.r;
  10998. customAttribute.array[ offset + 1 ] = value.g;
  10999. customAttribute.array[ offset + 2 ] = value.b;
  11000. offset += 3;
  11001. }
  11002. } else {
  11003. for ( ca = 0; ca < cal; ca ++ ) {
  11004. value = customAttribute.value[ ca ];
  11005. customAttribute.array[ offset ] = value.x;
  11006. customAttribute.array[ offset + 1 ] = value.y;
  11007. customAttribute.array[ offset + 2 ] = value.z;
  11008. offset += 3;
  11009. }
  11010. }
  11011. } else if ( customAttribute.size === 4 ) {
  11012. for ( ca = 0; ca < cal; ca ++ ) {
  11013. value = customAttribute.value[ ca ];
  11014. customAttribute.array[ offset ] = value.x;
  11015. customAttribute.array[ offset + 1 ] = value.y;
  11016. customAttribute.array[ offset + 2 ] = value.z;
  11017. customAttribute.array[ offset + 3 ] = value.w;
  11018. offset += 4;
  11019. }
  11020. }
  11021. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11022. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11023. }
  11024. }
  11025. }
  11026. };
  11027. function setRibbonBuffers ( geometry, hint ) {
  11028. var v, c, n, vertex, offset, color, normal,
  11029. i, il, ca, cal, customAttribute, value,
  11030. vertices = geometry.vertices,
  11031. colors = geometry.colors,
  11032. normals = geometry.normals,
  11033. vl = vertices.length,
  11034. cl = colors.length,
  11035. nl = normals.length,
  11036. vertexArray = geometry.__vertexArray,
  11037. colorArray = geometry.__colorArray,
  11038. normalArray = geometry.__normalArray,
  11039. dirtyVertices = geometry.verticesNeedUpdate,
  11040. dirtyColors = geometry.colorsNeedUpdate,
  11041. dirtyNormals = geometry.normalsNeedUpdate,
  11042. customAttributes = geometry.__webglCustomAttributesList;
  11043. if ( dirtyVertices ) {
  11044. for ( v = 0; v < vl; v ++ ) {
  11045. vertex = vertices[ v ];
  11046. offset = v * 3;
  11047. vertexArray[ offset ] = vertex.x;
  11048. vertexArray[ offset + 1 ] = vertex.y;
  11049. vertexArray[ offset + 2 ] = vertex.z;
  11050. }
  11051. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11052. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11053. }
  11054. if ( dirtyColors ) {
  11055. for ( c = 0; c < cl; c ++ ) {
  11056. color = colors[ c ];
  11057. offset = c * 3;
  11058. colorArray[ offset ] = color.r;
  11059. colorArray[ offset + 1 ] = color.g;
  11060. colorArray[ offset + 2 ] = color.b;
  11061. }
  11062. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11063. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11064. }
  11065. if ( dirtyNormals ) {
  11066. for ( n = 0; n < nl; n ++ ) {
  11067. normal = normals[ n ];
  11068. offset = n * 3;
  11069. normalArray[ offset ] = normal.x;
  11070. normalArray[ offset + 1 ] = normal.y;
  11071. normalArray[ offset + 2 ] = normal.z;
  11072. }
  11073. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11074. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11075. }
  11076. if ( customAttributes ) {
  11077. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11078. customAttribute = customAttributes[ i ];
  11079. if ( customAttribute.needsUpdate &&
  11080. ( customAttribute.boundTo === undefined ||
  11081. customAttribute.boundTo === "vertices" ) ) {
  11082. offset = 0;
  11083. cal = customAttribute.value.length;
  11084. if ( customAttribute.size === 1 ) {
  11085. for ( ca = 0; ca < cal; ca ++ ) {
  11086. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11087. }
  11088. } else if ( customAttribute.size === 2 ) {
  11089. for ( ca = 0; ca < cal; ca ++ ) {
  11090. value = customAttribute.value[ ca ];
  11091. customAttribute.array[ offset ] = value.x;
  11092. customAttribute.array[ offset + 1 ] = value.y;
  11093. offset += 2;
  11094. }
  11095. } else if ( customAttribute.size === 3 ) {
  11096. if ( customAttribute.type === "c" ) {
  11097. for ( ca = 0; ca < cal; ca ++ ) {
  11098. value = customAttribute.value[ ca ];
  11099. customAttribute.array[ offset ] = value.r;
  11100. customAttribute.array[ offset + 1 ] = value.g;
  11101. customAttribute.array[ offset + 2 ] = value.b;
  11102. offset += 3;
  11103. }
  11104. } else {
  11105. for ( ca = 0; ca < cal; ca ++ ) {
  11106. value = customAttribute.value[ ca ];
  11107. customAttribute.array[ offset ] = value.x;
  11108. customAttribute.array[ offset + 1 ] = value.y;
  11109. customAttribute.array[ offset + 2 ] = value.z;
  11110. offset += 3;
  11111. }
  11112. }
  11113. } else if ( customAttribute.size === 4 ) {
  11114. for ( ca = 0; ca < cal; ca ++ ) {
  11115. value = customAttribute.value[ ca ];
  11116. customAttribute.array[ offset ] = value.x;
  11117. customAttribute.array[ offset + 1 ] = value.y;
  11118. customAttribute.array[ offset + 2 ] = value.z;
  11119. customAttribute.array[ offset + 3 ] = value.w;
  11120. offset += 4;
  11121. }
  11122. }
  11123. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11124. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11125. }
  11126. }
  11127. }
  11128. };
  11129. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11130. if ( ! geometryGroup.__inittedArrays ) {
  11131. return;
  11132. }
  11133. var normalType = bufferGuessNormalType( material ),
  11134. vertexColorType = bufferGuessVertexColorType( material ),
  11135. uvType = bufferGuessUVType( material ),
  11136. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11137. var f, fl, fi, face,
  11138. vertexNormals, faceNormal, normal,
  11139. vertexColors, faceColor,
  11140. vertexTangents,
  11141. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11142. c1, c2, c3, c4,
  11143. sw1, sw2, sw3, sw4,
  11144. si1, si2, si3, si4,
  11145. sa1, sa2, sa3, sa4,
  11146. sb1, sb2, sb3, sb4,
  11147. m, ml, i, il,
  11148. vn, uvi, uv2i,
  11149. vk, vkl, vka,
  11150. nka, chf, faceVertexNormals,
  11151. a,
  11152. vertexIndex = 0,
  11153. offset = 0,
  11154. offset_uv = 0,
  11155. offset_uv2 = 0,
  11156. offset_face = 0,
  11157. offset_normal = 0,
  11158. offset_tangent = 0,
  11159. offset_line = 0,
  11160. offset_color = 0,
  11161. offset_skin = 0,
  11162. offset_morphTarget = 0,
  11163. offset_custom = 0,
  11164. offset_customSrc = 0,
  11165. value,
  11166. vertexArray = geometryGroup.__vertexArray,
  11167. uvArray = geometryGroup.__uvArray,
  11168. uv2Array = geometryGroup.__uv2Array,
  11169. normalArray = geometryGroup.__normalArray,
  11170. tangentArray = geometryGroup.__tangentArray,
  11171. colorArray = geometryGroup.__colorArray,
  11172. skinIndexArray = geometryGroup.__skinIndexArray,
  11173. skinWeightArray = geometryGroup.__skinWeightArray,
  11174. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11175. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11176. customAttributes = geometryGroup.__webglCustomAttributesList,
  11177. customAttribute,
  11178. faceArray = geometryGroup.__faceArray,
  11179. lineArray = geometryGroup.__lineArray,
  11180. geometry = object.geometry, // this is shared for all chunks
  11181. dirtyVertices = geometry.verticesNeedUpdate,
  11182. dirtyElements = geometry.elementsNeedUpdate,
  11183. dirtyUvs = geometry.uvsNeedUpdate,
  11184. dirtyNormals = geometry.normalsNeedUpdate,
  11185. dirtyTangents = geometry.tangentsNeedUpdate,
  11186. dirtyColors = geometry.colorsNeedUpdate,
  11187. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11188. vertices = geometry.vertices,
  11189. chunk_faces3 = geometryGroup.faces3,
  11190. chunk_faces4 = geometryGroup.faces4,
  11191. obj_faces = geometry.faces,
  11192. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11193. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11194. obj_colors = geometry.colors,
  11195. obj_skinIndices = geometry.skinIndices,
  11196. obj_skinWeights = geometry.skinWeights,
  11197. morphTargets = geometry.morphTargets,
  11198. morphNormals = geometry.morphNormals;
  11199. if ( dirtyVertices ) {
  11200. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11201. face = obj_faces[ chunk_faces3[ f ] ];
  11202. v1 = vertices[ face.a ];
  11203. v2 = vertices[ face.b ];
  11204. v3 = vertices[ face.c ];
  11205. vertexArray[ offset ] = v1.x;
  11206. vertexArray[ offset + 1 ] = v1.y;
  11207. vertexArray[ offset + 2 ] = v1.z;
  11208. vertexArray[ offset + 3 ] = v2.x;
  11209. vertexArray[ offset + 4 ] = v2.y;
  11210. vertexArray[ offset + 5 ] = v2.z;
  11211. vertexArray[ offset + 6 ] = v3.x;
  11212. vertexArray[ offset + 7 ] = v3.y;
  11213. vertexArray[ offset + 8 ] = v3.z;
  11214. offset += 9;
  11215. }
  11216. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11217. face = obj_faces[ chunk_faces4[ f ] ];
  11218. v1 = vertices[ face.a ];
  11219. v2 = vertices[ face.b ];
  11220. v3 = vertices[ face.c ];
  11221. v4 = vertices[ face.d ];
  11222. vertexArray[ offset ] = v1.x;
  11223. vertexArray[ offset + 1 ] = v1.y;
  11224. vertexArray[ offset + 2 ] = v1.z;
  11225. vertexArray[ offset + 3 ] = v2.x;
  11226. vertexArray[ offset + 4 ] = v2.y;
  11227. vertexArray[ offset + 5 ] = v2.z;
  11228. vertexArray[ offset + 6 ] = v3.x;
  11229. vertexArray[ offset + 7 ] = v3.y;
  11230. vertexArray[ offset + 8 ] = v3.z;
  11231. vertexArray[ offset + 9 ] = v4.x;
  11232. vertexArray[ offset + 10 ] = v4.y;
  11233. vertexArray[ offset + 11 ] = v4.z;
  11234. offset += 12;
  11235. }
  11236. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11237. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11238. }
  11239. if ( dirtyMorphTargets ) {
  11240. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11241. offset_morphTarget = 0;
  11242. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11243. chf = chunk_faces3[ f ];
  11244. face = obj_faces[ chf ];
  11245. // morph positions
  11246. v1 = morphTargets[ vk ].vertices[ face.a ];
  11247. v2 = morphTargets[ vk ].vertices[ face.b ];
  11248. v3 = morphTargets[ vk ].vertices[ face.c ];
  11249. vka = morphTargetsArrays[ vk ];
  11250. vka[ offset_morphTarget ] = v1.x;
  11251. vka[ offset_morphTarget + 1 ] = v1.y;
  11252. vka[ offset_morphTarget + 2 ] = v1.z;
  11253. vka[ offset_morphTarget + 3 ] = v2.x;
  11254. vka[ offset_morphTarget + 4 ] = v2.y;
  11255. vka[ offset_morphTarget + 5 ] = v2.z;
  11256. vka[ offset_morphTarget + 6 ] = v3.x;
  11257. vka[ offset_morphTarget + 7 ] = v3.y;
  11258. vka[ offset_morphTarget + 8 ] = v3.z;
  11259. // morph normals
  11260. if ( material.morphNormals ) {
  11261. if ( needsSmoothNormals ) {
  11262. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11263. n1 = faceVertexNormals.a;
  11264. n2 = faceVertexNormals.b;
  11265. n3 = faceVertexNormals.c;
  11266. } else {
  11267. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11268. n2 = n1;
  11269. n3 = n1;
  11270. }
  11271. nka = morphNormalsArrays[ vk ];
  11272. nka[ offset_morphTarget ] = n1.x;
  11273. nka[ offset_morphTarget + 1 ] = n1.y;
  11274. nka[ offset_morphTarget + 2 ] = n1.z;
  11275. nka[ offset_morphTarget + 3 ] = n2.x;
  11276. nka[ offset_morphTarget + 4 ] = n2.y;
  11277. nka[ offset_morphTarget + 5 ] = n2.z;
  11278. nka[ offset_morphTarget + 6 ] = n3.x;
  11279. nka[ offset_morphTarget + 7 ] = n3.y;
  11280. nka[ offset_morphTarget + 8 ] = n3.z;
  11281. }
  11282. //
  11283. offset_morphTarget += 9;
  11284. }
  11285. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11286. chf = chunk_faces4[ f ];
  11287. face = obj_faces[ chf ];
  11288. // morph positions
  11289. v1 = morphTargets[ vk ].vertices[ face.a ];
  11290. v2 = morphTargets[ vk ].vertices[ face.b ];
  11291. v3 = morphTargets[ vk ].vertices[ face.c ];
  11292. v4 = morphTargets[ vk ].vertices[ face.d ];
  11293. vka = morphTargetsArrays[ vk ];
  11294. vka[ offset_morphTarget ] = v1.x;
  11295. vka[ offset_morphTarget + 1 ] = v1.y;
  11296. vka[ offset_morphTarget + 2 ] = v1.z;
  11297. vka[ offset_morphTarget + 3 ] = v2.x;
  11298. vka[ offset_morphTarget + 4 ] = v2.y;
  11299. vka[ offset_morphTarget + 5 ] = v2.z;
  11300. vka[ offset_morphTarget + 6 ] = v3.x;
  11301. vka[ offset_morphTarget + 7 ] = v3.y;
  11302. vka[ offset_morphTarget + 8 ] = v3.z;
  11303. vka[ offset_morphTarget + 9 ] = v4.x;
  11304. vka[ offset_morphTarget + 10 ] = v4.y;
  11305. vka[ offset_morphTarget + 11 ] = v4.z;
  11306. // morph normals
  11307. if ( material.morphNormals ) {
  11308. if ( needsSmoothNormals ) {
  11309. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11310. n1 = faceVertexNormals.a;
  11311. n2 = faceVertexNormals.b;
  11312. n3 = faceVertexNormals.c;
  11313. n4 = faceVertexNormals.d;
  11314. } else {
  11315. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11316. n2 = n1;
  11317. n3 = n1;
  11318. n4 = n1;
  11319. }
  11320. nka = morphNormalsArrays[ vk ];
  11321. nka[ offset_morphTarget ] = n1.x;
  11322. nka[ offset_morphTarget + 1 ] = n1.y;
  11323. nka[ offset_morphTarget + 2 ] = n1.z;
  11324. nka[ offset_morphTarget + 3 ] = n2.x;
  11325. nka[ offset_morphTarget + 4 ] = n2.y;
  11326. nka[ offset_morphTarget + 5 ] = n2.z;
  11327. nka[ offset_morphTarget + 6 ] = n3.x;
  11328. nka[ offset_morphTarget + 7 ] = n3.y;
  11329. nka[ offset_morphTarget + 8 ] = n3.z;
  11330. nka[ offset_morphTarget + 9 ] = n4.x;
  11331. nka[ offset_morphTarget + 10 ] = n4.y;
  11332. nka[ offset_morphTarget + 11 ] = n4.z;
  11333. }
  11334. //
  11335. offset_morphTarget += 12;
  11336. }
  11337. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11338. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11339. if ( material.morphNormals ) {
  11340. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11341. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11342. }
  11343. }
  11344. }
  11345. if ( obj_skinWeights.length ) {
  11346. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11347. face = obj_faces[ chunk_faces3[ f ] ];
  11348. // weights
  11349. sw1 = obj_skinWeights[ face.a ];
  11350. sw2 = obj_skinWeights[ face.b ];
  11351. sw3 = obj_skinWeights[ face.c ];
  11352. skinWeightArray[ offset_skin ] = sw1.x;
  11353. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11354. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11355. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11356. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11357. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11358. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11359. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11360. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11361. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11362. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11363. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11364. // indices
  11365. si1 = obj_skinIndices[ face.a ];
  11366. si2 = obj_skinIndices[ face.b ];
  11367. si3 = obj_skinIndices[ face.c ];
  11368. skinIndexArray[ offset_skin ] = si1.x;
  11369. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11370. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11371. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11372. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11373. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11374. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11375. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11376. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11377. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11378. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11379. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11380. offset_skin += 12;
  11381. }
  11382. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11383. face = obj_faces[ chunk_faces4[ f ] ];
  11384. // weights
  11385. sw1 = obj_skinWeights[ face.a ];
  11386. sw2 = obj_skinWeights[ face.b ];
  11387. sw3 = obj_skinWeights[ face.c ];
  11388. sw4 = obj_skinWeights[ face.d ];
  11389. skinWeightArray[ offset_skin ] = sw1.x;
  11390. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11391. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11392. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11393. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11394. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11395. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11396. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11397. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11398. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11399. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11400. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11401. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11402. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11403. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11404. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11405. // indices
  11406. si1 = obj_skinIndices[ face.a ];
  11407. si2 = obj_skinIndices[ face.b ];
  11408. si3 = obj_skinIndices[ face.c ];
  11409. si4 = obj_skinIndices[ face.d ];
  11410. skinIndexArray[ offset_skin ] = si1.x;
  11411. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11412. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11413. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11414. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11415. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11416. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11417. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11418. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11419. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11420. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11421. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11422. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11423. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11424. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11425. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11426. offset_skin += 16;
  11427. }
  11428. if ( offset_skin > 0 ) {
  11429. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11430. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11431. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11432. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11433. }
  11434. }
  11435. if ( dirtyColors && vertexColorType ) {
  11436. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11437. face = obj_faces[ chunk_faces3[ f ] ];
  11438. vertexColors = face.vertexColors;
  11439. faceColor = face.color;
  11440. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11441. c1 = vertexColors[ 0 ];
  11442. c2 = vertexColors[ 1 ];
  11443. c3 = vertexColors[ 2 ];
  11444. } else {
  11445. c1 = faceColor;
  11446. c2 = faceColor;
  11447. c3 = faceColor;
  11448. }
  11449. colorArray[ offset_color ] = c1.r;
  11450. colorArray[ offset_color + 1 ] = c1.g;
  11451. colorArray[ offset_color + 2 ] = c1.b;
  11452. colorArray[ offset_color + 3 ] = c2.r;
  11453. colorArray[ offset_color + 4 ] = c2.g;
  11454. colorArray[ offset_color + 5 ] = c2.b;
  11455. colorArray[ offset_color + 6 ] = c3.r;
  11456. colorArray[ offset_color + 7 ] = c3.g;
  11457. colorArray[ offset_color + 8 ] = c3.b;
  11458. offset_color += 9;
  11459. }
  11460. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11461. face = obj_faces[ chunk_faces4[ f ] ];
  11462. vertexColors = face.vertexColors;
  11463. faceColor = face.color;
  11464. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  11465. c1 = vertexColors[ 0 ];
  11466. c2 = vertexColors[ 1 ];
  11467. c3 = vertexColors[ 2 ];
  11468. c4 = vertexColors[ 3 ];
  11469. } else {
  11470. c1 = faceColor;
  11471. c2 = faceColor;
  11472. c3 = faceColor;
  11473. c4 = faceColor;
  11474. }
  11475. colorArray[ offset_color ] = c1.r;
  11476. colorArray[ offset_color + 1 ] = c1.g;
  11477. colorArray[ offset_color + 2 ] = c1.b;
  11478. colorArray[ offset_color + 3 ] = c2.r;
  11479. colorArray[ offset_color + 4 ] = c2.g;
  11480. colorArray[ offset_color + 5 ] = c2.b;
  11481. colorArray[ offset_color + 6 ] = c3.r;
  11482. colorArray[ offset_color + 7 ] = c3.g;
  11483. colorArray[ offset_color + 8 ] = c3.b;
  11484. colorArray[ offset_color + 9 ] = c4.r;
  11485. colorArray[ offset_color + 10 ] = c4.g;
  11486. colorArray[ offset_color + 11 ] = c4.b;
  11487. offset_color += 12;
  11488. }
  11489. if ( offset_color > 0 ) {
  11490. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11491. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11492. }
  11493. }
  11494. if ( dirtyTangents && geometry.hasTangents ) {
  11495. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11496. face = obj_faces[ chunk_faces3[ f ] ];
  11497. vertexTangents = face.vertexTangents;
  11498. t1 = vertexTangents[ 0 ];
  11499. t2 = vertexTangents[ 1 ];
  11500. t3 = vertexTangents[ 2 ];
  11501. tangentArray[ offset_tangent ] = t1.x;
  11502. tangentArray[ offset_tangent + 1 ] = t1.y;
  11503. tangentArray[ offset_tangent + 2 ] = t1.z;
  11504. tangentArray[ offset_tangent + 3 ] = t1.w;
  11505. tangentArray[ offset_tangent + 4 ] = t2.x;
  11506. tangentArray[ offset_tangent + 5 ] = t2.y;
  11507. tangentArray[ offset_tangent + 6 ] = t2.z;
  11508. tangentArray[ offset_tangent + 7 ] = t2.w;
  11509. tangentArray[ offset_tangent + 8 ] = t3.x;
  11510. tangentArray[ offset_tangent + 9 ] = t3.y;
  11511. tangentArray[ offset_tangent + 10 ] = t3.z;
  11512. tangentArray[ offset_tangent + 11 ] = t3.w;
  11513. offset_tangent += 12;
  11514. }
  11515. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11516. face = obj_faces[ chunk_faces4[ f ] ];
  11517. vertexTangents = face.vertexTangents;
  11518. t1 = vertexTangents[ 0 ];
  11519. t2 = vertexTangents[ 1 ];
  11520. t3 = vertexTangents[ 2 ];
  11521. t4 = vertexTangents[ 3 ];
  11522. tangentArray[ offset_tangent ] = t1.x;
  11523. tangentArray[ offset_tangent + 1 ] = t1.y;
  11524. tangentArray[ offset_tangent + 2 ] = t1.z;
  11525. tangentArray[ offset_tangent + 3 ] = t1.w;
  11526. tangentArray[ offset_tangent + 4 ] = t2.x;
  11527. tangentArray[ offset_tangent + 5 ] = t2.y;
  11528. tangentArray[ offset_tangent + 6 ] = t2.z;
  11529. tangentArray[ offset_tangent + 7 ] = t2.w;
  11530. tangentArray[ offset_tangent + 8 ] = t3.x;
  11531. tangentArray[ offset_tangent + 9 ] = t3.y;
  11532. tangentArray[ offset_tangent + 10 ] = t3.z;
  11533. tangentArray[ offset_tangent + 11 ] = t3.w;
  11534. tangentArray[ offset_tangent + 12 ] = t4.x;
  11535. tangentArray[ offset_tangent + 13 ] = t4.y;
  11536. tangentArray[ offset_tangent + 14 ] = t4.z;
  11537. tangentArray[ offset_tangent + 15 ] = t4.w;
  11538. offset_tangent += 16;
  11539. }
  11540. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11541. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11542. }
  11543. if ( dirtyNormals && normalType ) {
  11544. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11545. face = obj_faces[ chunk_faces3[ f ] ];
  11546. vertexNormals = face.vertexNormals;
  11547. faceNormal = face.normal;
  11548. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11549. for ( i = 0; i < 3; i ++ ) {
  11550. vn = vertexNormals[ i ];
  11551. normalArray[ offset_normal ] = vn.x;
  11552. normalArray[ offset_normal + 1 ] = vn.y;
  11553. normalArray[ offset_normal + 2 ] = vn.z;
  11554. offset_normal += 3;
  11555. }
  11556. } else {
  11557. for ( i = 0; i < 3; i ++ ) {
  11558. normalArray[ offset_normal ] = faceNormal.x;
  11559. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11560. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11561. offset_normal += 3;
  11562. }
  11563. }
  11564. }
  11565. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11566. face = obj_faces[ chunk_faces4[ f ] ];
  11567. vertexNormals = face.vertexNormals;
  11568. faceNormal = face.normal;
  11569. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  11570. for ( i = 0; i < 4; i ++ ) {
  11571. vn = vertexNormals[ i ];
  11572. normalArray[ offset_normal ] = vn.x;
  11573. normalArray[ offset_normal + 1 ] = vn.y;
  11574. normalArray[ offset_normal + 2 ] = vn.z;
  11575. offset_normal += 3;
  11576. }
  11577. } else {
  11578. for ( i = 0; i < 4; i ++ ) {
  11579. normalArray[ offset_normal ] = faceNormal.x;
  11580. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11581. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11582. offset_normal += 3;
  11583. }
  11584. }
  11585. }
  11586. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11587. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11588. }
  11589. if ( dirtyUvs && obj_uvs && uvType ) {
  11590. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11591. fi = chunk_faces3[ f ];
  11592. uv = obj_uvs[ fi ];
  11593. if ( uv === undefined ) continue;
  11594. for ( i = 0; i < 3; i ++ ) {
  11595. uvi = uv[ i ];
  11596. uvArray[ offset_uv ] = uvi.x;
  11597. uvArray[ offset_uv + 1 ] = uvi.y;
  11598. offset_uv += 2;
  11599. }
  11600. }
  11601. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11602. fi = chunk_faces4[ f ];
  11603. uv = obj_uvs[ fi ];
  11604. if ( uv === undefined ) continue;
  11605. for ( i = 0; i < 4; i ++ ) {
  11606. uvi = uv[ i ];
  11607. uvArray[ offset_uv ] = uvi.x;
  11608. uvArray[ offset_uv + 1 ] = uvi.y;
  11609. offset_uv += 2;
  11610. }
  11611. }
  11612. if ( offset_uv > 0 ) {
  11613. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11614. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11615. }
  11616. }
  11617. if ( dirtyUvs && obj_uvs2 && uvType ) {
  11618. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11619. fi = chunk_faces3[ f ];
  11620. uv2 = obj_uvs2[ fi ];
  11621. if ( uv2 === undefined ) continue;
  11622. for ( i = 0; i < 3; i ++ ) {
  11623. uv2i = uv2[ i ];
  11624. uv2Array[ offset_uv2 ] = uv2i.x;
  11625. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11626. offset_uv2 += 2;
  11627. }
  11628. }
  11629. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11630. fi = chunk_faces4[ f ];
  11631. uv2 = obj_uvs2[ fi ];
  11632. if ( uv2 === undefined ) continue;
  11633. for ( i = 0; i < 4; i ++ ) {
  11634. uv2i = uv2[ i ];
  11635. uv2Array[ offset_uv2 ] = uv2i.x;
  11636. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11637. offset_uv2 += 2;
  11638. }
  11639. }
  11640. if ( offset_uv2 > 0 ) {
  11641. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11642. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11643. }
  11644. }
  11645. if ( dirtyElements ) {
  11646. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11647. faceArray[ offset_face ] = vertexIndex;
  11648. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11649. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11650. offset_face += 3;
  11651. lineArray[ offset_line ] = vertexIndex;
  11652. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11653. lineArray[ offset_line + 2 ] = vertexIndex;
  11654. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11655. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11656. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11657. offset_line += 6;
  11658. vertexIndex += 3;
  11659. }
  11660. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11661. faceArray[ offset_face ] = vertexIndex;
  11662. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11663. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  11664. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  11665. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  11666. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  11667. offset_face += 6;
  11668. lineArray[ offset_line ] = vertexIndex;
  11669. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11670. lineArray[ offset_line + 2 ] = vertexIndex;
  11671. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  11672. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11673. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11674. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  11675. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  11676. offset_line += 8;
  11677. vertexIndex += 4;
  11678. }
  11679. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11680. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11681. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11682. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11683. }
  11684. if ( customAttributes ) {
  11685. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11686. customAttribute = customAttributes[ i ];
  11687. if ( ! customAttribute.__original.needsUpdate ) continue;
  11688. offset_custom = 0;
  11689. offset_customSrc = 0;
  11690. if ( customAttribute.size === 1 ) {
  11691. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11692. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11693. face = obj_faces[ chunk_faces3[ f ] ];
  11694. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11695. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11696. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11697. offset_custom += 3;
  11698. }
  11699. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11700. face = obj_faces[ chunk_faces4[ f ] ];
  11701. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11702. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11703. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11704. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  11705. offset_custom += 4;
  11706. }
  11707. } else if ( customAttribute.boundTo === "faces" ) {
  11708. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11709. value = customAttribute.value[ chunk_faces3[ f ] ];
  11710. customAttribute.array[ offset_custom ] = value;
  11711. customAttribute.array[ offset_custom + 1 ] = value;
  11712. customAttribute.array[ offset_custom + 2 ] = value;
  11713. offset_custom += 3;
  11714. }
  11715. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11716. value = customAttribute.value[ chunk_faces4[ f ] ];
  11717. customAttribute.array[ offset_custom ] = value;
  11718. customAttribute.array[ offset_custom + 1 ] = value;
  11719. customAttribute.array[ offset_custom + 2 ] = value;
  11720. customAttribute.array[ offset_custom + 3 ] = value;
  11721. offset_custom += 4;
  11722. }
  11723. }
  11724. } else if ( customAttribute.size === 2 ) {
  11725. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11726. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11727. face = obj_faces[ chunk_faces3[ f ] ];
  11728. v1 = customAttribute.value[ face.a ];
  11729. v2 = customAttribute.value[ face.b ];
  11730. v3 = customAttribute.value[ face.c ];
  11731. customAttribute.array[ offset_custom ] = v1.x;
  11732. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11733. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11734. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11735. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11736. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11737. offset_custom += 6;
  11738. }
  11739. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11740. face = obj_faces[ chunk_faces4[ f ] ];
  11741. v1 = customAttribute.value[ face.a ];
  11742. v2 = customAttribute.value[ face.b ];
  11743. v3 = customAttribute.value[ face.c ];
  11744. v4 = customAttribute.value[ face.d ];
  11745. customAttribute.array[ offset_custom ] = v1.x;
  11746. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11747. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11748. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11749. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11750. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11751. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11752. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11753. offset_custom += 8;
  11754. }
  11755. } else if ( customAttribute.boundTo === "faces" ) {
  11756. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11757. value = customAttribute.value[ chunk_faces3[ f ] ];
  11758. v1 = value;
  11759. v2 = value;
  11760. v3 = value;
  11761. customAttribute.array[ offset_custom ] = v1.x;
  11762. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11763. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11764. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11765. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11766. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11767. offset_custom += 6;
  11768. }
  11769. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11770. value = customAttribute.value[ chunk_faces4[ f ] ];
  11771. v1 = value;
  11772. v2 = value;
  11773. v3 = value;
  11774. v4 = value;
  11775. customAttribute.array[ offset_custom ] = v1.x;
  11776. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11777. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11778. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11779. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11780. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11781. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11782. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11783. offset_custom += 8;
  11784. }
  11785. }
  11786. } else if ( customAttribute.size === 3 ) {
  11787. var pp;
  11788. if ( customAttribute.type === "c" ) {
  11789. pp = [ "r", "g", "b" ];
  11790. } else {
  11791. pp = [ "x", "y", "z" ];
  11792. }
  11793. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11794. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11795. face = obj_faces[ chunk_faces3[ f ] ];
  11796. v1 = customAttribute.value[ face.a ];
  11797. v2 = customAttribute.value[ face.b ];
  11798. v3 = customAttribute.value[ face.c ];
  11799. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11800. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11801. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11802. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11803. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11804. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11805. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11806. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11807. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11808. offset_custom += 9;
  11809. }
  11810. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11811. face = obj_faces[ chunk_faces4[ f ] ];
  11812. v1 = customAttribute.value[ face.a ];
  11813. v2 = customAttribute.value[ face.b ];
  11814. v3 = customAttribute.value[ face.c ];
  11815. v4 = customAttribute.value[ face.d ];
  11816. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11817. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11818. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11819. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11820. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11821. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11822. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11823. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11824. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11825. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11826. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11827. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11828. offset_custom += 12;
  11829. }
  11830. } else if ( customAttribute.boundTo === "faces" ) {
  11831. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11832. value = customAttribute.value[ chunk_faces3[ f ] ];
  11833. v1 = value;
  11834. v2 = value;
  11835. v3 = value;
  11836. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11837. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11838. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11839. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11840. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11841. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11842. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11843. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11844. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11845. offset_custom += 9;
  11846. }
  11847. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11848. value = customAttribute.value[ chunk_faces4[ f ] ];
  11849. v1 = value;
  11850. v2 = value;
  11851. v3 = value;
  11852. v4 = value;
  11853. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11854. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11855. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11856. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11857. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11858. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11859. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11860. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11861. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11862. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11863. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11864. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11865. offset_custom += 12;
  11866. }
  11867. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11868. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11869. value = customAttribute.value[ chunk_faces3[ f ] ];
  11870. v1 = value[ 0 ];
  11871. v2 = value[ 1 ];
  11872. v3 = value[ 2 ];
  11873. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11874. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11875. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11876. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11877. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11878. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11879. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11880. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11881. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11882. offset_custom += 9;
  11883. }
  11884. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11885. value = customAttribute.value[ chunk_faces4[ f ] ];
  11886. v1 = value[ 0 ];
  11887. v2 = value[ 1 ];
  11888. v3 = value[ 2 ];
  11889. v4 = value[ 3 ];
  11890. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11891. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11892. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11893. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11894. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11895. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11896. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11897. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11898. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11899. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11900. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11901. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11902. offset_custom += 12;
  11903. }
  11904. }
  11905. } else if ( customAttribute.size === 4 ) {
  11906. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11907. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11908. face = obj_faces[ chunk_faces3[ f ] ];
  11909. v1 = customAttribute.value[ face.a ];
  11910. v2 = customAttribute.value[ face.b ];
  11911. v3 = customAttribute.value[ face.c ];
  11912. customAttribute.array[ offset_custom ] = v1.x;
  11913. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11914. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11915. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11916. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11917. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11918. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11919. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11920. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11921. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11922. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11923. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11924. offset_custom += 12;
  11925. }
  11926. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11927. face = obj_faces[ chunk_faces4[ f ] ];
  11928. v1 = customAttribute.value[ face.a ];
  11929. v2 = customAttribute.value[ face.b ];
  11930. v3 = customAttribute.value[ face.c ];
  11931. v4 = customAttribute.value[ face.d ];
  11932. customAttribute.array[ offset_custom ] = v1.x;
  11933. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11934. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11935. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11936. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11937. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11938. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11939. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11940. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11941. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11942. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11943. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11944. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11945. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11946. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11947. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11948. offset_custom += 16;
  11949. }
  11950. } else if ( customAttribute.boundTo === "faces" ) {
  11951. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11952. value = customAttribute.value[ chunk_faces3[ f ] ];
  11953. v1 = value;
  11954. v2 = value;
  11955. v3 = value;
  11956. customAttribute.array[ offset_custom ] = v1.x;
  11957. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11958. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11959. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11960. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11961. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11962. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11963. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11964. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11965. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11966. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11967. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11968. offset_custom += 12;
  11969. }
  11970. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11971. value = customAttribute.value[ chunk_faces4[ f ] ];
  11972. v1 = value;
  11973. v2 = value;
  11974. v3 = value;
  11975. v4 = value;
  11976. customAttribute.array[ offset_custom ] = v1.x;
  11977. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11978. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11979. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11980. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11981. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11982. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11983. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11984. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11985. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11986. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11987. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11988. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11989. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11990. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11991. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11992. offset_custom += 16;
  11993. }
  11994. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11995. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11996. value = customAttribute.value[ chunk_faces3[ f ] ];
  11997. v1 = value[ 0 ];
  11998. v2 = value[ 1 ];
  11999. v3 = value[ 2 ];
  12000. customAttribute.array[ offset_custom ] = v1.x;
  12001. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12002. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12003. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12004. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12005. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12006. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12007. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12008. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12009. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12010. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12011. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12012. offset_custom += 12;
  12013. }
  12014. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12015. value = customAttribute.value[ chunk_faces4[ f ] ];
  12016. v1 = value[ 0 ];
  12017. v2 = value[ 1 ];
  12018. v3 = value[ 2 ];
  12019. v4 = value[ 3 ];
  12020. customAttribute.array[ offset_custom ] = v1.x;
  12021. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12022. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12023. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12024. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12025. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12026. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12027. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12028. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12029. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12030. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12031. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12032. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12033. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12034. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12035. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12036. offset_custom += 16;
  12037. }
  12038. }
  12039. }
  12040. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12041. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12042. }
  12043. }
  12044. if ( dispose ) {
  12045. delete geometryGroup.__inittedArrays;
  12046. delete geometryGroup.__colorArray;
  12047. delete geometryGroup.__normalArray;
  12048. delete geometryGroup.__tangentArray;
  12049. delete geometryGroup.__uvArray;
  12050. delete geometryGroup.__uv2Array;
  12051. delete geometryGroup.__faceArray;
  12052. delete geometryGroup.__vertexArray;
  12053. delete geometryGroup.__lineArray;
  12054. delete geometryGroup.__skinIndexArray;
  12055. delete geometryGroup.__skinWeightArray;
  12056. }
  12057. };
  12058. function setDirectBuffers ( geometry, hint, dispose ) {
  12059. var attributes = geometry.attributes;
  12060. var index = attributes[ "index" ];
  12061. var position = attributes[ "position" ];
  12062. var normal = attributes[ "normal" ];
  12063. var uv = attributes[ "uv" ];
  12064. var color = attributes[ "color" ];
  12065. var tangent = attributes[ "tangent" ];
  12066. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12067. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12068. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12069. }
  12070. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12071. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12072. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12073. }
  12074. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12075. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12076. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12077. }
  12078. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12079. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12080. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12081. }
  12082. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12083. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12084. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12085. }
  12086. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12087. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12088. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12089. }
  12090. if ( dispose ) {
  12091. for ( var i in geometry.attributes ) {
  12092. delete geometry.attributes[ i ].array;
  12093. }
  12094. }
  12095. };
  12096. // Buffer rendering
  12097. this.renderBufferImmediate = function ( object, program, material ) {
  12098. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12099. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12100. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12101. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12102. if ( object.hasPositions ) {
  12103. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12104. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12105. _gl.enableVertexAttribArray( program.attributes.position );
  12106. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12107. }
  12108. if ( object.hasNormals ) {
  12109. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12110. if ( material.shading === THREE.FlatShading ) {
  12111. var nx, ny, nz,
  12112. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12113. normalArray,
  12114. i, il = object.count * 3;
  12115. for( i = 0; i < il; i += 9 ) {
  12116. normalArray = object.normalArray;
  12117. nax = normalArray[ i ];
  12118. nay = normalArray[ i + 1 ];
  12119. naz = normalArray[ i + 2 ];
  12120. nbx = normalArray[ i + 3 ];
  12121. nby = normalArray[ i + 4 ];
  12122. nbz = normalArray[ i + 5 ];
  12123. ncx = normalArray[ i + 6 ];
  12124. ncy = normalArray[ i + 7 ];
  12125. ncz = normalArray[ i + 8 ];
  12126. nx = ( nax + nbx + ncx ) / 3;
  12127. ny = ( nay + nby + ncy ) / 3;
  12128. nz = ( naz + nbz + ncz ) / 3;
  12129. normalArray[ i ] = nx;
  12130. normalArray[ i + 1 ] = ny;
  12131. normalArray[ i + 2 ] = nz;
  12132. normalArray[ i + 3 ] = nx;
  12133. normalArray[ i + 4 ] = ny;
  12134. normalArray[ i + 5 ] = nz;
  12135. normalArray[ i + 6 ] = nx;
  12136. normalArray[ i + 7 ] = ny;
  12137. normalArray[ i + 8 ] = nz;
  12138. }
  12139. }
  12140. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12141. _gl.enableVertexAttribArray( program.attributes.normal );
  12142. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12143. }
  12144. if ( object.hasUvs && material.map ) {
  12145. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12146. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12147. _gl.enableVertexAttribArray( program.attributes.uv );
  12148. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12149. }
  12150. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12151. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12152. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12153. _gl.enableVertexAttribArray( program.attributes.color );
  12154. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12155. }
  12156. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12157. object.count = 0;
  12158. };
  12159. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12160. if ( material.visible === false ) return;
  12161. var program, attributes, linewidth, primitives, a, attribute;
  12162. program = setProgram( camera, lights, fog, material, object );
  12163. attributes = program.attributes;
  12164. var updateBuffers = false,
  12165. wireframeBit = material.wireframe ? 1 : 0,
  12166. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12167. if ( geometryHash !== _currentGeometryGroupHash ) {
  12168. _currentGeometryGroupHash = geometryHash;
  12169. updateBuffers = true;
  12170. }
  12171. if ( updateBuffers ) {
  12172. disableAttributes();
  12173. }
  12174. // render mesh
  12175. if ( object instanceof THREE.Mesh ) {
  12176. var index = geometry.attributes[ "index" ];
  12177. // indexed triangles
  12178. if ( index ) {
  12179. var offsets = geometry.offsets;
  12180. // if there is more than 1 chunk
  12181. // must set attribute pointers to use new offsets for each chunk
  12182. // even if geometry and materials didn't change
  12183. if ( offsets.length > 1 ) updateBuffers = true;
  12184. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12185. var startIndex = offsets[ i ].index;
  12186. if ( updateBuffers ) {
  12187. // vertices
  12188. var position = geometry.attributes[ "position" ];
  12189. var positionSize = position.itemSize;
  12190. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12191. enableAttribute( attributes.position );
  12192. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12193. // normals
  12194. var normal = geometry.attributes[ "normal" ];
  12195. if ( attributes.normal >= 0 && normal ) {
  12196. var normalSize = normal.itemSize;
  12197. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12198. enableAttribute( attributes.normal );
  12199. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12200. }
  12201. // uvs
  12202. var uv = geometry.attributes[ "uv" ];
  12203. if ( attributes.uv >= 0 && uv ) {
  12204. var uvSize = uv.itemSize;
  12205. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12206. enableAttribute( attributes.uv );
  12207. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12208. }
  12209. // colors
  12210. var color = geometry.attributes[ "color" ];
  12211. if ( attributes.color >= 0 && color ) {
  12212. var colorSize = color.itemSize;
  12213. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12214. enableAttribute( attributes.color );
  12215. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12216. }
  12217. // tangents
  12218. var tangent = geometry.attributes[ "tangent" ];
  12219. if ( attributes.tangent >= 0 && tangent ) {
  12220. var tangentSize = tangent.itemSize;
  12221. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12222. enableAttribute( attributes.tangent );
  12223. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12224. }
  12225. // indices
  12226. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12227. }
  12228. // render indexed triangles
  12229. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12230. _this.info.render.calls ++;
  12231. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12232. _this.info.render.faces += offsets[ i ].count / 3;
  12233. }
  12234. // non-indexed triangles
  12235. } else {
  12236. if ( updateBuffers ) {
  12237. // vertices
  12238. var position = geometry.attributes[ "position" ];
  12239. var positionSize = position.itemSize;
  12240. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12241. enableAttribute( attributes.position );
  12242. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12243. // normals
  12244. var normal = geometry.attributes[ "normal" ];
  12245. if ( attributes.normal >= 0 && normal ) {
  12246. var normalSize = normal.itemSize;
  12247. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12248. enableAttribute( attributes.normal );
  12249. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12250. }
  12251. // uvs
  12252. var uv = geometry.attributes[ "uv" ];
  12253. if ( attributes.uv >= 0 && uv ) {
  12254. var uvSize = uv.itemSize;
  12255. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12256. enableAttribute( attributes.uv );
  12257. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12258. }
  12259. // colors
  12260. var color = geometry.attributes[ "color" ];
  12261. if ( attributes.color >= 0 && color ) {
  12262. var colorSize = color.itemSize;
  12263. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12264. enableAttribute( attributes.color );
  12265. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12266. }
  12267. // tangents
  12268. var tangent = geometry.attributes[ "tangent" ];
  12269. if ( attributes.tangent >= 0 && tangent ) {
  12270. var tangentSize = tangent.itemSize;
  12271. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12272. enableAttribute( attributes.tangent );
  12273. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12274. }
  12275. }
  12276. // render non-indexed triangles
  12277. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12278. _this.info.render.calls ++;
  12279. _this.info.render.vertices += position.numItems / 3;
  12280. _this.info.render.faces += position.numItems / 3 / 3;
  12281. }
  12282. // render particles
  12283. } else if ( object instanceof THREE.ParticleSystem ) {
  12284. if ( updateBuffers ) {
  12285. // vertices
  12286. var position = geometry.attributes[ "position" ];
  12287. var positionSize = position.itemSize;
  12288. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12289. enableAttribute( attributes.position );
  12290. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12291. // colors
  12292. var color = geometry.attributes[ "color" ];
  12293. if ( attributes.color >= 0 && color ) {
  12294. var colorSize = color.itemSize;
  12295. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12296. enableAttribute( attributes.color );
  12297. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12298. }
  12299. // render particles
  12300. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12301. _this.info.render.calls ++;
  12302. _this.info.render.points += position.numItems / 3;
  12303. }
  12304. }
  12305. };
  12306. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12307. if ( material.visible === false ) return;
  12308. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12309. program = setProgram( camera, lights, fog, material, object );
  12310. attributes = program.attributes;
  12311. var updateBuffers = false,
  12312. wireframeBit = material.wireframe ? 1 : 0,
  12313. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12314. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12315. _currentGeometryGroupHash = geometryGroupHash;
  12316. updateBuffers = true;
  12317. }
  12318. if ( updateBuffers ) {
  12319. disableAttributes();
  12320. }
  12321. // vertices
  12322. if ( !material.morphTargets && attributes.position >= 0 ) {
  12323. if ( updateBuffers ) {
  12324. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12325. enableAttribute( attributes.position );
  12326. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12327. }
  12328. } else {
  12329. if ( object.morphTargetBase ) {
  12330. setupMorphTargets( material, geometryGroup, object );
  12331. }
  12332. }
  12333. if ( updateBuffers ) {
  12334. // custom attributes
  12335. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12336. if ( geometryGroup.__webglCustomAttributesList ) {
  12337. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12338. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12339. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12340. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12341. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12342. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12343. }
  12344. }
  12345. }
  12346. // colors
  12347. if ( attributes.color >= 0 ) {
  12348. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12349. enableAttribute( attributes.color );
  12350. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12351. }
  12352. // normals
  12353. if ( attributes.normal >= 0 ) {
  12354. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12355. enableAttribute( attributes.normal );
  12356. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12357. }
  12358. // tangents
  12359. if ( attributes.tangent >= 0 ) {
  12360. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12361. enableAttribute( attributes.tangent );
  12362. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12363. }
  12364. // uvs
  12365. if ( attributes.uv >= 0 ) {
  12366. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12367. enableAttribute( attributes.uv );
  12368. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12369. }
  12370. if ( attributes.uv2 >= 0 ) {
  12371. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12372. enableAttribute( attributes.uv2 );
  12373. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12374. }
  12375. if ( material.skinning &&
  12376. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12377. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12378. enableAttribute( attributes.skinIndex );
  12379. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12380. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12381. enableAttribute( attributes.skinWeight );
  12382. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12383. }
  12384. // line distances
  12385. if ( attributes.lineDistance >= 0 ) {
  12386. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12387. enableAttribute( attributes.lineDistance );
  12388. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12389. }
  12390. }
  12391. // render mesh
  12392. if ( object instanceof THREE.Mesh ) {
  12393. // wireframe
  12394. if ( material.wireframe ) {
  12395. setLineWidth( material.wireframeLinewidth );
  12396. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12397. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12398. // triangles
  12399. } else {
  12400. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12401. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12402. }
  12403. _this.info.render.calls ++;
  12404. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12405. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12406. // render lines
  12407. } else if ( object instanceof THREE.Line ) {
  12408. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12409. setLineWidth( material.linewidth );
  12410. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12411. _this.info.render.calls ++;
  12412. // render particles
  12413. } else if ( object instanceof THREE.ParticleSystem ) {
  12414. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12415. _this.info.render.calls ++;
  12416. _this.info.render.points += geometryGroup.__webglParticleCount;
  12417. // render ribbon
  12418. } else if ( object instanceof THREE.Ribbon ) {
  12419. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12420. _this.info.render.calls ++;
  12421. }
  12422. };
  12423. function enableAttribute( attribute ) {
  12424. if ( ! _enabledAttributes[ attribute ] ) {
  12425. _gl.enableVertexAttribArray( attribute );
  12426. _enabledAttributes[ attribute ] = true;
  12427. }
  12428. };
  12429. function disableAttributes() {
  12430. for ( var attribute in _enabledAttributes ) {
  12431. if ( _enabledAttributes[ attribute ] ) {
  12432. _gl.disableVertexAttribArray( attribute );
  12433. _enabledAttributes[ attribute ] = false;
  12434. }
  12435. }
  12436. };
  12437. function setupMorphTargets ( material, geometryGroup, object ) {
  12438. // set base
  12439. var attributes = material.program.attributes;
  12440. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  12441. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12442. enableAttribute( attributes.position );
  12443. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12444. } else if ( attributes.position >= 0 ) {
  12445. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12446. enableAttribute( attributes.position );
  12447. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12448. }
  12449. if ( object.morphTargetForcedOrder.length ) {
  12450. // set forced order
  12451. var m = 0;
  12452. var order = object.morphTargetForcedOrder;
  12453. var influences = object.morphTargetInfluences;
  12454. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12455. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12456. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12457. enableAttribute( attributes[ "morphTarget" + m ] );
  12458. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12459. }
  12460. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12461. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12462. enableAttribute( attributes[ "morphNormal" + m ] );
  12463. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12464. }
  12465. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12466. m ++;
  12467. }
  12468. } else {
  12469. // find the most influencing
  12470. var influence, activeInfluenceIndices = [];
  12471. var influences = object.morphTargetInfluences;
  12472. var i, il = influences.length;
  12473. for ( i = 0; i < il; i ++ ) {
  12474. influence = influences[ i ];
  12475. if ( influence > 0 ) {
  12476. activeInfluenceIndices.push( [ influence, i ] );
  12477. }
  12478. }
  12479. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12480. activeInfluenceIndices.sort( numericalSort );
  12481. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12482. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12483. activeInfluenceIndices.sort( numericalSort );
  12484. } else if ( activeInfluenceIndices.length === 0 ) {
  12485. activeInfluenceIndices.push( [ 0, 0 ] );
  12486. };
  12487. var influenceIndex, m = 0;
  12488. while ( m < material.numSupportedMorphTargets ) {
  12489. if ( activeInfluenceIndices[ m ] ) {
  12490. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12491. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12492. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12493. enableAttribute( attributes[ "morphTarget" + m ] );
  12494. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12495. }
  12496. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12497. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12498. enableAttribute( attributes[ "morphNormal" + m ] );
  12499. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12500. }
  12501. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12502. } else {
  12503. /*
  12504. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12505. if ( material.morphNormals ) {
  12506. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12507. }
  12508. */
  12509. object.__webglMorphTargetInfluences[ m ] = 0;
  12510. }
  12511. m ++;
  12512. }
  12513. }
  12514. // load updated influences uniform
  12515. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12516. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12517. }
  12518. };
  12519. // Sorting
  12520. function painterSortStable ( a, b ) {
  12521. if ( a.z !== b.z ) {
  12522. return b.z - a.z;
  12523. } else {
  12524. return b.id - a.id;
  12525. }
  12526. };
  12527. function numericalSort ( a, b ) {
  12528. return b[ 0 ] - a[ 0 ];
  12529. };
  12530. // Rendering
  12531. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12532. if ( camera instanceof THREE.Camera === false ) {
  12533. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12534. return;
  12535. }
  12536. var i, il,
  12537. webglObject, object,
  12538. renderList,
  12539. lights = scene.__lights,
  12540. fog = scene.fog;
  12541. // reset caching for this frame
  12542. _currentMaterialId = -1;
  12543. _lightsNeedUpdate = true;
  12544. // update scene graph
  12545. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  12546. // update camera matrices and frustum
  12547. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12548. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12549. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  12550. _frustum.setFromMatrix( _projScreenMatrix );
  12551. // update WebGL objects
  12552. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  12553. // custom render plugins (pre pass)
  12554. renderPlugins( this.renderPluginsPre, scene, camera );
  12555. //
  12556. _this.info.render.calls = 0;
  12557. _this.info.render.vertices = 0;
  12558. _this.info.render.faces = 0;
  12559. _this.info.render.points = 0;
  12560. this.setRenderTarget( renderTarget );
  12561. if ( this.autoClear || forceClear ) {
  12562. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12563. }
  12564. // set matrices for regular objects (frustum culled)
  12565. renderList = scene.__webglObjects;
  12566. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12567. webglObject = renderList[ i ];
  12568. object = webglObject.object;
  12569. webglObject.render = false;
  12570. if ( object.visible ) {
  12571. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  12572. setupMatrices( object, camera );
  12573. unrollBufferMaterial( webglObject );
  12574. webglObject.render = true;
  12575. if ( this.sortObjects === true ) {
  12576. if ( object.renderDepth !== null ) {
  12577. webglObject.z = object.renderDepth;
  12578. } else {
  12579. _vector3.copy( object.matrixWorld.getPosition() );
  12580. _projScreenMatrix.multiplyVector3( _vector3 );
  12581. webglObject.z = _vector3.z;
  12582. }
  12583. webglObject.id = object.id;
  12584. }
  12585. }
  12586. }
  12587. }
  12588. if ( this.sortObjects ) {
  12589. renderList.sort( painterSortStable );
  12590. }
  12591. // set matrices for immediate objects
  12592. renderList = scene.__webglObjectsImmediate;
  12593. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12594. webglObject = renderList[ i ];
  12595. object = webglObject.object;
  12596. if ( object.visible ) {
  12597. setupMatrices( object, camera );
  12598. unrollImmediateBufferMaterial( webglObject );
  12599. }
  12600. }
  12601. if ( scene.overrideMaterial ) {
  12602. var material = scene.overrideMaterial;
  12603. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12604. this.setDepthTest( material.depthTest );
  12605. this.setDepthWrite( material.depthWrite );
  12606. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12607. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  12608. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  12609. } else {
  12610. var material = null;
  12611. // opaque pass (front-to-back order)
  12612. this.setBlending( THREE.NoBlending );
  12613. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  12614. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  12615. // transparent pass (back-to-front order)
  12616. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  12617. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  12618. }
  12619. // custom render plugins (post pass)
  12620. renderPlugins( this.renderPluginsPost, scene, camera );
  12621. // Generate mipmap if we're using any kind of mipmap filtering
  12622. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12623. updateRenderTargetMipmap( renderTarget );
  12624. }
  12625. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12626. this.setDepthTest( true );
  12627. this.setDepthWrite( true );
  12628. // _gl.finish();
  12629. };
  12630. function renderPlugins( plugins, scene, camera ) {
  12631. if ( ! plugins.length ) return;
  12632. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  12633. // reset state for plugin (to start from clean slate)
  12634. _currentProgram = null;
  12635. _currentCamera = null;
  12636. _oldBlending = -1;
  12637. _oldDepthTest = -1;
  12638. _oldDepthWrite = -1;
  12639. _oldDoubleSided = -1;
  12640. _oldFlipSided = -1;
  12641. _currentGeometryGroupHash = -1;
  12642. _currentMaterialId = -1;
  12643. _lightsNeedUpdate = true;
  12644. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  12645. // reset state after plugin (anything could have changed)
  12646. _currentProgram = null;
  12647. _currentCamera = null;
  12648. _oldBlending = -1;
  12649. _oldDepthTest = -1;
  12650. _oldDepthWrite = -1;
  12651. _oldDoubleSided = -1;
  12652. _oldFlipSided = -1;
  12653. _currentGeometryGroupHash = -1;
  12654. _currentMaterialId = -1;
  12655. _lightsNeedUpdate = true;
  12656. }
  12657. };
  12658. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12659. var webglObject, object, buffer, material, start, end, delta;
  12660. if ( reverse ) {
  12661. start = renderList.length - 1;
  12662. end = -1;
  12663. delta = -1;
  12664. } else {
  12665. start = 0;
  12666. end = renderList.length;
  12667. delta = 1;
  12668. }
  12669. for ( var i = start; i !== end; i += delta ) {
  12670. webglObject = renderList[ i ];
  12671. if ( webglObject.render ) {
  12672. object = webglObject.object;
  12673. buffer = webglObject.buffer;
  12674. if ( overrideMaterial ) {
  12675. material = overrideMaterial;
  12676. } else {
  12677. material = webglObject[ materialType ];
  12678. if ( ! material ) continue;
  12679. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12680. _this.setDepthTest( material.depthTest );
  12681. _this.setDepthWrite( material.depthWrite );
  12682. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12683. }
  12684. _this.setMaterialFaces( material );
  12685. if ( buffer instanceof THREE.BufferGeometry ) {
  12686. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12687. } else {
  12688. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12689. }
  12690. }
  12691. }
  12692. };
  12693. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12694. var webglObject, object, material, program;
  12695. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  12696. webglObject = renderList[ i ];
  12697. object = webglObject.object;
  12698. if ( object.visible ) {
  12699. if ( overrideMaterial ) {
  12700. material = overrideMaterial;
  12701. } else {
  12702. material = webglObject[ materialType ];
  12703. if ( ! material ) continue;
  12704. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12705. _this.setDepthTest( material.depthTest );
  12706. _this.setDepthWrite( material.depthWrite );
  12707. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12708. }
  12709. _this.renderImmediateObject( camera, lights, fog, material, object );
  12710. }
  12711. }
  12712. };
  12713. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12714. var program = setProgram( camera, lights, fog, material, object );
  12715. _currentGeometryGroupHash = -1;
  12716. _this.setMaterialFaces( material );
  12717. if ( object.immediateRenderCallback ) {
  12718. object.immediateRenderCallback( program, _gl, _frustum );
  12719. } else {
  12720. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12721. }
  12722. };
  12723. function unrollImmediateBufferMaterial ( globject ) {
  12724. var object = globject.object,
  12725. material = object.material;
  12726. if ( material.transparent ) {
  12727. globject.transparent = material;
  12728. globject.opaque = null;
  12729. } else {
  12730. globject.opaque = material;
  12731. globject.transparent = null;
  12732. }
  12733. };
  12734. function unrollBufferMaterial ( globject ) {
  12735. var object = globject.object,
  12736. buffer = globject.buffer,
  12737. material, materialIndex, meshMaterial;
  12738. meshMaterial = object.material;
  12739. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  12740. materialIndex = buffer.materialIndex;
  12741. material = meshMaterial.materials[ materialIndex ];
  12742. if ( material.transparent ) {
  12743. globject.transparent = material;
  12744. globject.opaque = null;
  12745. } else {
  12746. globject.opaque = material;
  12747. globject.transparent = null;
  12748. }
  12749. } else {
  12750. material = meshMaterial;
  12751. if ( material ) {
  12752. if ( material.transparent ) {
  12753. globject.transparent = material;
  12754. globject.opaque = null;
  12755. } else {
  12756. globject.opaque = material;
  12757. globject.transparent = null;
  12758. }
  12759. }
  12760. }
  12761. };
  12762. // Geometry splitting
  12763. function sortFacesByMaterial ( geometry, material ) {
  12764. var f, fl, face, materialIndex, vertices,
  12765. groupHash, hash_map = {};
  12766. var numMorphTargets = geometry.morphTargets.length;
  12767. var numMorphNormals = geometry.morphNormals.length;
  12768. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  12769. geometry.geometryGroups = {};
  12770. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12771. face = geometry.faces[ f ];
  12772. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12773. if ( hash_map[ materialIndex ] === undefined ) {
  12774. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  12775. }
  12776. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12777. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12778. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12779. }
  12780. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12781. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12782. hash_map[ materialIndex ].counter += 1;
  12783. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12784. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12785. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12786. }
  12787. }
  12788. if ( face instanceof THREE.Face3 ) {
  12789. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12790. } else {
  12791. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12792. }
  12793. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12794. }
  12795. geometry.geometryGroupsList = [];
  12796. for ( var g in geometry.geometryGroups ) {
  12797. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12798. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12799. }
  12800. };
  12801. // Objects refresh
  12802. this.initWebGLObjects = function ( scene ) {
  12803. if ( !scene.__webglObjects ) {
  12804. scene.__webglObjects = [];
  12805. scene.__webglObjectsImmediate = [];
  12806. scene.__webglSprites = [];
  12807. scene.__webglFlares = [];
  12808. }
  12809. while ( scene.__objectsAdded.length ) {
  12810. addObject( scene.__objectsAdded[ 0 ], scene );
  12811. scene.__objectsAdded.splice( 0, 1 );
  12812. }
  12813. while ( scene.__objectsRemoved.length ) {
  12814. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12815. scene.__objectsRemoved.splice( 0, 1 );
  12816. }
  12817. // update must be called after objects adding / removal
  12818. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12819. updateObject( scene.__webglObjects[ o ].object );
  12820. }
  12821. };
  12822. // Objects adding
  12823. function addObject ( object, scene ) {
  12824. var g, geometry, material, geometryGroup;
  12825. if ( ! object.__webglInit ) {
  12826. object.__webglInit = true;
  12827. object._modelViewMatrix = new THREE.Matrix4();
  12828. object._normalMatrix = new THREE.Matrix3();
  12829. if ( object instanceof THREE.Mesh ) {
  12830. geometry = object.geometry;
  12831. material = object.material;
  12832. if ( geometry instanceof THREE.Geometry ) {
  12833. if ( geometry.geometryGroups === undefined ) {
  12834. sortFacesByMaterial( geometry, material );
  12835. }
  12836. // create separate VBOs per geometry chunk
  12837. for ( g in geometry.geometryGroups ) {
  12838. geometryGroup = geometry.geometryGroups[ g ];
  12839. // initialise VBO on the first access
  12840. if ( ! geometryGroup.__webglVertexBuffer ) {
  12841. createMeshBuffers( geometryGroup );
  12842. initMeshBuffers( geometryGroup, object );
  12843. geometry.verticesNeedUpdate = true;
  12844. geometry.morphTargetsNeedUpdate = true;
  12845. geometry.elementsNeedUpdate = true;
  12846. geometry.uvsNeedUpdate = true;
  12847. geometry.normalsNeedUpdate = true;
  12848. geometry.tangentsNeedUpdate = true;
  12849. geometry.colorsNeedUpdate = true;
  12850. }
  12851. }
  12852. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12853. initDirectBuffers( geometry );
  12854. }
  12855. } else if ( object instanceof THREE.Ribbon ) {
  12856. geometry = object.geometry;
  12857. if ( ! geometry.__webglVertexBuffer ) {
  12858. createRibbonBuffers( geometry );
  12859. initRibbonBuffers( geometry, object );
  12860. geometry.verticesNeedUpdate = true;
  12861. geometry.colorsNeedUpdate = true;
  12862. geometry.normalsNeedUpdate = true;
  12863. }
  12864. } else if ( object instanceof THREE.Line ) {
  12865. geometry = object.geometry;
  12866. if ( ! geometry.__webglVertexBuffer ) {
  12867. createLineBuffers( geometry );
  12868. initLineBuffers( geometry, object );
  12869. geometry.verticesNeedUpdate = true;
  12870. geometry.colorsNeedUpdate = true;
  12871. geometry.lineDistancesNeedUpdate = true;
  12872. }
  12873. } else if ( object instanceof THREE.ParticleSystem ) {
  12874. geometry = object.geometry;
  12875. if ( ! geometry.__webglVertexBuffer ) {
  12876. if ( geometry instanceof THREE.Geometry ) {
  12877. createParticleBuffers( geometry );
  12878. initParticleBuffers( geometry, object );
  12879. geometry.verticesNeedUpdate = true;
  12880. geometry.colorsNeedUpdate = true;
  12881. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12882. initDirectBuffers( geometry );
  12883. }
  12884. }
  12885. }
  12886. }
  12887. if ( ! object.__webglActive ) {
  12888. if ( object instanceof THREE.Mesh ) {
  12889. geometry = object.geometry;
  12890. if ( geometry instanceof THREE.BufferGeometry ) {
  12891. addBuffer( scene.__webglObjects, geometry, object );
  12892. } else {
  12893. for ( g in geometry.geometryGroups ) {
  12894. geometryGroup = geometry.geometryGroups[ g ];
  12895. addBuffer( scene.__webglObjects, geometryGroup, object );
  12896. }
  12897. }
  12898. } else if ( object instanceof THREE.Ribbon ||
  12899. object instanceof THREE.Line ||
  12900. object instanceof THREE.ParticleSystem ) {
  12901. geometry = object.geometry;
  12902. addBuffer( scene.__webglObjects, geometry, object );
  12903. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12904. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12905. } else if ( object instanceof THREE.Sprite ) {
  12906. scene.__webglSprites.push( object );
  12907. } else if ( object instanceof THREE.LensFlare ) {
  12908. scene.__webglFlares.push( object );
  12909. }
  12910. object.__webglActive = true;
  12911. }
  12912. };
  12913. function addBuffer ( objlist, buffer, object ) {
  12914. objlist.push(
  12915. {
  12916. buffer: buffer,
  12917. object: object,
  12918. opaque: null,
  12919. transparent: null
  12920. }
  12921. );
  12922. };
  12923. function addBufferImmediate ( objlist, object ) {
  12924. objlist.push(
  12925. {
  12926. object: object,
  12927. opaque: null,
  12928. transparent: null
  12929. }
  12930. );
  12931. };
  12932. // Objects updates
  12933. function updateObject ( object ) {
  12934. var geometry = object.geometry,
  12935. geometryGroup, customAttributesDirty, material;
  12936. if ( object instanceof THREE.Mesh ) {
  12937. if ( geometry instanceof THREE.BufferGeometry ) {
  12938. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12939. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12940. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12941. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12942. }
  12943. geometry.verticesNeedUpdate = false;
  12944. geometry.elementsNeedUpdate = false;
  12945. geometry.uvsNeedUpdate = false;
  12946. geometry.normalsNeedUpdate = false;
  12947. geometry.colorsNeedUpdate = false;
  12948. geometry.tangentsNeedUpdate = false;
  12949. } else {
  12950. // check all geometry groups
  12951. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12952. geometryGroup = geometry.geometryGroupsList[ i ];
  12953. material = getBufferMaterial( object, geometryGroup );
  12954. if ( geometry.buffersNeedUpdate ) {
  12955. initMeshBuffers( geometryGroup, object );
  12956. }
  12957. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12958. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12959. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12960. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12961. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12962. }
  12963. }
  12964. geometry.verticesNeedUpdate = false;
  12965. geometry.morphTargetsNeedUpdate = false;
  12966. geometry.elementsNeedUpdate = false;
  12967. geometry.uvsNeedUpdate = false;
  12968. geometry.normalsNeedUpdate = false;
  12969. geometry.colorsNeedUpdate = false;
  12970. geometry.tangentsNeedUpdate = false;
  12971. geometry.buffersNeedUpdate = false;
  12972. material.attributes && clearCustomAttributes( material );
  12973. }
  12974. } else if ( object instanceof THREE.Ribbon ) {
  12975. material = getBufferMaterial( object, geometry );
  12976. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12977. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12978. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12979. }
  12980. geometry.verticesNeedUpdate = false;
  12981. geometry.colorsNeedUpdate = false;
  12982. geometry.normalsNeedUpdate = false;
  12983. material.attributes && clearCustomAttributes( material );
  12984. } else if ( object instanceof THREE.Line ) {
  12985. material = getBufferMaterial( object, geometry );
  12986. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12987. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12988. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12989. }
  12990. geometry.verticesNeedUpdate = false;
  12991. geometry.colorsNeedUpdate = false;
  12992. geometry.lineDistancesNeedUpdate = false;
  12993. material.attributes && clearCustomAttributes( material );
  12994. } else if ( object instanceof THREE.ParticleSystem ) {
  12995. if ( geometry instanceof THREE.BufferGeometry ) {
  12996. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12997. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12998. }
  12999. geometry.verticesNeedUpdate = false;
  13000. geometry.colorsNeedUpdate = false;
  13001. } else {
  13002. material = getBufferMaterial( object, geometry );
  13003. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13004. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13005. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13006. }
  13007. geometry.verticesNeedUpdate = false;
  13008. geometry.colorsNeedUpdate = false;
  13009. material.attributes && clearCustomAttributes( material );
  13010. }
  13011. }
  13012. };
  13013. // Objects updates - custom attributes check
  13014. function areCustomAttributesDirty ( material ) {
  13015. for ( var a in material.attributes ) {
  13016. if ( material.attributes[ a ].needsUpdate ) return true;
  13017. }
  13018. return false;
  13019. };
  13020. function clearCustomAttributes ( material ) {
  13021. for ( var a in material.attributes ) {
  13022. material.attributes[ a ].needsUpdate = false;
  13023. }
  13024. };
  13025. // Objects removal
  13026. function removeObject ( object, scene ) {
  13027. if ( object instanceof THREE.Mesh ||
  13028. object instanceof THREE.ParticleSystem ||
  13029. object instanceof THREE.Ribbon ||
  13030. object instanceof THREE.Line ) {
  13031. removeInstances( scene.__webglObjects, object );
  13032. } else if ( object instanceof THREE.Sprite ) {
  13033. removeInstancesDirect( scene.__webglSprites, object );
  13034. } else if ( object instanceof THREE.LensFlare ) {
  13035. removeInstancesDirect( scene.__webglFlares, object );
  13036. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13037. removeInstances( scene.__webglObjectsImmediate, object );
  13038. }
  13039. object.__webglActive = false;
  13040. };
  13041. function removeInstances ( objlist, object ) {
  13042. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13043. if ( objlist[ o ].object === object ) {
  13044. objlist.splice( o, 1 );
  13045. }
  13046. }
  13047. };
  13048. function removeInstancesDirect ( objlist, object ) {
  13049. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13050. if ( objlist[ o ] === object ) {
  13051. objlist.splice( o, 1 );
  13052. }
  13053. }
  13054. };
  13055. // Materials
  13056. this.initMaterial = function ( material, lights, fog, object ) {
  13057. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13058. if ( material instanceof THREE.MeshDepthMaterial ) {
  13059. shaderID = 'depth';
  13060. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13061. shaderID = 'normal';
  13062. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13063. shaderID = 'basic';
  13064. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13065. shaderID = 'lambert';
  13066. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13067. shaderID = 'phong';
  13068. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13069. shaderID = 'basic';
  13070. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13071. shaderID = 'dashed';
  13072. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13073. shaderID = 'particle_basic';
  13074. }
  13075. if ( shaderID ) {
  13076. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13077. }
  13078. // heuristics to create shader parameters according to lights in the scene
  13079. // (not to blow over maxLights budget)
  13080. maxLightCount = allocateLights( lights );
  13081. maxShadows = allocateShadows( lights );
  13082. maxBones = allocateBones( object );
  13083. parameters = {
  13084. map: !!material.map,
  13085. envMap: !!material.envMap,
  13086. lightMap: !!material.lightMap,
  13087. bumpMap: !!material.bumpMap,
  13088. normalMap: !!material.normalMap,
  13089. specularMap: !!material.specularMap,
  13090. vertexColors: material.vertexColors,
  13091. fog: fog,
  13092. useFog: material.fog,
  13093. fogExp: fog instanceof THREE.FogExp2,
  13094. sizeAttenuation: material.sizeAttenuation,
  13095. skinning: material.skinning,
  13096. maxBones: maxBones,
  13097. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13098. boneTextureWidth: object && object.boneTextureWidth,
  13099. boneTextureHeight: object && object.boneTextureHeight,
  13100. morphTargets: material.morphTargets,
  13101. morphNormals: material.morphNormals,
  13102. maxMorphTargets: this.maxMorphTargets,
  13103. maxMorphNormals: this.maxMorphNormals,
  13104. maxDirLights: maxLightCount.directional,
  13105. maxPointLights: maxLightCount.point,
  13106. maxSpotLights: maxLightCount.spot,
  13107. maxHemiLights: maxLightCount.hemi,
  13108. maxShadows: maxShadows,
  13109. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13110. shadowMapType: this.shadowMapType,
  13111. shadowMapDebug: this.shadowMapDebug,
  13112. shadowMapCascade: this.shadowMapCascade,
  13113. alphaTest: material.alphaTest,
  13114. metal: material.metal,
  13115. perPixel: material.perPixel,
  13116. wrapAround: material.wrapAround,
  13117. doubleSided: material.side === THREE.DoubleSide,
  13118. flipSided: material.side === THREE.BackSide
  13119. };
  13120. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13121. var attributes = material.program.attributes;
  13122. if ( material.morphTargets ) {
  13123. material.numSupportedMorphTargets = 0;
  13124. var id, base = "morphTarget";
  13125. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13126. id = base + i;
  13127. if ( attributes[ id ] >= 0 ) {
  13128. material.numSupportedMorphTargets ++;
  13129. }
  13130. }
  13131. }
  13132. if ( material.morphNormals ) {
  13133. material.numSupportedMorphNormals = 0;
  13134. var id, base = "morphNormal";
  13135. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13136. id = base + i;
  13137. if ( attributes[ id ] >= 0 ) {
  13138. material.numSupportedMorphNormals ++;
  13139. }
  13140. }
  13141. }
  13142. material.uniformsList = [];
  13143. for ( u in material.uniforms ) {
  13144. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13145. }
  13146. };
  13147. function setMaterialShaders( material, shaders ) {
  13148. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13149. material.vertexShader = shaders.vertexShader;
  13150. material.fragmentShader = shaders.fragmentShader;
  13151. };
  13152. function setProgram( camera, lights, fog, material, object ) {
  13153. _usedTextureUnits = 0;
  13154. if ( material.needsUpdate ) {
  13155. if ( material.program ) _this.deallocateMaterial( material );
  13156. _this.initMaterial( material, lights, fog, object );
  13157. material.needsUpdate = false;
  13158. }
  13159. if ( material.morphTargets ) {
  13160. if ( ! object.__webglMorphTargetInfluences ) {
  13161. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13162. }
  13163. }
  13164. var refreshMaterial = false;
  13165. var program = material.program,
  13166. p_uniforms = program.uniforms,
  13167. m_uniforms = material.uniforms;
  13168. if ( program !== _currentProgram ) {
  13169. _gl.useProgram( program );
  13170. _currentProgram = program;
  13171. refreshMaterial = true;
  13172. }
  13173. if ( material.id !== _currentMaterialId ) {
  13174. _currentMaterialId = material.id;
  13175. refreshMaterial = true;
  13176. }
  13177. if ( refreshMaterial || camera !== _currentCamera ) {
  13178. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13179. if ( camera !== _currentCamera ) _currentCamera = camera;
  13180. }
  13181. // skinning uniforms must be set even if material didn't change
  13182. // auto-setting of texture unit for bone texture must go before other textures
  13183. // not sure why, but otherwise weird things happen
  13184. if ( material.skinning ) {
  13185. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13186. if ( p_uniforms.boneTexture !== null ) {
  13187. var textureUnit = getTextureUnit();
  13188. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13189. _this.setTexture( object.boneTexture, textureUnit );
  13190. }
  13191. } else {
  13192. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13193. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13194. }
  13195. }
  13196. }
  13197. if ( refreshMaterial ) {
  13198. // refresh uniforms common to several materials
  13199. if ( fog && material.fog ) {
  13200. refreshUniformsFog( m_uniforms, fog );
  13201. }
  13202. if ( material instanceof THREE.MeshPhongMaterial ||
  13203. material instanceof THREE.MeshLambertMaterial ||
  13204. material.lights ) {
  13205. if ( _lightsNeedUpdate ) {
  13206. setupLights( program, lights );
  13207. _lightsNeedUpdate = false;
  13208. }
  13209. refreshUniformsLights( m_uniforms, _lights );
  13210. }
  13211. if ( material instanceof THREE.MeshBasicMaterial ||
  13212. material instanceof THREE.MeshLambertMaterial ||
  13213. material instanceof THREE.MeshPhongMaterial ) {
  13214. refreshUniformsCommon( m_uniforms, material );
  13215. }
  13216. // refresh single material specific uniforms
  13217. if ( material instanceof THREE.LineBasicMaterial ) {
  13218. refreshUniformsLine( m_uniforms, material );
  13219. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13220. refreshUniformsLine( m_uniforms, material );
  13221. refreshUniformsDash( m_uniforms, material );
  13222. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13223. refreshUniformsParticle( m_uniforms, material );
  13224. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13225. refreshUniformsPhong( m_uniforms, material );
  13226. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13227. refreshUniformsLambert( m_uniforms, material );
  13228. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13229. m_uniforms.mNear.value = camera.near;
  13230. m_uniforms.mFar.value = camera.far;
  13231. m_uniforms.opacity.value = material.opacity;
  13232. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13233. m_uniforms.opacity.value = material.opacity;
  13234. }
  13235. if ( object.receiveShadow && ! material._shadowPass ) {
  13236. refreshUniformsShadow( m_uniforms, lights );
  13237. }
  13238. // load common uniforms
  13239. loadUniformsGeneric( program, material.uniformsList );
  13240. // load material specific uniforms
  13241. // (shader material also gets them for the sake of genericity)
  13242. if ( material instanceof THREE.ShaderMaterial ||
  13243. material instanceof THREE.MeshPhongMaterial ||
  13244. material.envMap ) {
  13245. if ( p_uniforms.cameraPosition !== null ) {
  13246. var position = camera.matrixWorld.getPosition();
  13247. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13248. }
  13249. }
  13250. if ( material instanceof THREE.MeshPhongMaterial ||
  13251. material instanceof THREE.MeshLambertMaterial ||
  13252. material instanceof THREE.ShaderMaterial ||
  13253. material.skinning ) {
  13254. if ( p_uniforms.viewMatrix !== null ) {
  13255. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13256. }
  13257. }
  13258. }
  13259. loadUniformsMatrices( p_uniforms, object );
  13260. if ( p_uniforms.modelMatrix !== null ) {
  13261. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13262. }
  13263. return program;
  13264. };
  13265. // Uniforms (refresh uniforms objects)
  13266. function refreshUniformsCommon ( uniforms, material ) {
  13267. uniforms.opacity.value = material.opacity;
  13268. if ( _this.gammaInput ) {
  13269. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13270. } else {
  13271. uniforms.diffuse.value = material.color;
  13272. }
  13273. uniforms.map.value = material.map;
  13274. uniforms.lightMap.value = material.lightMap;
  13275. uniforms.specularMap.value = material.specularMap;
  13276. if ( material.bumpMap ) {
  13277. uniforms.bumpMap.value = material.bumpMap;
  13278. uniforms.bumpScale.value = material.bumpScale;
  13279. }
  13280. if ( material.normalMap ) {
  13281. uniforms.normalMap.value = material.normalMap;
  13282. uniforms.normalScale.value.copy( material.normalScale );
  13283. }
  13284. // uv repeat and offset setting priorities
  13285. // 1. color map
  13286. // 2. specular map
  13287. // 3. normal map
  13288. // 4. bump map
  13289. var uvScaleMap;
  13290. if ( material.map ) {
  13291. uvScaleMap = material.map;
  13292. } else if ( material.specularMap ) {
  13293. uvScaleMap = material.specularMap;
  13294. } else if ( material.normalMap ) {
  13295. uvScaleMap = material.normalMap;
  13296. } else if ( material.bumpMap ) {
  13297. uvScaleMap = material.bumpMap;
  13298. }
  13299. if ( uvScaleMap !== undefined ) {
  13300. var offset = uvScaleMap.offset;
  13301. var repeat = uvScaleMap.repeat;
  13302. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13303. }
  13304. uniforms.envMap.value = material.envMap;
  13305. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13306. if ( _this.gammaInput ) {
  13307. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13308. uniforms.reflectivity.value = material.reflectivity;
  13309. } else {
  13310. uniforms.reflectivity.value = material.reflectivity;
  13311. }
  13312. uniforms.refractionRatio.value = material.refractionRatio;
  13313. uniforms.combine.value = material.combine;
  13314. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13315. };
  13316. function refreshUniformsLine ( uniforms, material ) {
  13317. uniforms.diffuse.value = material.color;
  13318. uniforms.opacity.value = material.opacity;
  13319. };
  13320. function refreshUniformsDash ( uniforms, material ) {
  13321. uniforms.dashSize.value = material.dashSize;
  13322. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13323. uniforms.scale.value = material.scale;
  13324. };
  13325. function refreshUniformsParticle ( uniforms, material ) {
  13326. uniforms.psColor.value = material.color;
  13327. uniforms.opacity.value = material.opacity;
  13328. uniforms.size.value = material.size;
  13329. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13330. uniforms.map.value = material.map;
  13331. };
  13332. function refreshUniformsFog ( uniforms, fog ) {
  13333. uniforms.fogColor.value = fog.color;
  13334. if ( fog instanceof THREE.Fog ) {
  13335. uniforms.fogNear.value = fog.near;
  13336. uniforms.fogFar.value = fog.far;
  13337. } else if ( fog instanceof THREE.FogExp2 ) {
  13338. uniforms.fogDensity.value = fog.density;
  13339. }
  13340. };
  13341. function refreshUniformsPhong ( uniforms, material ) {
  13342. uniforms.shininess.value = material.shininess;
  13343. if ( _this.gammaInput ) {
  13344. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13345. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13346. uniforms.specular.value.copyGammaToLinear( material.specular );
  13347. } else {
  13348. uniforms.ambient.value = material.ambient;
  13349. uniforms.emissive.value = material.emissive;
  13350. uniforms.specular.value = material.specular;
  13351. }
  13352. if ( material.wrapAround ) {
  13353. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13354. }
  13355. };
  13356. function refreshUniformsLambert ( uniforms, material ) {
  13357. if ( _this.gammaInput ) {
  13358. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13359. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13360. } else {
  13361. uniforms.ambient.value = material.ambient;
  13362. uniforms.emissive.value = material.emissive;
  13363. }
  13364. if ( material.wrapAround ) {
  13365. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13366. }
  13367. };
  13368. function refreshUniformsLights ( uniforms, lights ) {
  13369. uniforms.ambientLightColor.value = lights.ambient;
  13370. uniforms.directionalLightColor.value = lights.directional.colors;
  13371. uniforms.directionalLightDirection.value = lights.directional.positions;
  13372. uniforms.pointLightColor.value = lights.point.colors;
  13373. uniforms.pointLightPosition.value = lights.point.positions;
  13374. uniforms.pointLightDistance.value = lights.point.distances;
  13375. uniforms.spotLightColor.value = lights.spot.colors;
  13376. uniforms.spotLightPosition.value = lights.spot.positions;
  13377. uniforms.spotLightDistance.value = lights.spot.distances;
  13378. uniforms.spotLightDirection.value = lights.spot.directions;
  13379. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13380. uniforms.spotLightExponent.value = lights.spot.exponents;
  13381. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13382. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13383. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13384. };
  13385. function refreshUniformsShadow ( uniforms, lights ) {
  13386. if ( uniforms.shadowMatrix ) {
  13387. var j = 0;
  13388. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13389. var light = lights[ i ];
  13390. if ( ! light.castShadow ) continue;
  13391. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13392. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13393. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13394. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13395. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13396. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13397. j ++;
  13398. }
  13399. }
  13400. }
  13401. };
  13402. // Uniforms (load to GPU)
  13403. function loadUniformsMatrices ( uniforms, object ) {
  13404. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13405. if ( uniforms.normalMatrix ) {
  13406. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13407. }
  13408. };
  13409. function getTextureUnit() {
  13410. var textureUnit = _usedTextureUnits;
  13411. if ( textureUnit >= _maxTextures ) {
  13412. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13413. }
  13414. _usedTextureUnits += 1;
  13415. return textureUnit;
  13416. };
  13417. function loadUniformsGeneric ( program, uniforms ) {
  13418. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13419. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13420. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  13421. if ( !location ) continue;
  13422. uniform = uniforms[ j ][ 0 ];
  13423. type = uniform.type;
  13424. value = uniform.value;
  13425. if ( type === "i" ) { // single integer
  13426. _gl.uniform1i( location, value );
  13427. } else if ( type === "f" ) { // single float
  13428. _gl.uniform1f( location, value );
  13429. } else if ( type === "v2" ) { // single THREE.Vector2
  13430. _gl.uniform2f( location, value.x, value.y );
  13431. } else if ( type === "v3" ) { // single THREE.Vector3
  13432. _gl.uniform3f( location, value.x, value.y, value.z );
  13433. } else if ( type === "v4" ) { // single THREE.Vector4
  13434. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13435. } else if ( type === "c" ) { // single THREE.Color
  13436. _gl.uniform3f( location, value.r, value.g, value.b );
  13437. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  13438. _gl.uniform1iv( location, value );
  13439. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  13440. _gl.uniform3iv( location, value );
  13441. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  13442. _gl.uniform1fv( location, value );
  13443. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  13444. _gl.uniform3fv( location, value );
  13445. } else if ( type === "v2v" ) { // array of THREE.Vector2
  13446. if ( uniform._array === undefined ) {
  13447. uniform._array = new Float32Array( 2 * value.length );
  13448. }
  13449. for ( i = 0, il = value.length; i < il; i ++ ) {
  13450. offset = i * 2;
  13451. uniform._array[ offset ] = value[ i ].x;
  13452. uniform._array[ offset + 1 ] = value[ i ].y;
  13453. }
  13454. _gl.uniform2fv( location, uniform._array );
  13455. } else if ( type === "v3v" ) { // array of THREE.Vector3
  13456. if ( uniform._array === undefined ) {
  13457. uniform._array = new Float32Array( 3 * value.length );
  13458. }
  13459. for ( i = 0, il = value.length; i < il; i ++ ) {
  13460. offset = i * 3;
  13461. uniform._array[ offset ] = value[ i ].x;
  13462. uniform._array[ offset + 1 ] = value[ i ].y;
  13463. uniform._array[ offset + 2 ] = value[ i ].z;
  13464. }
  13465. _gl.uniform3fv( location, uniform._array );
  13466. } else if ( type === "v4v" ) { // array of THREE.Vector4
  13467. if ( uniform._array === undefined ) {
  13468. uniform._array = new Float32Array( 4 * value.length );
  13469. }
  13470. for ( i = 0, il = value.length; i < il; i ++ ) {
  13471. offset = i * 4;
  13472. uniform._array[ offset ] = value[ i ].x;
  13473. uniform._array[ offset + 1 ] = value[ i ].y;
  13474. uniform._array[ offset + 2 ] = value[ i ].z;
  13475. uniform._array[ offset + 3 ] = value[ i ].w;
  13476. }
  13477. _gl.uniform4fv( location, uniform._array );
  13478. } else if ( type === "m4") { // single THREE.Matrix4
  13479. if ( uniform._array === undefined ) {
  13480. uniform._array = new Float32Array( 16 );
  13481. }
  13482. value.flattenToArray( uniform._array );
  13483. _gl.uniformMatrix4fv( location, false, uniform._array );
  13484. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  13485. if ( uniform._array === undefined ) {
  13486. uniform._array = new Float32Array( 16 * value.length );
  13487. }
  13488. for ( i = 0, il = value.length; i < il; i ++ ) {
  13489. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13490. }
  13491. _gl.uniformMatrix4fv( location, false, uniform._array );
  13492. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  13493. texture = value;
  13494. textureUnit = getTextureUnit();
  13495. _gl.uniform1i( location, textureUnit );
  13496. if ( !texture ) continue;
  13497. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  13498. setCubeTexture( texture, textureUnit );
  13499. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13500. setCubeTextureDynamic( texture, textureUnit );
  13501. } else {
  13502. _this.setTexture( texture, textureUnit );
  13503. }
  13504. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  13505. if ( uniform._array === undefined ) {
  13506. uniform._array = [];
  13507. }
  13508. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13509. uniform._array[ i ] = getTextureUnit();
  13510. }
  13511. _gl.uniform1iv( location, uniform._array );
  13512. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13513. texture = uniform.value[ i ];
  13514. textureUnit = uniform._array[ i ];
  13515. if ( !texture ) continue;
  13516. _this.setTexture( texture, textureUnit );
  13517. }
  13518. }
  13519. }
  13520. };
  13521. function setupMatrices ( object, camera ) {
  13522. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  13523. object._normalMatrix.getInverse( object._modelViewMatrix );
  13524. object._normalMatrix.transpose();
  13525. };
  13526. //
  13527. function setColorGamma( array, offset, color, intensitySq ) {
  13528. array[ offset ] = color.r * color.r * intensitySq;
  13529. array[ offset + 1 ] = color.g * color.g * intensitySq;
  13530. array[ offset + 2 ] = color.b * color.b * intensitySq;
  13531. };
  13532. function setColorLinear( array, offset, color, intensity ) {
  13533. array[ offset ] = color.r * intensity;
  13534. array[ offset + 1 ] = color.g * intensity;
  13535. array[ offset + 2 ] = color.b * intensity;
  13536. };
  13537. function setupLights ( program, lights ) {
  13538. var l, ll, light, n,
  13539. r = 0, g = 0, b = 0,
  13540. color, skyColor, groundColor,
  13541. intensity, intensitySq,
  13542. position,
  13543. distance,
  13544. zlights = _lights,
  13545. dirColors = zlights.directional.colors,
  13546. dirPositions = zlights.directional.positions,
  13547. pointColors = zlights.point.colors,
  13548. pointPositions = zlights.point.positions,
  13549. pointDistances = zlights.point.distances,
  13550. spotColors = zlights.spot.colors,
  13551. spotPositions = zlights.spot.positions,
  13552. spotDistances = zlights.spot.distances,
  13553. spotDirections = zlights.spot.directions,
  13554. spotAnglesCos = zlights.spot.anglesCos,
  13555. spotExponents = zlights.spot.exponents,
  13556. hemiSkyColors = zlights.hemi.skyColors,
  13557. hemiGroundColors = zlights.hemi.groundColors,
  13558. hemiPositions = zlights.hemi.positions,
  13559. dirLength = 0,
  13560. pointLength = 0,
  13561. spotLength = 0,
  13562. hemiLength = 0,
  13563. dirCount = 0,
  13564. pointCount = 0,
  13565. spotCount = 0,
  13566. hemiCount = 0,
  13567. dirOffset = 0,
  13568. pointOffset = 0,
  13569. spotOffset = 0,
  13570. hemiOffset = 0;
  13571. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13572. light = lights[ l ];
  13573. if ( light.onlyShadow ) continue;
  13574. color = light.color;
  13575. intensity = light.intensity;
  13576. distance = light.distance;
  13577. if ( light instanceof THREE.AmbientLight ) {
  13578. if ( ! light.visible ) continue;
  13579. if ( _this.gammaInput ) {
  13580. r += color.r * color.r;
  13581. g += color.g * color.g;
  13582. b += color.b * color.b;
  13583. } else {
  13584. r += color.r;
  13585. g += color.g;
  13586. b += color.b;
  13587. }
  13588. } else if ( light instanceof THREE.DirectionalLight ) {
  13589. dirCount += 1;
  13590. if ( ! light.visible ) continue;
  13591. _direction.copy( light.matrixWorld.getPosition() );
  13592. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13593. _direction.normalize();
  13594. // skip lights with undefined direction
  13595. // these create troubles in OpenGL (making pixel black)
  13596. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13597. dirOffset = dirLength * 3;
  13598. dirPositions[ dirOffset ] = _direction.x;
  13599. dirPositions[ dirOffset + 1 ] = _direction.y;
  13600. dirPositions[ dirOffset + 2 ] = _direction.z;
  13601. if ( _this.gammaInput ) {
  13602. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  13603. } else {
  13604. setColorLinear( dirColors, dirOffset, color, intensity );
  13605. }
  13606. dirLength += 1;
  13607. } else if ( light instanceof THREE.PointLight ) {
  13608. pointCount += 1;
  13609. if ( ! light.visible ) continue;
  13610. pointOffset = pointLength * 3;
  13611. if ( _this.gammaInput ) {
  13612. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  13613. } else {
  13614. setColorLinear( pointColors, pointOffset, color, intensity );
  13615. }
  13616. position = light.matrixWorld.getPosition();
  13617. pointPositions[ pointOffset ] = position.x;
  13618. pointPositions[ pointOffset + 1 ] = position.y;
  13619. pointPositions[ pointOffset + 2 ] = position.z;
  13620. pointDistances[ pointLength ] = distance;
  13621. pointLength += 1;
  13622. } else if ( light instanceof THREE.SpotLight ) {
  13623. spotCount += 1;
  13624. if ( ! light.visible ) continue;
  13625. spotOffset = spotLength * 3;
  13626. if ( _this.gammaInput ) {
  13627. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  13628. } else {
  13629. setColorLinear( spotColors, spotOffset, color, intensity );
  13630. }
  13631. position = light.matrixWorld.getPosition();
  13632. spotPositions[ spotOffset ] = position.x;
  13633. spotPositions[ spotOffset + 1 ] = position.y;
  13634. spotPositions[ spotOffset + 2 ] = position.z;
  13635. spotDistances[ spotLength ] = distance;
  13636. _direction.copy( position );
  13637. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13638. _direction.normalize();
  13639. spotDirections[ spotOffset ] = _direction.x;
  13640. spotDirections[ spotOffset + 1 ] = _direction.y;
  13641. spotDirections[ spotOffset + 2 ] = _direction.z;
  13642. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13643. spotExponents[ spotLength ] = light.exponent;
  13644. spotLength += 1;
  13645. } else if ( light instanceof THREE.HemisphereLight ) {
  13646. hemiCount += 1;
  13647. if ( ! light.visible ) continue;
  13648. _direction.copy( light.matrixWorld.getPosition() );
  13649. _direction.normalize();
  13650. // skip lights with undefined direction
  13651. // these create troubles in OpenGL (making pixel black)
  13652. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13653. hemiOffset = hemiLength * 3;
  13654. hemiPositions[ hemiOffset ] = _direction.x;
  13655. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13656. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13657. skyColor = light.color;
  13658. groundColor = light.groundColor;
  13659. if ( _this.gammaInput ) {
  13660. intensitySq = intensity * intensity;
  13661. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  13662. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  13663. } else {
  13664. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13665. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13666. }
  13667. hemiLength += 1;
  13668. }
  13669. }
  13670. // null eventual remains from removed lights
  13671. // (this is to avoid if in shader)
  13672. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13673. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13674. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13675. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13676. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13677. zlights.directional.length = dirLength;
  13678. zlights.point.length = pointLength;
  13679. zlights.spot.length = spotLength;
  13680. zlights.hemi.length = hemiLength;
  13681. zlights.ambient[ 0 ] = r;
  13682. zlights.ambient[ 1 ] = g;
  13683. zlights.ambient[ 2 ] = b;
  13684. };
  13685. // GL state setting
  13686. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13687. if ( cullFace === THREE.CullFaceNone ) {
  13688. _gl.disable( _gl.CULL_FACE );
  13689. } else {
  13690. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13691. _gl.frontFace( _gl.CW );
  13692. } else {
  13693. _gl.frontFace( _gl.CCW );
  13694. }
  13695. if ( cullFace === THREE.CullFaceBack ) {
  13696. _gl.cullFace( _gl.BACK );
  13697. } else if ( cullFace === THREE.CullFaceFront ) {
  13698. _gl.cullFace( _gl.FRONT );
  13699. } else {
  13700. _gl.cullFace( _gl.FRONT_AND_BACK );
  13701. }
  13702. _gl.enable( _gl.CULL_FACE );
  13703. }
  13704. };
  13705. this.setMaterialFaces = function ( material ) {
  13706. var doubleSided = material.side === THREE.DoubleSide;
  13707. var flipSided = material.side === THREE.BackSide;
  13708. if ( _oldDoubleSided !== doubleSided ) {
  13709. if ( doubleSided ) {
  13710. _gl.disable( _gl.CULL_FACE );
  13711. } else {
  13712. _gl.enable( _gl.CULL_FACE );
  13713. }
  13714. _oldDoubleSided = doubleSided;
  13715. }
  13716. if ( _oldFlipSided !== flipSided ) {
  13717. if ( flipSided ) {
  13718. _gl.frontFace( _gl.CW );
  13719. } else {
  13720. _gl.frontFace( _gl.CCW );
  13721. }
  13722. _oldFlipSided = flipSided;
  13723. }
  13724. };
  13725. this.setDepthTest = function ( depthTest ) {
  13726. if ( _oldDepthTest !== depthTest ) {
  13727. if ( depthTest ) {
  13728. _gl.enable( _gl.DEPTH_TEST );
  13729. } else {
  13730. _gl.disable( _gl.DEPTH_TEST );
  13731. }
  13732. _oldDepthTest = depthTest;
  13733. }
  13734. };
  13735. this.setDepthWrite = function ( depthWrite ) {
  13736. if ( _oldDepthWrite !== depthWrite ) {
  13737. _gl.depthMask( depthWrite );
  13738. _oldDepthWrite = depthWrite;
  13739. }
  13740. };
  13741. function setLineWidth ( width ) {
  13742. if ( width !== _oldLineWidth ) {
  13743. _gl.lineWidth( width );
  13744. _oldLineWidth = width;
  13745. }
  13746. };
  13747. function setPolygonOffset ( polygonoffset, factor, units ) {
  13748. if ( _oldPolygonOffset !== polygonoffset ) {
  13749. if ( polygonoffset ) {
  13750. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13751. } else {
  13752. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13753. }
  13754. _oldPolygonOffset = polygonoffset;
  13755. }
  13756. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13757. _gl.polygonOffset( factor, units );
  13758. _oldPolygonOffsetFactor = factor;
  13759. _oldPolygonOffsetUnits = units;
  13760. }
  13761. };
  13762. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13763. if ( blending !== _oldBlending ) {
  13764. if ( blending === THREE.NoBlending ) {
  13765. _gl.disable( _gl.BLEND );
  13766. } else if ( blending === THREE.AdditiveBlending ) {
  13767. _gl.enable( _gl.BLEND );
  13768. _gl.blendEquation( _gl.FUNC_ADD );
  13769. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13770. } else if ( blending === THREE.SubtractiveBlending ) {
  13771. // TODO: Find blendFuncSeparate() combination
  13772. _gl.enable( _gl.BLEND );
  13773. _gl.blendEquation( _gl.FUNC_ADD );
  13774. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13775. } else if ( blending === THREE.MultiplyBlending ) {
  13776. // TODO: Find blendFuncSeparate() combination
  13777. _gl.enable( _gl.BLEND );
  13778. _gl.blendEquation( _gl.FUNC_ADD );
  13779. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13780. } else if ( blending === THREE.CustomBlending ) {
  13781. _gl.enable( _gl.BLEND );
  13782. } else {
  13783. _gl.enable( _gl.BLEND );
  13784. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13785. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13786. }
  13787. _oldBlending = blending;
  13788. }
  13789. if ( blending === THREE.CustomBlending ) {
  13790. if ( blendEquation !== _oldBlendEquation ) {
  13791. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13792. _oldBlendEquation = blendEquation;
  13793. }
  13794. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13795. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13796. _oldBlendSrc = blendSrc;
  13797. _oldBlendDst = blendDst;
  13798. }
  13799. } else {
  13800. _oldBlendEquation = null;
  13801. _oldBlendSrc = null;
  13802. _oldBlendDst = null;
  13803. }
  13804. };
  13805. // Defines
  13806. function generateDefines ( defines ) {
  13807. var value, chunk, chunks = [];
  13808. for ( var d in defines ) {
  13809. value = defines[ d ];
  13810. if ( value === false ) continue;
  13811. chunk = "#define " + d + " " + value;
  13812. chunks.push( chunk );
  13813. }
  13814. return chunks.join( "\n" );
  13815. };
  13816. // Shaders
  13817. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13818. var p, pl, d, program, code;
  13819. var chunks = [];
  13820. // Generate code
  13821. if ( shaderID ) {
  13822. chunks.push( shaderID );
  13823. } else {
  13824. chunks.push( fragmentShader );
  13825. chunks.push( vertexShader );
  13826. }
  13827. for ( d in defines ) {
  13828. chunks.push( d );
  13829. chunks.push( defines[ d ] );
  13830. }
  13831. for ( p in parameters ) {
  13832. chunks.push( p );
  13833. chunks.push( parameters[ p ] );
  13834. }
  13835. code = chunks.join();
  13836. // Check if code has been already compiled
  13837. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13838. var programInfo = _programs[ p ];
  13839. if ( programInfo.code === code ) {
  13840. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13841. programInfo.usedTimes ++;
  13842. return programInfo.program;
  13843. }
  13844. }
  13845. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  13846. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  13847. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  13848. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  13849. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  13850. }
  13851. //console.log( "building new program " );
  13852. //
  13853. var customDefines = generateDefines( defines );
  13854. //
  13855. program = _gl.createProgram();
  13856. var prefix_vertex = [
  13857. "precision " + _precision + " float;",
  13858. customDefines,
  13859. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13860. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13861. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13862. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13863. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13864. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13865. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13866. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13867. "#define MAX_SHADOWS " + parameters.maxShadows,
  13868. "#define MAX_BONES " + parameters.maxBones,
  13869. parameters.map ? "#define USE_MAP" : "",
  13870. parameters.envMap ? "#define USE_ENVMAP" : "",
  13871. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13872. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13873. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13874. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13875. parameters.vertexColors ? "#define USE_COLOR" : "",
  13876. parameters.skinning ? "#define USE_SKINNING" : "",
  13877. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13878. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13879. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13880. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13881. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13882. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13883. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13884. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13885. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13886. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13887. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13888. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13889. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13890. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13891. "uniform mat4 modelMatrix;",
  13892. "uniform mat4 modelViewMatrix;",
  13893. "uniform mat4 projectionMatrix;",
  13894. "uniform mat4 viewMatrix;",
  13895. "uniform mat3 normalMatrix;",
  13896. "uniform vec3 cameraPosition;",
  13897. "attribute vec3 position;",
  13898. "attribute vec3 normal;",
  13899. "attribute vec2 uv;",
  13900. "attribute vec2 uv2;",
  13901. "#ifdef USE_COLOR",
  13902. "attribute vec3 color;",
  13903. "#endif",
  13904. "#ifdef USE_MORPHTARGETS",
  13905. "attribute vec3 morphTarget0;",
  13906. "attribute vec3 morphTarget1;",
  13907. "attribute vec3 morphTarget2;",
  13908. "attribute vec3 morphTarget3;",
  13909. "#ifdef USE_MORPHNORMALS",
  13910. "attribute vec3 morphNormal0;",
  13911. "attribute vec3 morphNormal1;",
  13912. "attribute vec3 morphNormal2;",
  13913. "attribute vec3 morphNormal3;",
  13914. "#else",
  13915. "attribute vec3 morphTarget4;",
  13916. "attribute vec3 morphTarget5;",
  13917. "attribute vec3 morphTarget6;",
  13918. "attribute vec3 morphTarget7;",
  13919. "#endif",
  13920. "#endif",
  13921. "#ifdef USE_SKINNING",
  13922. "attribute vec4 skinIndex;",
  13923. "attribute vec4 skinWeight;",
  13924. "#endif",
  13925. ""
  13926. ].join("\n");
  13927. var prefix_fragment = [
  13928. "precision " + _precision + " float;",
  13929. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13930. customDefines,
  13931. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13932. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13933. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13934. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13935. "#define MAX_SHADOWS " + parameters.maxShadows,
  13936. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13937. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13938. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13939. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13940. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13941. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13942. parameters.map ? "#define USE_MAP" : "",
  13943. parameters.envMap ? "#define USE_ENVMAP" : "",
  13944. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13945. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13946. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13947. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13948. parameters.vertexColors ? "#define USE_COLOR" : "",
  13949. parameters.metal ? "#define METAL" : "",
  13950. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13951. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13952. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13953. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13954. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13955. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13956. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13957. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13958. "uniform mat4 viewMatrix;",
  13959. "uniform vec3 cameraPosition;",
  13960. ""
  13961. ].join("\n");
  13962. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13963. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13964. _gl.attachShader( program, glVertexShader );
  13965. _gl.attachShader( program, glFragmentShader );
  13966. _gl.linkProgram( program );
  13967. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13968. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13969. }
  13970. // clean up
  13971. _gl.deleteShader( glFragmentShader );
  13972. _gl.deleteShader( glVertexShader );
  13973. //console.log( prefix_fragment + fragmentShader );
  13974. //console.log( prefix_vertex + vertexShader );
  13975. program.uniforms = {};
  13976. program.attributes = {};
  13977. var identifiers, u, a, i;
  13978. // cache uniform locations
  13979. identifiers = [
  13980. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13981. 'morphTargetInfluences'
  13982. ];
  13983. if ( parameters.useVertexTexture ) {
  13984. identifiers.push( 'boneTexture' );
  13985. } else {
  13986. identifiers.push( 'boneGlobalMatrices' );
  13987. }
  13988. for ( u in uniforms ) {
  13989. identifiers.push( u );
  13990. }
  13991. cacheUniformLocations( program, identifiers );
  13992. // cache attributes locations
  13993. identifiers = [
  13994. "position", "normal", "uv", "uv2", "tangent", "color",
  13995. "skinIndex", "skinWeight", "lineDistance"
  13996. ];
  13997. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13998. identifiers.push( "morphTarget" + i );
  13999. }
  14000. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14001. identifiers.push( "morphNormal" + i );
  14002. }
  14003. for ( a in attributes ) {
  14004. identifiers.push( a );
  14005. }
  14006. cacheAttributeLocations( program, identifiers );
  14007. program.id = _programs_counter ++;
  14008. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14009. _this.info.memory.programs = _programs.length;
  14010. return program;
  14011. };
  14012. // Shader parameters cache
  14013. function cacheUniformLocations ( program, identifiers ) {
  14014. var i, l, id;
  14015. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14016. id = identifiers[ i ];
  14017. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14018. }
  14019. };
  14020. function cacheAttributeLocations ( program, identifiers ) {
  14021. var i, l, id;
  14022. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14023. id = identifiers[ i ];
  14024. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14025. }
  14026. };
  14027. function addLineNumbers ( string ) {
  14028. var chunks = string.split( "\n" );
  14029. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14030. // Chrome reports shader errors on lines
  14031. // starting counting from 1
  14032. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14033. }
  14034. return chunks.join( "\n" );
  14035. };
  14036. function getShader ( type, string ) {
  14037. var shader;
  14038. if ( type === "fragment" ) {
  14039. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14040. } else if ( type === "vertex" ) {
  14041. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14042. }
  14043. _gl.shaderSource( shader, string );
  14044. _gl.compileShader( shader );
  14045. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14046. console.error( _gl.getShaderInfoLog( shader ) );
  14047. console.error( addLineNumbers( string ) );
  14048. return null;
  14049. }
  14050. return shader;
  14051. };
  14052. // Textures
  14053. function isPowerOfTwo ( value ) {
  14054. return ( value & ( value - 1 ) ) === 0;
  14055. };
  14056. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14057. if ( isImagePowerOfTwo ) {
  14058. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14059. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14060. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14061. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14062. } else {
  14063. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14064. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14065. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14066. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14067. }
  14068. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14069. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14070. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14071. texture.__oldAnisotropy = texture.anisotropy;
  14072. }
  14073. }
  14074. };
  14075. this.setTexture = function ( texture, slot ) {
  14076. if ( texture.needsUpdate ) {
  14077. if ( ! texture.__webglInit ) {
  14078. texture.__webglInit = true;
  14079. texture.__webglTexture = _gl.createTexture();
  14080. _this.info.memory.textures ++;
  14081. }
  14082. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14083. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14084. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14085. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14086. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14087. var image = texture.image,
  14088. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14089. glFormat = paramThreeToGL( texture.format ),
  14090. glType = paramThreeToGL( texture.type );
  14091. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14092. var mipmap, mipmaps = texture.mipmaps;
  14093. if ( texture instanceof THREE.DataTexture ) {
  14094. // use manually created mipmaps if available
  14095. // if there are no manual mipmaps
  14096. // set 0 level mipmap and then use GL to generate other mipmap levels
  14097. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14098. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14099. mipmap = mipmaps[ i ];
  14100. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14101. }
  14102. texture.generateMipmaps = false;
  14103. } else {
  14104. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14105. }
  14106. } else if ( texture instanceof THREE.CompressedTexture ) {
  14107. // compressed textures can only use manually created mipmaps
  14108. // WebGL can't generate mipmaps for DDS textures
  14109. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14110. mipmap = mipmaps[ i ];
  14111. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14112. }
  14113. } else { // regular Texture (image, video, canvas)
  14114. // use manually created mipmaps if available
  14115. // if there are no manual mipmaps
  14116. // set 0 level mipmap and then use GL to generate other mipmap levels
  14117. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14118. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14119. mipmap = mipmaps[ i ];
  14120. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14121. }
  14122. texture.generateMipmaps = false;
  14123. } else {
  14124. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14125. }
  14126. }
  14127. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14128. texture.needsUpdate = false;
  14129. if ( texture.onUpdate ) texture.onUpdate();
  14130. } else {
  14131. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14132. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14133. }
  14134. };
  14135. function clampToMaxSize ( image, maxSize ) {
  14136. if ( image.width <= maxSize && image.height <= maxSize ) {
  14137. return image;
  14138. }
  14139. // Warning: Scaling through the canvas will only work with images that use
  14140. // premultiplied alpha.
  14141. var maxDimension = Math.max( image.width, image.height );
  14142. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14143. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14144. var canvas = document.createElement( 'canvas' );
  14145. canvas.width = newWidth;
  14146. canvas.height = newHeight;
  14147. var ctx = canvas.getContext( "2d" );
  14148. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14149. return canvas;
  14150. }
  14151. function setCubeTexture ( texture, slot ) {
  14152. if ( texture.image.length === 6 ) {
  14153. if ( texture.needsUpdate ) {
  14154. if ( ! texture.image.__webglTextureCube ) {
  14155. texture.image.__webglTextureCube = _gl.createTexture();
  14156. _this.info.memory.textures ++;
  14157. }
  14158. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14159. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14160. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14161. var isCompressed = texture instanceof THREE.CompressedTexture;
  14162. var cubeImage = [];
  14163. for ( var i = 0; i < 6; i ++ ) {
  14164. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14165. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14166. } else {
  14167. cubeImage[ i ] = texture.image[ i ];
  14168. }
  14169. }
  14170. var image = cubeImage[ 0 ],
  14171. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14172. glFormat = paramThreeToGL( texture.format ),
  14173. glType = paramThreeToGL( texture.type );
  14174. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14175. for ( var i = 0; i < 6; i ++ ) {
  14176. if ( isCompressed ) {
  14177. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14178. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14179. mipmap = mipmaps[ j ];
  14180. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14181. }
  14182. } else {
  14183. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14184. }
  14185. }
  14186. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14187. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14188. }
  14189. texture.needsUpdate = false;
  14190. if ( texture.onUpdate ) texture.onUpdate();
  14191. } else {
  14192. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14193. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14194. }
  14195. }
  14196. };
  14197. function setCubeTextureDynamic ( texture, slot ) {
  14198. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14199. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14200. };
  14201. // Render targets
  14202. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14203. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14204. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14205. };
  14206. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14207. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14208. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14209. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14210. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14211. /* For some reason this is not working. Defaulting to RGBA4.
  14212. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14213. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14214. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14215. */
  14216. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14217. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14218. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14219. } else {
  14220. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14221. }
  14222. };
  14223. this.setRenderTarget = function ( renderTarget ) {
  14224. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14225. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14226. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14227. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14228. renderTarget.__webglTexture = _gl.createTexture();
  14229. _this.info.memory.textures ++;
  14230. // Setup texture, create render and frame buffers
  14231. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14232. glFormat = paramThreeToGL( renderTarget.format ),
  14233. glType = paramThreeToGL( renderTarget.type );
  14234. if ( isCube ) {
  14235. renderTarget.__webglFramebuffer = [];
  14236. renderTarget.__webglRenderbuffer = [];
  14237. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14238. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14239. for ( var i = 0; i < 6; i ++ ) {
  14240. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14241. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14242. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14243. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14244. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14245. }
  14246. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14247. } else {
  14248. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14249. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14250. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14251. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14252. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14253. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14254. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14255. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14256. }
  14257. // Release everything
  14258. if ( isCube ) {
  14259. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14260. } else {
  14261. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14262. }
  14263. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14264. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14265. }
  14266. var framebuffer, width, height, vx, vy;
  14267. if ( renderTarget ) {
  14268. if ( isCube ) {
  14269. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14270. } else {
  14271. framebuffer = renderTarget.__webglFramebuffer;
  14272. }
  14273. width = renderTarget.width;
  14274. height = renderTarget.height;
  14275. vx = 0;
  14276. vy = 0;
  14277. } else {
  14278. framebuffer = null;
  14279. width = _viewportWidth;
  14280. height = _viewportHeight;
  14281. vx = _viewportX;
  14282. vy = _viewportY;
  14283. }
  14284. if ( framebuffer !== _currentFramebuffer ) {
  14285. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14286. _gl.viewport( vx, vy, width, height );
  14287. _currentFramebuffer = framebuffer;
  14288. }
  14289. _currentWidth = width;
  14290. _currentHeight = height;
  14291. };
  14292. function updateRenderTargetMipmap ( renderTarget ) {
  14293. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14294. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14295. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14296. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14297. } else {
  14298. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14299. _gl.generateMipmap( _gl.TEXTURE_2D );
  14300. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14301. }
  14302. };
  14303. // Fallback filters for non-power-of-2 textures
  14304. function filterFallback ( f ) {
  14305. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14306. return _gl.NEAREST;
  14307. }
  14308. return _gl.LINEAR;
  14309. };
  14310. // Map three.js constants to WebGL constants
  14311. function paramThreeToGL ( p ) {
  14312. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14313. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14314. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14315. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14316. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14317. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14318. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14319. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14320. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14321. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14322. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14323. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14324. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14325. if ( p === THREE.ByteType ) return _gl.BYTE;
  14326. if ( p === THREE.ShortType ) return _gl.SHORT;
  14327. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14328. if ( p === THREE.IntType ) return _gl.INT;
  14329. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14330. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14331. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14332. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14333. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14334. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14335. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14336. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14337. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14338. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14339. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14340. if ( p === THREE.OneFactor ) return _gl.ONE;
  14341. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14342. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14343. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14344. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14345. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14346. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14347. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14348. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14349. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14350. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14351. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14352. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14353. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14354. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14355. }
  14356. return 0;
  14357. };
  14358. // Allocations
  14359. function allocateBones ( object ) {
  14360. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14361. return 1024;
  14362. } else {
  14363. // default for when object is not specified
  14364. // ( for example when prebuilding shader
  14365. // to be used with multiple objects )
  14366. //
  14367. // - leave some extra space for other uniforms
  14368. // - limit here is ANGLE's 254 max uniform vectors
  14369. // (up to 54 should be safe)
  14370. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14371. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14372. var maxBones = nVertexMatrices;
  14373. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14374. maxBones = Math.min( object.bones.length, maxBones );
  14375. if ( maxBones < object.bones.length ) {
  14376. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14377. }
  14378. }
  14379. return maxBones;
  14380. }
  14381. };
  14382. function allocateLights ( lights ) {
  14383. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14384. dirLights = pointLights = spotLights = hemiLights = 0;
  14385. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14386. light = lights[ l ];
  14387. if ( light.onlyShadow ) continue;
  14388. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14389. if ( light instanceof THREE.PointLight ) pointLights ++;
  14390. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14391. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14392. }
  14393. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14394. };
  14395. function allocateShadows ( lights ) {
  14396. var l, ll, light, maxShadows = 0;
  14397. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14398. light = lights[ l ];
  14399. if ( ! light.castShadow ) continue;
  14400. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14401. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14402. }
  14403. return maxShadows;
  14404. };
  14405. // Initialization
  14406. function initGL () {
  14407. try {
  14408. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  14409. throw 'Error creating WebGL context.';
  14410. }
  14411. } catch ( error ) {
  14412. console.error( error );
  14413. }
  14414. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  14415. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  14416. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  14417. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  14418. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14419. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  14420. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  14421. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14422. if ( ! _glExtensionTextureFloat ) {
  14423. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  14424. }
  14425. if ( ! _glExtensionStandardDerivatives ) {
  14426. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  14427. }
  14428. if ( ! _glExtensionTextureFilterAnisotropic ) {
  14429. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  14430. }
  14431. if ( ! _glExtensionCompressedTextureS3TC ) {
  14432. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  14433. }
  14434. };
  14435. function setDefaultGLState () {
  14436. _gl.clearColor( 0, 0, 0, 1 );
  14437. _gl.clearDepth( 1 );
  14438. _gl.clearStencil( 0 );
  14439. _gl.enable( _gl.DEPTH_TEST );
  14440. _gl.depthFunc( _gl.LEQUAL );
  14441. _gl.frontFace( _gl.CCW );
  14442. _gl.cullFace( _gl.BACK );
  14443. _gl.enable( _gl.CULL_FACE );
  14444. _gl.enable( _gl.BLEND );
  14445. _gl.blendEquation( _gl.FUNC_ADD );
  14446. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  14447. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14448. };
  14449. // default plugins (order is important)
  14450. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  14451. this.addPrePlugin( this.shadowMapPlugin );
  14452. this.addPostPlugin( new THREE.SpritePlugin() );
  14453. this.addPostPlugin( new THREE.LensFlarePlugin() );
  14454. };
  14455. /**
  14456. * @author szimek / https://github.com/szimek/
  14457. * @author alteredq / http://alteredqualia.com/
  14458. */
  14459. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14460. this.width = width;
  14461. this.height = height;
  14462. options = options || {};
  14463. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14464. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14465. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14466. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14467. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14468. this.offset = new THREE.Vector2( 0, 0 );
  14469. this.repeat = new THREE.Vector2( 1, 1 );
  14470. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14471. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14472. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14473. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14474. this.generateMipmaps = true;
  14475. };
  14476. THREE.WebGLRenderTarget.prototype.clone = function() {
  14477. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14478. tmp.wrapS = this.wrapS;
  14479. tmp.wrapT = this.wrapT;
  14480. tmp.magFilter = this.magFilter;
  14481. tmp.minFilter = this.minFilter;
  14482. tmp.anisotropy = this.anisotropy;
  14483. tmp.offset.copy( this.offset );
  14484. tmp.repeat.copy( this.repeat );
  14485. tmp.format = this.format;
  14486. tmp.type = this.type;
  14487. tmp.depthBuffer = this.depthBuffer;
  14488. tmp.stencilBuffer = this.stencilBuffer;
  14489. tmp.generateMipmaps = this.generateMipmaps;
  14490. return tmp;
  14491. };
  14492. /**
  14493. * @author alteredq / http://alteredqualia.com
  14494. */
  14495. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14496. THREE.WebGLRenderTarget.call( this, width, height, options );
  14497. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14498. };
  14499. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14500. /**
  14501. * @author mrdoob / http://mrdoob.com/
  14502. */
  14503. THREE.RenderableVertex = function () {
  14504. this.positionWorld = new THREE.Vector3();
  14505. this.positionScreen = new THREE.Vector4();
  14506. this.visible = true;
  14507. };
  14508. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  14509. this.positionWorld.copy( vertex.positionWorld );
  14510. this.positionScreen.copy( vertex.positionScreen );
  14511. }
  14512. /**
  14513. * @author mrdoob / http://mrdoob.com/
  14514. */
  14515. THREE.RenderableFace3 = function () {
  14516. this.v1 = new THREE.RenderableVertex();
  14517. this.v2 = new THREE.RenderableVertex();
  14518. this.v3 = new THREE.RenderableVertex();
  14519. this.centroidWorld = new THREE.Vector3();
  14520. this.centroidScreen = new THREE.Vector3();
  14521. this.normalWorld = new THREE.Vector3();
  14522. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14523. this.vertexNormalsLength = 0;
  14524. this.color = null;
  14525. this.material = null;
  14526. this.uvs = [[]];
  14527. this.z = null;
  14528. };
  14529. /**
  14530. * @author mrdoob / http://mrdoob.com/
  14531. */
  14532. THREE.RenderableFace4 = function () {
  14533. this.v1 = new THREE.RenderableVertex();
  14534. this.v2 = new THREE.RenderableVertex();
  14535. this.v3 = new THREE.RenderableVertex();
  14536. this.v4 = new THREE.RenderableVertex();
  14537. this.centroidWorld = new THREE.Vector3();
  14538. this.centroidScreen = new THREE.Vector3();
  14539. this.normalWorld = new THREE.Vector3();
  14540. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14541. this.vertexNormalsLength = 0;
  14542. this.color = null;
  14543. this.material = null;
  14544. this.uvs = [[]];
  14545. this.z = null;
  14546. };
  14547. /**
  14548. * @author mrdoob / http://mrdoob.com/
  14549. */
  14550. THREE.RenderableObject = function () {
  14551. this.object = null;
  14552. this.z = null;
  14553. };
  14554. /**
  14555. * @author mrdoob / http://mrdoob.com/
  14556. */
  14557. THREE.RenderableParticle = function () {
  14558. this.object = null;
  14559. this.x = null;
  14560. this.y = null;
  14561. this.z = null;
  14562. this.rotation = null;
  14563. this.scale = new THREE.Vector2();
  14564. this.material = null;
  14565. };
  14566. /**
  14567. * @author mrdoob / http://mrdoob.com/
  14568. */
  14569. THREE.RenderableLine = function () {
  14570. this.z = null;
  14571. this.v1 = new THREE.RenderableVertex();
  14572. this.v2 = new THREE.RenderableVertex();
  14573. this.material = null;
  14574. };
  14575. /**
  14576. * @author alteredq / http://alteredqualia.com/
  14577. */
  14578. THREE.ColorUtils = {
  14579. adjustHSV : function ( color, h, s, v ) {
  14580. var hsv = THREE.ColorUtils.__hsv;
  14581. color.getHSV( hsv );
  14582. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  14583. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  14584. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  14585. color.setHSV( hsv.h, hsv.s, hsv.v );
  14586. }
  14587. };
  14588. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  14589. * @author mrdoob / http://mrdoob.com/
  14590. * @author alteredq / http://alteredqualia.com/
  14591. */
  14592. THREE.GeometryUtils = {
  14593. // Merge two geometries or geometry and geometry from object (using object's transform)
  14594. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  14595. var matrix, matrixRotation,
  14596. vertexOffset = geometry1.vertices.length,
  14597. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  14598. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  14599. vertices1 = geometry1.vertices,
  14600. vertices2 = geometry2.vertices,
  14601. faces1 = geometry1.faces,
  14602. faces2 = geometry2.faces,
  14603. uvs1 = geometry1.faceVertexUvs[ 0 ],
  14604. uvs2 = geometry2.faceVertexUvs[ 0 ];
  14605. if ( object2 instanceof THREE.Mesh ) {
  14606. object2.matrixAutoUpdate && object2.updateMatrix();
  14607. matrix = object2.matrix;
  14608. matrixRotation = new THREE.Matrix4();
  14609. matrixRotation.extractRotation( matrix, object2.scale );
  14610. }
  14611. // vertices
  14612. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  14613. var vertex = vertices2[ i ];
  14614. var vertexCopy = vertex.clone();
  14615. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  14616. vertices1.push( vertexCopy );
  14617. }
  14618. // faces
  14619. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  14620. var face = faces2[ i ], faceCopy, normal, color,
  14621. faceVertexNormals = face.vertexNormals,
  14622. faceVertexColors = face.vertexColors;
  14623. if ( face instanceof THREE.Face3 ) {
  14624. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  14625. } else if ( face instanceof THREE.Face4 ) {
  14626. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  14627. }
  14628. faceCopy.normal.copy( face.normal );
  14629. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  14630. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  14631. normal = faceVertexNormals[ j ].clone();
  14632. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  14633. faceCopy.vertexNormals.push( normal );
  14634. }
  14635. faceCopy.color.copy( face.color );
  14636. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  14637. color = faceVertexColors[ j ];
  14638. faceCopy.vertexColors.push( color.clone() );
  14639. }
  14640. faceCopy.materialIndex = face.materialIndex;
  14641. faceCopy.centroid.copy( face.centroid );
  14642. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  14643. faces1.push( faceCopy );
  14644. }
  14645. // uvs
  14646. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  14647. var uv = uvs2[ i ], uvCopy = [];
  14648. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  14649. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  14650. }
  14651. uvs1.push( uvCopy );
  14652. }
  14653. },
  14654. removeMaterials: function ( geometry, materialIndexArray ) {
  14655. var materialIndexMap = {};
  14656. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  14657. materialIndexMap[ materialIndexArray[i] ] = true;
  14658. }
  14659. var face, newFaces = [];
  14660. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14661. face = geometry.faces[ i ];
  14662. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  14663. }
  14664. geometry.faces = newFaces;
  14665. },
  14666. // Get random point in triangle (via barycentric coordinates)
  14667. // (uniform distribution)
  14668. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  14669. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  14670. var a, b, c,
  14671. point = new THREE.Vector3(),
  14672. tmp = THREE.GeometryUtils.__v1;
  14673. a = THREE.GeometryUtils.random();
  14674. b = THREE.GeometryUtils.random();
  14675. if ( ( a + b ) > 1 ) {
  14676. a = 1 - a;
  14677. b = 1 - b;
  14678. }
  14679. c = 1 - a - b;
  14680. point.copy( vectorA );
  14681. point.multiplyScalar( a );
  14682. tmp.copy( vectorB );
  14683. tmp.multiplyScalar( b );
  14684. point.addSelf( tmp );
  14685. tmp.copy( vectorC );
  14686. tmp.multiplyScalar( c );
  14687. point.addSelf( tmp );
  14688. return point;
  14689. },
  14690. // Get random point in face (triangle / quad)
  14691. // (uniform distribution)
  14692. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  14693. var vA, vB, vC, vD;
  14694. if ( face instanceof THREE.Face3 ) {
  14695. vA = geometry.vertices[ face.a ];
  14696. vB = geometry.vertices[ face.b ];
  14697. vC = geometry.vertices[ face.c ];
  14698. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  14699. } else if ( face instanceof THREE.Face4 ) {
  14700. vA = geometry.vertices[ face.a ];
  14701. vB = geometry.vertices[ face.b ];
  14702. vC = geometry.vertices[ face.c ];
  14703. vD = geometry.vertices[ face.d ];
  14704. var area1, area2;
  14705. if ( useCachedAreas ) {
  14706. if ( face._area1 && face._area2 ) {
  14707. area1 = face._area1;
  14708. area2 = face._area2;
  14709. } else {
  14710. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14711. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14712. face._area1 = area1;
  14713. face._area2 = area2;
  14714. }
  14715. } else {
  14716. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  14717. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14718. }
  14719. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  14720. if ( r < area1 ) {
  14721. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  14722. } else {
  14723. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  14724. }
  14725. }
  14726. },
  14727. // Get uniformly distributed random points in mesh
  14728. // - create array with cumulative sums of face areas
  14729. // - pick random number from 0 to total area
  14730. // - find corresponding place in area array by binary search
  14731. // - get random point in face
  14732. randomPointsInGeometry: function ( geometry, n ) {
  14733. var face, i,
  14734. faces = geometry.faces,
  14735. vertices = geometry.vertices,
  14736. il = faces.length,
  14737. totalArea = 0,
  14738. cumulativeAreas = [],
  14739. vA, vB, vC, vD;
  14740. // precompute face areas
  14741. for ( i = 0; i < il; i ++ ) {
  14742. face = faces[ i ];
  14743. if ( face instanceof THREE.Face3 ) {
  14744. vA = vertices[ face.a ];
  14745. vB = vertices[ face.b ];
  14746. vC = vertices[ face.c ];
  14747. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  14748. } else if ( face instanceof THREE.Face4 ) {
  14749. vA = vertices[ face.a ];
  14750. vB = vertices[ face.b ];
  14751. vC = vertices[ face.c ];
  14752. vD = vertices[ face.d ];
  14753. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14754. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14755. face._area = face._area1 + face._area2;
  14756. }
  14757. totalArea += face._area;
  14758. cumulativeAreas[ i ] = totalArea;
  14759. }
  14760. // binary search cumulative areas array
  14761. function binarySearchIndices( value ) {
  14762. function binarySearch( start, end ) {
  14763. // return closest larger index
  14764. // if exact number is not found
  14765. if ( end < start )
  14766. return start;
  14767. var mid = start + Math.floor( ( end - start ) / 2 );
  14768. if ( cumulativeAreas[ mid ] > value ) {
  14769. return binarySearch( start, mid - 1 );
  14770. } else if ( cumulativeAreas[ mid ] < value ) {
  14771. return binarySearch( mid + 1, end );
  14772. } else {
  14773. return mid;
  14774. }
  14775. }
  14776. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  14777. return result;
  14778. }
  14779. // pick random face weighted by face area
  14780. var r, index,
  14781. result = [];
  14782. var stats = {};
  14783. for ( i = 0; i < n; i ++ ) {
  14784. r = THREE.GeometryUtils.random() * totalArea;
  14785. index = binarySearchIndices( r );
  14786. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  14787. if ( ! stats[ index ] ) {
  14788. stats[ index ] = 1;
  14789. } else {
  14790. stats[ index ] += 1;
  14791. }
  14792. }
  14793. return result;
  14794. },
  14795. // Get triangle area (half of parallelogram)
  14796. // http://mathworld.wolfram.com/TriangleArea.html
  14797. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14798. var tmp1 = THREE.GeometryUtils.__v1,
  14799. tmp2 = THREE.GeometryUtils.__v2;
  14800. tmp1.sub( vectorB, vectorA );
  14801. tmp2.sub( vectorC, vectorA );
  14802. tmp1.crossSelf( tmp2 );
  14803. return 0.5 * tmp1.length();
  14804. },
  14805. // Center geometry so that 0,0,0 is in center of bounding box
  14806. center: function ( geometry ) {
  14807. geometry.computeBoundingBox();
  14808. var bb = geometry.boundingBox;
  14809. var offset = new THREE.Vector3();
  14810. offset.add( bb.min, bb.max );
  14811. offset.multiplyScalar( -0.5 );
  14812. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  14813. geometry.computeBoundingBox();
  14814. return offset;
  14815. },
  14816. // Normalize UVs to be from <0,1>
  14817. // (for now just the first set of UVs)
  14818. normalizeUVs: function ( geometry ) {
  14819. var uvSet = geometry.faceVertexUvs[ 0 ];
  14820. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14821. var uvs = uvSet[ i ];
  14822. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14823. // texture repeat
  14824. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  14825. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  14826. }
  14827. }
  14828. },
  14829. triangulateQuads: function ( geometry ) {
  14830. var i, il, j, jl;
  14831. var faces = [];
  14832. var faceUvs = [];
  14833. var faceVertexUvs = [];
  14834. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14835. faceUvs[ i ] = [];
  14836. }
  14837. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14838. faceVertexUvs[ i ] = [];
  14839. }
  14840. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14841. var face = geometry.faces[ i ];
  14842. if ( face instanceof THREE.Face4 ) {
  14843. var a = face.a;
  14844. var b = face.b;
  14845. var c = face.c;
  14846. var d = face.d;
  14847. var triA = new THREE.Face3();
  14848. var triB = new THREE.Face3();
  14849. triA.color.copy( face.color );
  14850. triB.color.copy( face.color );
  14851. triA.materialIndex = face.materialIndex;
  14852. triB.materialIndex = face.materialIndex;
  14853. triA.a = a;
  14854. triA.b = b;
  14855. triA.c = d;
  14856. triB.a = b;
  14857. triB.b = c;
  14858. triB.c = d;
  14859. if ( face.vertexColors.length === 4 ) {
  14860. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14861. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14862. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14863. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14864. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14865. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14866. }
  14867. faces.push( triA, triB );
  14868. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14869. if ( geometry.faceVertexUvs[ j ].length ) {
  14870. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14871. var uvA = uvs[ 0 ];
  14872. var uvB = uvs[ 1 ];
  14873. var uvC = uvs[ 2 ];
  14874. var uvD = uvs[ 3 ];
  14875. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14876. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14877. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14878. }
  14879. }
  14880. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14881. if ( geometry.faceUvs[ j ].length ) {
  14882. var faceUv = geometry.faceUvs[ j ][ i ];
  14883. faceUvs[ j ].push( faceUv, faceUv );
  14884. }
  14885. }
  14886. } else {
  14887. faces.push( face );
  14888. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14889. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14890. }
  14891. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14892. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14893. }
  14894. }
  14895. }
  14896. geometry.faces = faces;
  14897. geometry.faceUvs = faceUvs;
  14898. geometry.faceVertexUvs = faceVertexUvs;
  14899. geometry.computeCentroids();
  14900. geometry.computeFaceNormals();
  14901. geometry.computeVertexNormals();
  14902. if ( geometry.hasTangents ) geometry.computeTangents();
  14903. },
  14904. // Make all faces use unique vertices
  14905. // so that each face can be separated from others
  14906. explode: function( geometry ) {
  14907. var vertices = [];
  14908. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14909. var n = vertices.length;
  14910. var face = geometry.faces[ i ];
  14911. if ( face instanceof THREE.Face4 ) {
  14912. var a = face.a;
  14913. var b = face.b;
  14914. var c = face.c;
  14915. var d = face.d;
  14916. var va = geometry.vertices[ a ];
  14917. var vb = geometry.vertices[ b ];
  14918. var vc = geometry.vertices[ c ];
  14919. var vd = geometry.vertices[ d ];
  14920. vertices.push( va.clone() );
  14921. vertices.push( vb.clone() );
  14922. vertices.push( vc.clone() );
  14923. vertices.push( vd.clone() );
  14924. face.a = n;
  14925. face.b = n + 1;
  14926. face.c = n + 2;
  14927. face.d = n + 3;
  14928. } else {
  14929. var a = face.a;
  14930. var b = face.b;
  14931. var c = face.c;
  14932. var va = geometry.vertices[ a ];
  14933. var vb = geometry.vertices[ b ];
  14934. var vc = geometry.vertices[ c ];
  14935. vertices.push( va.clone() );
  14936. vertices.push( vb.clone() );
  14937. vertices.push( vc.clone() );
  14938. face.a = n;
  14939. face.b = n + 1;
  14940. face.c = n + 2;
  14941. }
  14942. }
  14943. geometry.vertices = vertices;
  14944. delete geometry.__tmpVertices;
  14945. },
  14946. // Break faces with edges longer than maxEdgeLength
  14947. // - not recursive
  14948. tessellate: function ( geometry, maxEdgeLength ) {
  14949. var i, il, face,
  14950. a, b, c, d,
  14951. va, vb, vc, vd,
  14952. dab, dbc, dac, dcd, dad,
  14953. m, m1, m2,
  14954. vm, vm1, vm2,
  14955. vnm, vnm1, vnm2,
  14956. vcm, vcm1, vcm2,
  14957. triA, triB,
  14958. quadA, quadB,
  14959. edge;
  14960. var faces = [];
  14961. var faceVertexUvs = [];
  14962. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14963. faceVertexUvs[ i ] = [];
  14964. }
  14965. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14966. face = geometry.faces[ i ];
  14967. if ( face instanceof THREE.Face3 ) {
  14968. a = face.a;
  14969. b = face.b;
  14970. c = face.c;
  14971. va = geometry.vertices[ a ];
  14972. vb = geometry.vertices[ b ];
  14973. vc = geometry.vertices[ c ];
  14974. dab = va.distanceTo( vb );
  14975. dbc = vb.distanceTo( vc );
  14976. dac = va.distanceTo( vc );
  14977. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  14978. m = geometry.vertices.length;
  14979. triA = face.clone();
  14980. triB = face.clone();
  14981. if ( dab >= dbc && dab >= dac ) {
  14982. vm = va.clone();
  14983. vm.lerpSelf( vb, 0.5 );
  14984. triA.a = a;
  14985. triA.b = m;
  14986. triA.c = c;
  14987. triB.a = m;
  14988. triB.b = b;
  14989. triB.c = c;
  14990. if ( face.vertexNormals.length === 3 ) {
  14991. vnm = face.vertexNormals[ 0 ].clone();
  14992. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14993. triA.vertexNormals[ 1 ].copy( vnm );
  14994. triB.vertexNormals[ 0 ].copy( vnm );
  14995. }
  14996. if ( face.vertexColors.length === 3 ) {
  14997. vcm = face.vertexColors[ 0 ].clone();
  14998. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14999. triA.vertexColors[ 1 ].copy( vcm );
  15000. triB.vertexColors[ 0 ].copy( vcm );
  15001. }
  15002. edge = 0;
  15003. } else if ( dbc >= dab && dbc >= dac ) {
  15004. vm = vb.clone();
  15005. vm.lerpSelf( vc, 0.5 );
  15006. triA.a = a;
  15007. triA.b = b;
  15008. triA.c = m;
  15009. triB.a = m;
  15010. triB.b = c;
  15011. triB.c = a;
  15012. if ( face.vertexNormals.length === 3 ) {
  15013. vnm = face.vertexNormals[ 1 ].clone();
  15014. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15015. triA.vertexNormals[ 2 ].copy( vnm );
  15016. triB.vertexNormals[ 0 ].copy( vnm );
  15017. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  15018. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  15019. }
  15020. if ( face.vertexColors.length === 3 ) {
  15021. vcm = face.vertexColors[ 1 ].clone();
  15022. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15023. triA.vertexColors[ 2 ].copy( vcm );
  15024. triB.vertexColors[ 0 ].copy( vcm );
  15025. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  15026. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  15027. }
  15028. edge = 1;
  15029. } else {
  15030. vm = va.clone();
  15031. vm.lerpSelf( vc, 0.5 );
  15032. triA.a = a;
  15033. triA.b = b;
  15034. triA.c = m;
  15035. triB.a = m;
  15036. triB.b = b;
  15037. triB.c = c;
  15038. if ( face.vertexNormals.length === 3 ) {
  15039. vnm = face.vertexNormals[ 0 ].clone();
  15040. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15041. triA.vertexNormals[ 2 ].copy( vnm );
  15042. triB.vertexNormals[ 0 ].copy( vnm );
  15043. }
  15044. if ( face.vertexColors.length === 3 ) {
  15045. vcm = face.vertexColors[ 0 ].clone();
  15046. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15047. triA.vertexColors[ 2 ].copy( vcm );
  15048. triB.vertexColors[ 0 ].copy( vcm );
  15049. }
  15050. edge = 2;
  15051. }
  15052. faces.push( triA, triB );
  15053. geometry.vertices.push( vm );
  15054. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  15055. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15056. if ( geometry.faceVertexUvs[ j ].length ) {
  15057. uvs = geometry.faceVertexUvs[ j ][ i ];
  15058. uvA = uvs[ 0 ];
  15059. uvB = uvs[ 1 ];
  15060. uvC = uvs[ 2 ];
  15061. // AB
  15062. if ( edge === 0 ) {
  15063. uvM = uvA.clone();
  15064. uvM.lerpSelf( uvB, 0.5 );
  15065. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  15066. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  15067. // BC
  15068. } else if ( edge === 1 ) {
  15069. uvM = uvB.clone();
  15070. uvM.lerpSelf( uvC, 0.5 );
  15071. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  15072. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  15073. // AC
  15074. } else {
  15075. uvM = uvA.clone();
  15076. uvM.lerpSelf( uvC, 0.5 );
  15077. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  15078. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  15079. }
  15080. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15081. }
  15082. }
  15083. } else {
  15084. faces.push( face );
  15085. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15086. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15087. }
  15088. }
  15089. } else {
  15090. a = face.a;
  15091. b = face.b;
  15092. c = face.c;
  15093. d = face.d;
  15094. va = geometry.vertices[ a ];
  15095. vb = geometry.vertices[ b ];
  15096. vc = geometry.vertices[ c ];
  15097. vd = geometry.vertices[ d ];
  15098. dab = va.distanceTo( vb );
  15099. dbc = vb.distanceTo( vc );
  15100. dcd = vc.distanceTo( vd );
  15101. dad = va.distanceTo( vd );
  15102. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  15103. m1 = geometry.vertices.length;
  15104. m2 = geometry.vertices.length + 1;
  15105. quadA = face.clone();
  15106. quadB = face.clone();
  15107. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  15108. vm1 = va.clone();
  15109. vm1.lerpSelf( vb, 0.5 );
  15110. vm2 = vc.clone();
  15111. vm2.lerpSelf( vd, 0.5 );
  15112. quadA.a = a;
  15113. quadA.b = m1;
  15114. quadA.c = m2;
  15115. quadA.d = d;
  15116. quadB.a = m1;
  15117. quadB.b = b;
  15118. quadB.c = c;
  15119. quadB.d = m2;
  15120. if ( face.vertexNormals.length === 4 ) {
  15121. vnm1 = face.vertexNormals[ 0 ].clone();
  15122. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  15123. vnm2 = face.vertexNormals[ 2 ].clone();
  15124. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  15125. quadA.vertexNormals[ 1 ].copy( vnm1 );
  15126. quadA.vertexNormals[ 2 ].copy( vnm2 );
  15127. quadB.vertexNormals[ 0 ].copy( vnm1 );
  15128. quadB.vertexNormals[ 3 ].copy( vnm2 );
  15129. }
  15130. if ( face.vertexColors.length === 4 ) {
  15131. vcm1 = face.vertexColors[ 0 ].clone();
  15132. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  15133. vcm2 = face.vertexColors[ 2 ].clone();
  15134. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  15135. quadA.vertexColors[ 1 ].copy( vcm1 );
  15136. quadA.vertexColors[ 2 ].copy( vcm2 );
  15137. quadB.vertexColors[ 0 ].copy( vcm1 );
  15138. quadB.vertexColors[ 3 ].copy( vcm2 );
  15139. }
  15140. edge = 0;
  15141. } else {
  15142. vm1 = vb.clone();
  15143. vm1.lerpSelf( vc, 0.5 );
  15144. vm2 = vd.clone();
  15145. vm2.lerpSelf( va, 0.5 );
  15146. quadA.a = a;
  15147. quadA.b = b;
  15148. quadA.c = m1;
  15149. quadA.d = m2;
  15150. quadB.a = m2;
  15151. quadB.b = m1;
  15152. quadB.c = c;
  15153. quadB.d = d;
  15154. if ( face.vertexNormals.length === 4 ) {
  15155. vnm1 = face.vertexNormals[ 1 ].clone();
  15156. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15157. vnm2 = face.vertexNormals[ 3 ].clone();
  15158. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  15159. quadA.vertexNormals[ 2 ].copy( vnm1 );
  15160. quadA.vertexNormals[ 3 ].copy( vnm2 );
  15161. quadB.vertexNormals[ 0 ].copy( vnm2 );
  15162. quadB.vertexNormals[ 1 ].copy( vnm1 );
  15163. }
  15164. if ( face.vertexColors.length === 4 ) {
  15165. vcm1 = face.vertexColors[ 1 ].clone();
  15166. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15167. vcm2 = face.vertexColors[ 3 ].clone();
  15168. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  15169. quadA.vertexColors[ 2 ].copy( vcm1 );
  15170. quadA.vertexColors[ 3 ].copy( vcm2 );
  15171. quadB.vertexColors[ 0 ].copy( vcm2 );
  15172. quadB.vertexColors[ 1 ].copy( vcm1 );
  15173. }
  15174. edge = 1;
  15175. }
  15176. faces.push( quadA, quadB );
  15177. geometry.vertices.push( vm1, vm2 );
  15178. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  15179. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15180. if ( geometry.faceVertexUvs[ j ].length ) {
  15181. uvs = geometry.faceVertexUvs[ j ][ i ];
  15182. uvA = uvs[ 0 ];
  15183. uvB = uvs[ 1 ];
  15184. uvC = uvs[ 2 ];
  15185. uvD = uvs[ 3 ];
  15186. // AB + CD
  15187. if ( edge === 0 ) {
  15188. uvM1 = uvA.clone();
  15189. uvM1.lerpSelf( uvB, 0.5 );
  15190. uvM2 = uvC.clone();
  15191. uvM2.lerpSelf( uvD, 0.5 );
  15192. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  15193. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  15194. // BC + AD
  15195. } else {
  15196. uvM1 = uvB.clone();
  15197. uvM1.lerpSelf( uvC, 0.5 );
  15198. uvM2 = uvD.clone();
  15199. uvM2.lerpSelf( uvA, 0.5 );
  15200. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  15201. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  15202. }
  15203. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  15204. }
  15205. }
  15206. } else {
  15207. faces.push( face );
  15208. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15209. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15210. }
  15211. }
  15212. }
  15213. }
  15214. geometry.faces = faces;
  15215. geometry.faceVertexUvs = faceVertexUvs;
  15216. }
  15217. };
  15218. THREE.GeometryUtils.random = THREE.Math.random16;
  15219. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15220. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15221. /**
  15222. * @author alteredq / http://alteredqualia.com/
  15223. * @author mrdoob / http://mrdoob.com/
  15224. */
  15225. THREE.ImageUtils = {
  15226. crossOrigin: 'anonymous',
  15227. loadTexture: function ( url, mapping, onLoad, onError ) {
  15228. var image = new Image();
  15229. var texture = new THREE.Texture( image, mapping );
  15230. var loader = new THREE.ImageLoader();
  15231. loader.addEventListener( 'load', function ( event ) {
  15232. texture.image = event.content;
  15233. texture.needsUpdate = true;
  15234. if ( onLoad ) onLoad( texture );
  15235. } );
  15236. loader.addEventListener( 'error', function ( event ) {
  15237. if ( onError ) onError( event.message );
  15238. } );
  15239. loader.crossOrigin = this.crossOrigin;
  15240. loader.load( url, image );
  15241. texture.sourceFile = url;
  15242. return texture;
  15243. },
  15244. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15245. var texture = new THREE.CompressedTexture();
  15246. texture.mapping = mapping;
  15247. var request = new XMLHttpRequest();
  15248. request.onload = function () {
  15249. var buffer = request.response;
  15250. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15251. texture.format = dds.format;
  15252. texture.mipmaps = dds.mipmaps;
  15253. texture.image.width = dds.width;
  15254. texture.image.height = dds.height;
  15255. // gl.generateMipmap fails for compressed textures
  15256. // mipmaps must be embedded in the DDS file
  15257. // or texture filters must not use mipmapping
  15258. texture.generateMipmaps = false;
  15259. texture.needsUpdate = true;
  15260. if ( onLoad ) onLoad( texture );
  15261. }
  15262. request.onerror = onError;
  15263. request.open( 'GET', url, true );
  15264. request.responseType = "arraybuffer";
  15265. request.send( null );
  15266. return texture;
  15267. },
  15268. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15269. var images = [];
  15270. images.loadCount = 0;
  15271. var texture = new THREE.Texture();
  15272. texture.image = images;
  15273. if ( mapping !== undefined ) texture.mapping = mapping;
  15274. // no flipping needed for cube textures
  15275. texture.flipY = false;
  15276. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15277. var cubeImage = new Image();
  15278. images[ i ] = cubeImage;
  15279. cubeImage.onload = function () {
  15280. images.loadCount += 1;
  15281. if ( images.loadCount === 6 ) {
  15282. texture.needsUpdate = true;
  15283. if ( onLoad ) onLoad( texture );
  15284. }
  15285. };
  15286. cubeImage.onerror = onError;
  15287. cubeImage.crossOrigin = this.crossOrigin;
  15288. cubeImage.src = array[ i ];
  15289. }
  15290. return texture;
  15291. },
  15292. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15293. var images = [];
  15294. images.loadCount = 0;
  15295. var texture = new THREE.CompressedTexture();
  15296. texture.image = images;
  15297. if ( mapping !== undefined ) texture.mapping = mapping;
  15298. // no flipping for cube textures
  15299. // (also flipping doesn't work for compressed textures )
  15300. texture.flipY = false;
  15301. // can't generate mipmaps for compressed textures
  15302. // mips must be embedded in DDS files
  15303. texture.generateMipmaps = false;
  15304. var generateCubeFaceCallback = function ( rq, img ) {
  15305. return function () {
  15306. var buffer = rq.response;
  15307. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15308. img.format = dds.format;
  15309. img.mipmaps = dds.mipmaps;
  15310. img.width = dds.width;
  15311. img.height = dds.height;
  15312. images.loadCount += 1;
  15313. if ( images.loadCount === 6 ) {
  15314. texture.format = dds.format;
  15315. texture.needsUpdate = true;
  15316. if ( onLoad ) onLoad( texture );
  15317. }
  15318. }
  15319. }
  15320. // compressed cubemap textures as 6 separate DDS files
  15321. if ( array instanceof Array ) {
  15322. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15323. var cubeImage = {};
  15324. images[ i ] = cubeImage;
  15325. var request = new XMLHttpRequest();
  15326. request.onload = generateCubeFaceCallback( request, cubeImage );
  15327. request.onerror = onError;
  15328. var url = array[ i ];
  15329. request.open( 'GET', url, true );
  15330. request.responseType = "arraybuffer";
  15331. request.send( null );
  15332. }
  15333. // compressed cubemap texture stored in a single DDS file
  15334. } else {
  15335. var url = array;
  15336. var request = new XMLHttpRequest();
  15337. request.onload = function( ) {
  15338. var buffer = request.response;
  15339. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15340. if ( dds.isCubemap ) {
  15341. var faces = dds.mipmaps.length / dds.mipmapCount;
  15342. for ( var f = 0; f < faces; f ++ ) {
  15343. images[ f ] = { mipmaps : [] };
  15344. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15345. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15346. images[ f ].format = dds.format;
  15347. images[ f ].width = dds.width;
  15348. images[ f ].height = dds.height;
  15349. }
  15350. }
  15351. texture.format = dds.format;
  15352. texture.needsUpdate = true;
  15353. if ( onLoad ) onLoad( texture );
  15354. }
  15355. }
  15356. request.onerror = onError;
  15357. request.open( 'GET', url, true );
  15358. request.responseType = "arraybuffer";
  15359. request.send( null );
  15360. }
  15361. return texture;
  15362. },
  15363. parseDDS: function ( buffer, loadMipmaps ) {
  15364. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15365. // Adapted from @toji's DDS utils
  15366. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15367. // All values and structures referenced from:
  15368. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15369. var DDS_MAGIC = 0x20534444;
  15370. var DDSD_CAPS = 0x1,
  15371. DDSD_HEIGHT = 0x2,
  15372. DDSD_WIDTH = 0x4,
  15373. DDSD_PITCH = 0x8,
  15374. DDSD_PIXELFORMAT = 0x1000,
  15375. DDSD_MIPMAPCOUNT = 0x20000,
  15376. DDSD_LINEARSIZE = 0x80000,
  15377. DDSD_DEPTH = 0x800000;
  15378. var DDSCAPS_COMPLEX = 0x8,
  15379. DDSCAPS_MIPMAP = 0x400000,
  15380. DDSCAPS_TEXTURE = 0x1000;
  15381. var DDSCAPS2_CUBEMAP = 0x200,
  15382. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15383. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15384. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15385. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15386. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15387. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15388. DDSCAPS2_VOLUME = 0x200000;
  15389. var DDPF_ALPHAPIXELS = 0x1,
  15390. DDPF_ALPHA = 0x2,
  15391. DDPF_FOURCC = 0x4,
  15392. DDPF_RGB = 0x40,
  15393. DDPF_YUV = 0x200,
  15394. DDPF_LUMINANCE = 0x20000;
  15395. function fourCCToInt32( value ) {
  15396. return value.charCodeAt(0) +
  15397. (value.charCodeAt(1) << 8) +
  15398. (value.charCodeAt(2) << 16) +
  15399. (value.charCodeAt(3) << 24);
  15400. }
  15401. function int32ToFourCC( value ) {
  15402. return String.fromCharCode(
  15403. value & 0xff,
  15404. (value >> 8) & 0xff,
  15405. (value >> 16) & 0xff,
  15406. (value >> 24) & 0xff
  15407. );
  15408. }
  15409. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15410. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15411. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15412. var headerLengthInt = 31; // The header length in 32 bit ints
  15413. // Offsets into the header array
  15414. var off_magic = 0;
  15415. var off_size = 1;
  15416. var off_flags = 2;
  15417. var off_height = 3;
  15418. var off_width = 4;
  15419. var off_mipmapCount = 7;
  15420. var off_pfFlags = 20;
  15421. var off_pfFourCC = 21;
  15422. var off_caps = 27;
  15423. var off_caps2 = 28;
  15424. var off_caps3 = 29;
  15425. var off_caps4 = 30;
  15426. // Parse header
  15427. var header = new Int32Array( buffer, 0, headerLengthInt );
  15428. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15429. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15430. return dds;
  15431. }
  15432. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15433. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15434. return dds;
  15435. }
  15436. var blockBytes;
  15437. var fourCC = header[ off_pfFourCC ];
  15438. switch ( fourCC ) {
  15439. case FOURCC_DXT1:
  15440. blockBytes = 8;
  15441. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15442. break;
  15443. case FOURCC_DXT3:
  15444. blockBytes = 16;
  15445. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15446. break;
  15447. case FOURCC_DXT5:
  15448. blockBytes = 16;
  15449. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15450. break;
  15451. default:
  15452. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15453. return dds;
  15454. }
  15455. dds.mipmapCount = 1;
  15456. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15457. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15458. }
  15459. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15460. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15461. dds.width = header[ off_width ];
  15462. dds.height = header[ off_height ];
  15463. var dataOffset = header[ off_size ] + 4;
  15464. // Extract mipmaps buffers
  15465. var width = dds.width;
  15466. var height = dds.height;
  15467. var faces = dds.isCubemap ? 6 : 1;
  15468. for ( var face = 0; face < faces; face ++ ) {
  15469. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15470. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15471. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15472. var mipmap = { "data": byteArray, "width": width, "height": height };
  15473. dds.mipmaps.push( mipmap );
  15474. dataOffset += dataLength;
  15475. width = Math.max( width * 0.5, 1 );
  15476. height = Math.max( height * 0.5, 1 );
  15477. }
  15478. width = dds.width;
  15479. height = dds.height;
  15480. }
  15481. return dds;
  15482. },
  15483. getNormalMap: function ( image, depth ) {
  15484. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15485. var cross = function ( a, b ) {
  15486. 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 ] ];
  15487. }
  15488. var subtract = function ( a, b ) {
  15489. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15490. }
  15491. var normalize = function ( a ) {
  15492. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15493. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15494. }
  15495. depth = depth | 1;
  15496. var width = image.width;
  15497. var height = image.height;
  15498. var canvas = document.createElement( 'canvas' );
  15499. canvas.width = width;
  15500. canvas.height = height;
  15501. var context = canvas.getContext( '2d' );
  15502. context.drawImage( image, 0, 0 );
  15503. var data = context.getImageData( 0, 0, width, height ).data;
  15504. var imageData = context.createImageData( width, height );
  15505. var output = imageData.data;
  15506. for ( var x = 0; x < width; x ++ ) {
  15507. for ( var y = 0; y < height; y ++ ) {
  15508. var ly = y - 1 < 0 ? 0 : y - 1;
  15509. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15510. var lx = x - 1 < 0 ? 0 : x - 1;
  15511. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15512. var points = [];
  15513. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15514. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15515. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15516. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15517. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15518. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15519. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15520. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15521. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15522. var normals = [];
  15523. var num_points = points.length;
  15524. for ( var i = 0; i < num_points; i ++ ) {
  15525. var v1 = points[ i ];
  15526. var v2 = points[ ( i + 1 ) % num_points ];
  15527. v1 = subtract( v1, origin );
  15528. v2 = subtract( v2, origin );
  15529. normals.push( normalize( cross( v1, v2 ) ) );
  15530. }
  15531. var normal = [ 0, 0, 0 ];
  15532. for ( var i = 0; i < normals.length; i ++ ) {
  15533. normal[ 0 ] += normals[ i ][ 0 ];
  15534. normal[ 1 ] += normals[ i ][ 1 ];
  15535. normal[ 2 ] += normals[ i ][ 2 ];
  15536. }
  15537. normal[ 0 ] /= normals.length;
  15538. normal[ 1 ] /= normals.length;
  15539. normal[ 2 ] /= normals.length;
  15540. var idx = ( y * width + x ) * 4;
  15541. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15542. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15543. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15544. output[ idx + 3 ] = 255;
  15545. }
  15546. }
  15547. context.putImageData( imageData, 0, 0 );
  15548. return canvas;
  15549. },
  15550. generateDataTexture: function ( width, height, color ) {
  15551. var size = width * height;
  15552. var data = new Uint8Array( 3 * size );
  15553. var r = Math.floor( color.r * 255 );
  15554. var g = Math.floor( color.g * 255 );
  15555. var b = Math.floor( color.b * 255 );
  15556. for ( var i = 0; i < size; i ++ ) {
  15557. data[ i * 3 ] = r;
  15558. data[ i * 3 + 1 ] = g;
  15559. data[ i * 3 + 2 ] = b;
  15560. }
  15561. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15562. texture.needsUpdate = true;
  15563. return texture;
  15564. }
  15565. };
  15566. /**
  15567. * @author alteredq / http://alteredqualia.com/
  15568. */
  15569. THREE.SceneUtils = {
  15570. createMultiMaterialObject: function ( geometry, materials ) {
  15571. var group = new THREE.Object3D();
  15572. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15573. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15574. }
  15575. return group;
  15576. },
  15577. detach : function ( child, parent, scene ) {
  15578. child.applyMatrix( parent.matrixWorld );
  15579. parent.remove( child );
  15580. scene.add( child );
  15581. },
  15582. attach: function ( child, scene, parent ) {
  15583. var matrixWorldInverse = new THREE.Matrix4();
  15584. matrixWorldInverse.getInverse( parent.matrixWorld );
  15585. child.applyMatrix( matrixWorldInverse );
  15586. scene.remove( child );
  15587. parent.add( child );
  15588. }
  15589. };
  15590. /**
  15591. * @author alteredq / http://alteredqualia.com/
  15592. * @author mrdoob / http://mrdoob.com/
  15593. *
  15594. * ShaderUtils currently contains:
  15595. *
  15596. * fresnel
  15597. * normal
  15598. * cube
  15599. *
  15600. */
  15601. THREE.ShaderUtils = {
  15602. lib: {
  15603. /* -------------------------------------------------------------------------
  15604. // Fresnel shader
  15605. // - based on Nvidia Cg tutorial
  15606. ------------------------------------------------------------------------- */
  15607. 'fresnel': {
  15608. uniforms: {
  15609. "mRefractionRatio": { type: "f", value: 1.02 },
  15610. "mFresnelBias": { type: "f", value: 0.1 },
  15611. "mFresnelPower": { type: "f", value: 2.0 },
  15612. "mFresnelScale": { type: "f", value: 1.0 },
  15613. "tCube": { type: "t", value: null }
  15614. },
  15615. fragmentShader: [
  15616. "uniform samplerCube tCube;",
  15617. "varying vec3 vReflect;",
  15618. "varying vec3 vRefract[3];",
  15619. "varying float vReflectionFactor;",
  15620. "void main() {",
  15621. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15622. "vec4 refractedColor = vec4( 1.0 );",
  15623. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  15624. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  15625. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  15626. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  15627. "}"
  15628. ].join("\n"),
  15629. vertexShader: [
  15630. "uniform float mRefractionRatio;",
  15631. "uniform float mFresnelBias;",
  15632. "uniform float mFresnelScale;",
  15633. "uniform float mFresnelPower;",
  15634. "varying vec3 vReflect;",
  15635. "varying vec3 vRefract[3];",
  15636. "varying float vReflectionFactor;",
  15637. "void main() {",
  15638. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  15639. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15640. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  15641. "vec3 I = worldPosition.xyz - cameraPosition;",
  15642. "vReflect = reflect( I, worldNormal );",
  15643. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  15644. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  15645. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  15646. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  15647. "gl_Position = projectionMatrix * mvPosition;",
  15648. "}"
  15649. ].join("\n")
  15650. },
  15651. /* -------------------------------------------------------------------------
  15652. // Normal map shader
  15653. // - Blinn-Phong
  15654. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  15655. // - point and directional lights (use with "lights: true" material option)
  15656. ------------------------------------------------------------------------- */
  15657. 'normal' : {
  15658. uniforms: THREE.UniformsUtils.merge( [
  15659. THREE.UniformsLib[ "fog" ],
  15660. THREE.UniformsLib[ "lights" ],
  15661. THREE.UniformsLib[ "shadowmap" ],
  15662. {
  15663. "enableAO" : { type: "i", value: 0 },
  15664. "enableDiffuse" : { type: "i", value: 0 },
  15665. "enableSpecular" : { type: "i", value: 0 },
  15666. "enableReflection": { type: "i", value: 0 },
  15667. "enableDisplacement": { type: "i", value: 0 },
  15668. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  15669. "tDiffuse" : { type: "t", value: null },
  15670. "tCube" : { type: "t", value: null },
  15671. "tNormal" : { type: "t", value: null },
  15672. "tSpecular" : { type: "t", value: null },
  15673. "tAO" : { type: "t", value: null },
  15674. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15675. "uDisplacementBias": { type: "f", value: 0.0 },
  15676. "uDisplacementScale": { type: "f", value: 1.0 },
  15677. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15678. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  15679. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15680. "uShininess": { type: "f", value: 30 },
  15681. "uOpacity": { type: "f", value: 1 },
  15682. "useRefract": { type: "i", value: 0 },
  15683. "uRefractionRatio": { type: "f", value: 0.98 },
  15684. "uReflectivity": { type: "f", value: 0.5 },
  15685. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  15686. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15687. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  15688. }
  15689. ] ),
  15690. fragmentShader: [
  15691. "uniform vec3 uAmbientColor;",
  15692. "uniform vec3 uDiffuseColor;",
  15693. "uniform vec3 uSpecularColor;",
  15694. "uniform float uShininess;",
  15695. "uniform float uOpacity;",
  15696. "uniform bool enableDiffuse;",
  15697. "uniform bool enableSpecular;",
  15698. "uniform bool enableAO;",
  15699. "uniform bool enableReflection;",
  15700. "uniform sampler2D tDiffuse;",
  15701. "uniform sampler2D tNormal;",
  15702. "uniform sampler2D tSpecular;",
  15703. "uniform sampler2D tAO;",
  15704. "uniform samplerCube tCube;",
  15705. "uniform vec2 uNormalScale;",
  15706. "uniform bool useRefract;",
  15707. "uniform float uRefractionRatio;",
  15708. "uniform float uReflectivity;",
  15709. "varying vec3 vTangent;",
  15710. "varying vec3 vBinormal;",
  15711. "varying vec3 vNormal;",
  15712. "varying vec2 vUv;",
  15713. "uniform vec3 ambientLightColor;",
  15714. "#if MAX_DIR_LIGHTS > 0",
  15715. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  15716. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  15717. "#endif",
  15718. "#if MAX_HEMI_LIGHTS > 0",
  15719. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  15720. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  15721. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  15722. "#endif",
  15723. "#if MAX_POINT_LIGHTS > 0",
  15724. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  15725. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  15726. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  15727. "#endif",
  15728. "#if MAX_SPOT_LIGHTS > 0",
  15729. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  15730. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  15731. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  15732. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  15733. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  15734. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  15735. "#endif",
  15736. "#ifdef WRAP_AROUND",
  15737. "uniform vec3 wrapRGB;",
  15738. "#endif",
  15739. "varying vec3 vWorldPosition;",
  15740. "varying vec3 vViewPosition;",
  15741. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  15742. THREE.ShaderChunk[ "fog_pars_fragment" ],
  15743. "void main() {",
  15744. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  15745. "vec3 specularTex = vec3( 1.0 );",
  15746. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  15747. "normalTex.xy *= uNormalScale;",
  15748. "normalTex = normalize( normalTex );",
  15749. "if( enableDiffuse ) {",
  15750. "#ifdef GAMMA_INPUT",
  15751. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  15752. "texelColor.xyz *= texelColor.xyz;",
  15753. "gl_FragColor = gl_FragColor * texelColor;",
  15754. "#else",
  15755. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  15756. "#endif",
  15757. "}",
  15758. "if( enableAO ) {",
  15759. "#ifdef GAMMA_INPUT",
  15760. "vec4 aoColor = texture2D( tAO, vUv );",
  15761. "aoColor.xyz *= aoColor.xyz;",
  15762. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  15763. "#else",
  15764. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  15765. "#endif",
  15766. "}",
  15767. "if( enableSpecular )",
  15768. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  15769. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  15770. "vec3 finalNormal = tsb * normalTex;",
  15771. "#ifdef FLIP_SIDED",
  15772. "finalNormal = -finalNormal;",
  15773. "#endif",
  15774. "vec3 normal = normalize( finalNormal );",
  15775. "vec3 viewPosition = normalize( vViewPosition );",
  15776. // point lights
  15777. "#if MAX_POINT_LIGHTS > 0",
  15778. "vec3 pointDiffuse = vec3( 0.0 );",
  15779. "vec3 pointSpecular = vec3( 0.0 );",
  15780. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  15781. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  15782. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  15783. "float pointDistance = 1.0;",
  15784. "if ( pointLightDistance[ i ] > 0.0 )",
  15785. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  15786. "pointVector = normalize( pointVector );",
  15787. // diffuse
  15788. "#ifdef WRAP_AROUND",
  15789. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  15790. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  15791. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  15792. "#else",
  15793. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  15794. "#endif",
  15795. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  15796. // specular
  15797. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  15798. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  15799. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  15800. "#ifdef PHYSICALLY_BASED_SHADING",
  15801. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15802. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15803. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  15804. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  15805. "#else",
  15806. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  15807. "#endif",
  15808. "}",
  15809. "#endif",
  15810. // spot lights
  15811. "#if MAX_SPOT_LIGHTS > 0",
  15812. "vec3 spotDiffuse = vec3( 0.0 );",
  15813. "vec3 spotSpecular = vec3( 0.0 );",
  15814. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  15815. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  15816. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  15817. "float spotDistance = 1.0;",
  15818. "if ( spotLightDistance[ i ] > 0.0 )",
  15819. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  15820. "spotVector = normalize( spotVector );",
  15821. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  15822. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  15823. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  15824. // diffuse
  15825. "#ifdef WRAP_AROUND",
  15826. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15827. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15828. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15829. "#else",
  15830. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15831. "#endif",
  15832. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15833. // specular
  15834. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15835. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15836. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15837. "#ifdef PHYSICALLY_BASED_SHADING",
  15838. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15839. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15840. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15841. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15842. "#else",
  15843. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15844. "#endif",
  15845. "}",
  15846. "}",
  15847. "#endif",
  15848. // directional lights
  15849. "#if MAX_DIR_LIGHTS > 0",
  15850. "vec3 dirDiffuse = vec3( 0.0 );",
  15851. "vec3 dirSpecular = vec3( 0.0 );",
  15852. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15853. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15854. "vec3 dirVector = normalize( lDirection.xyz );",
  15855. // diffuse
  15856. "#ifdef WRAP_AROUND",
  15857. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15858. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15859. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15860. "#else",
  15861. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15862. "#endif",
  15863. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15864. // specular
  15865. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15866. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15867. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15868. "#ifdef PHYSICALLY_BASED_SHADING",
  15869. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15870. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15871. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15872. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15873. "#else",
  15874. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15875. "#endif",
  15876. "}",
  15877. "#endif",
  15878. // hemisphere lights
  15879. "#if MAX_HEMI_LIGHTS > 0",
  15880. "vec3 hemiDiffuse = vec3( 0.0 );",
  15881. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15882. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15883. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15884. "vec3 lVector = normalize( lDirection.xyz );",
  15885. // diffuse
  15886. "float dotProduct = dot( normal, lVector );",
  15887. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  15888. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  15889. "hemiDiffuse += uDiffuseColor * hemiColor;",
  15890. // specular (sky light)
  15891. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  15892. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  15893. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  15894. // specular (ground light)
  15895. "vec3 lVectorGround = -lVector;",
  15896. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  15897. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15898. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15899. "#ifdef PHYSICALLY_BASED_SHADING",
  15900. "float dotProductGround = dot( normal, lVectorGround );",
  15901. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15902. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15903. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15904. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15905. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15906. "#else",
  15907. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15908. "#endif",
  15909. "}",
  15910. "#endif",
  15911. // all lights contribution summation
  15912. "vec3 totalDiffuse = vec3( 0.0 );",
  15913. "vec3 totalSpecular = vec3( 0.0 );",
  15914. "#if MAX_DIR_LIGHTS > 0",
  15915. "totalDiffuse += dirDiffuse;",
  15916. "totalSpecular += dirSpecular;",
  15917. "#endif",
  15918. "#if MAX_HEMI_LIGHTS > 0",
  15919. "totalDiffuse += hemiDiffuse;",
  15920. "totalSpecular += hemiSpecular;",
  15921. "#endif",
  15922. "#if MAX_POINT_LIGHTS > 0",
  15923. "totalDiffuse += pointDiffuse;",
  15924. "totalSpecular += pointSpecular;",
  15925. "#endif",
  15926. "#if MAX_SPOT_LIGHTS > 0",
  15927. "totalDiffuse += spotDiffuse;",
  15928. "totalSpecular += spotSpecular;",
  15929. "#endif",
  15930. "#ifdef METAL",
  15931. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15932. "#else",
  15933. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15934. "#endif",
  15935. "if ( enableReflection ) {",
  15936. "vec3 vReflect;",
  15937. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15938. "if ( useRefract ) {",
  15939. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15940. "} else {",
  15941. "vReflect = reflect( cameraToVertex, normal );",
  15942. "}",
  15943. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15944. "#ifdef GAMMA_INPUT",
  15945. "cubeColor.xyz *= cubeColor.xyz;",
  15946. "#endif",
  15947. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15948. "}",
  15949. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15950. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15951. THREE.ShaderChunk[ "fog_fragment" ],
  15952. "}"
  15953. ].join("\n"),
  15954. vertexShader: [
  15955. "attribute vec4 tangent;",
  15956. "uniform vec2 uOffset;",
  15957. "uniform vec2 uRepeat;",
  15958. "uniform bool enableDisplacement;",
  15959. "#ifdef VERTEX_TEXTURES",
  15960. "uniform sampler2D tDisplacement;",
  15961. "uniform float uDisplacementScale;",
  15962. "uniform float uDisplacementBias;",
  15963. "#endif",
  15964. "varying vec3 vTangent;",
  15965. "varying vec3 vBinormal;",
  15966. "varying vec3 vNormal;",
  15967. "varying vec2 vUv;",
  15968. "varying vec3 vWorldPosition;",
  15969. "varying vec3 vViewPosition;",
  15970. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15971. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15972. "void main() {",
  15973. THREE.ShaderChunk[ "skinbase_vertex" ],
  15974. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15975. // normal, tangent and binormal vectors
  15976. "#ifdef USE_SKINNING",
  15977. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15978. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15979. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15980. "#else",
  15981. "vNormal = normalize( normalMatrix * normal );",
  15982. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15983. "#endif",
  15984. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15985. "vUv = uv * uRepeat + uOffset;",
  15986. // displacement mapping
  15987. "vec3 displacedPosition;",
  15988. "#ifdef VERTEX_TEXTURES",
  15989. "if ( enableDisplacement ) {",
  15990. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15991. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15992. "displacedPosition = position + normalize( normal ) * df;",
  15993. "} else {",
  15994. "#ifdef USE_SKINNING",
  15995. "vec4 skinVertex = vec4( position, 1.0 );",
  15996. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15997. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15998. "displacedPosition = skinned.xyz;",
  15999. "#else",
  16000. "displacedPosition = position;",
  16001. "#endif",
  16002. "}",
  16003. "#else",
  16004. "#ifdef USE_SKINNING",
  16005. "vec4 skinVertex = vec4( position, 1.0 );",
  16006. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  16007. "skinned += boneMatY * skinVertex * skinWeight.y;",
  16008. "displacedPosition = skinned.xyz;",
  16009. "#else",
  16010. "displacedPosition = position;",
  16011. "#endif",
  16012. "#endif",
  16013. //
  16014. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  16015. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  16016. "gl_Position = projectionMatrix * mvPosition;",
  16017. //
  16018. "vWorldPosition = worldPosition.xyz;",
  16019. "vViewPosition = -mvPosition.xyz;",
  16020. // shadows
  16021. "#ifdef USE_SHADOWMAP",
  16022. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  16023. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  16024. "}",
  16025. "#endif",
  16026. "}"
  16027. ].join("\n")
  16028. },
  16029. /* -------------------------------------------------------------------------
  16030. // Cube map shader
  16031. ------------------------------------------------------------------------- */
  16032. 'cube': {
  16033. uniforms: { "tCube": { type: "t", value: null },
  16034. "tFlip": { type: "f", value: -1 } },
  16035. vertexShader: [
  16036. "varying vec3 vWorldPosition;",
  16037. "void main() {",
  16038. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  16039. "vWorldPosition = worldPosition.xyz;",
  16040. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  16041. "}"
  16042. ].join("\n"),
  16043. fragmentShader: [
  16044. "uniform samplerCube tCube;",
  16045. "uniform float tFlip;",
  16046. "varying vec3 vWorldPosition;",
  16047. "void main() {",
  16048. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  16049. "}"
  16050. ].join("\n")
  16051. }
  16052. }
  16053. };
  16054. /**
  16055. * @author zz85 / http://www.lab4games.net/zz85/blog
  16056. * @author alteredq / http://alteredqualia.com/
  16057. *
  16058. * For Text operations in three.js (See TextGeometry)
  16059. *
  16060. * It uses techniques used in:
  16061. *
  16062. * typeface.js and canvastext
  16063. * For converting fonts and rendering with javascript
  16064. * http://typeface.neocracy.org
  16065. *
  16066. * Triangulation ported from AS3
  16067. * Simple Polygon Triangulation
  16068. * http://actionsnippet.com/?p=1462
  16069. *
  16070. * A Method to triangulate shapes with holes
  16071. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16072. *
  16073. */
  16074. THREE.FontUtils = {
  16075. faces : {},
  16076. // Just for now. face[weight][style]
  16077. face : "helvetiker",
  16078. weight: "normal",
  16079. style : "normal",
  16080. size : 150,
  16081. divisions : 10,
  16082. getFace : function() {
  16083. return this.faces[ this.face ][ this.weight ][ this.style ];
  16084. },
  16085. loadFace : function( data ) {
  16086. var family = data.familyName.toLowerCase();
  16087. var ThreeFont = this;
  16088. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16089. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16090. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16091. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16092. return data;
  16093. },
  16094. drawText : function( text ) {
  16095. var characterPts = [], allPts = [];
  16096. // RenderText
  16097. var i, p,
  16098. face = this.getFace(),
  16099. scale = this.size / face.resolution,
  16100. offset = 0,
  16101. chars = String( text ).split( '' ),
  16102. length = chars.length;
  16103. var fontPaths = [];
  16104. for ( i = 0; i < length; i ++ ) {
  16105. var path = new THREE.Path();
  16106. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16107. offset += ret.offset;
  16108. fontPaths.push( ret.path );
  16109. }
  16110. // get the width
  16111. var width = offset / 2;
  16112. //
  16113. // for ( p = 0; p < allPts.length; p++ ) {
  16114. //
  16115. // allPts[ p ].x -= width;
  16116. //
  16117. // }
  16118. //var extract = this.extractPoints( allPts, characterPts );
  16119. //extract.contour = allPts;
  16120. //extract.paths = fontPaths;
  16121. //extract.offset = width;
  16122. return { paths : fontPaths, offset : width };
  16123. },
  16124. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16125. var pts = [];
  16126. var i, i2, divisions,
  16127. outline, action, length,
  16128. scaleX, scaleY,
  16129. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16130. laste,
  16131. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16132. if ( !glyph ) return;
  16133. if ( glyph.o ) {
  16134. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16135. length = outline.length;
  16136. scaleX = scale;
  16137. scaleY = scale;
  16138. for ( i = 0; i < length; ) {
  16139. action = outline[ i ++ ];
  16140. //console.log( action );
  16141. switch( action ) {
  16142. case 'm':
  16143. // Move To
  16144. x = outline[ i++ ] * scaleX + offset;
  16145. y = outline[ i++ ] * scaleY;
  16146. path.moveTo( x, y );
  16147. break;
  16148. case 'l':
  16149. // Line To
  16150. x = outline[ i++ ] * scaleX + offset;
  16151. y = outline[ i++ ] * scaleY;
  16152. path.lineTo(x,y);
  16153. break;
  16154. case 'q':
  16155. // QuadraticCurveTo
  16156. cpx = outline[ i++ ] * scaleX + offset;
  16157. cpy = outline[ i++ ] * scaleY;
  16158. cpx1 = outline[ i++ ] * scaleX + offset;
  16159. cpy1 = outline[ i++ ] * scaleY;
  16160. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16161. laste = pts[ pts.length - 1 ];
  16162. if ( laste ) {
  16163. cpx0 = laste.x;
  16164. cpy0 = laste.y;
  16165. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16166. var t = i2 / divisions;
  16167. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16168. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16169. }
  16170. }
  16171. break;
  16172. case 'b':
  16173. // Cubic Bezier Curve
  16174. cpx = outline[ i++ ] * scaleX + offset;
  16175. cpy = outline[ i++ ] * scaleY;
  16176. cpx1 = outline[ i++ ] * scaleX + offset;
  16177. cpy1 = outline[ i++ ] * -scaleY;
  16178. cpx2 = outline[ i++ ] * scaleX + offset;
  16179. cpy2 = outline[ i++ ] * -scaleY;
  16180. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16181. laste = pts[ pts.length - 1 ];
  16182. if ( laste ) {
  16183. cpx0 = laste.x;
  16184. cpy0 = laste.y;
  16185. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16186. var t = i2 / divisions;
  16187. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16188. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16189. }
  16190. }
  16191. break;
  16192. }
  16193. }
  16194. }
  16195. return { offset: glyph.ha*scale, path:path};
  16196. }
  16197. };
  16198. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16199. // Parameters
  16200. parameters = parameters || {};
  16201. var size = parameters.size !== undefined ? parameters.size : 100;
  16202. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16203. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16204. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16205. var style = parameters.style !== undefined ? parameters.style : "normal";
  16206. THREE.FontUtils.size = size;
  16207. THREE.FontUtils.divisions = curveSegments;
  16208. THREE.FontUtils.face = font;
  16209. THREE.FontUtils.weight = weight;
  16210. THREE.FontUtils.style = style;
  16211. // Get a Font data json object
  16212. var data = THREE.FontUtils.drawText( text );
  16213. var paths = data.paths;
  16214. var shapes = [];
  16215. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16216. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16217. }
  16218. return shapes;
  16219. };
  16220. /**
  16221. * This code is a quick port of code written in C++ which was submitted to
  16222. * flipcode.com by John W. Ratcliff // July 22, 2000
  16223. * See original code and more information here:
  16224. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16225. *
  16226. * ported to actionscript by Zevan Rosser
  16227. * www.actionsnippet.com
  16228. *
  16229. * ported to javascript by Joshua Koo
  16230. * http://www.lab4games.net/zz85/blog
  16231. *
  16232. */
  16233. ( function( namespace ) {
  16234. var EPSILON = 0.0000000001;
  16235. // takes in an contour array and returns
  16236. var process = function( contour, indices ) {
  16237. var n = contour.length;
  16238. if ( n < 3 ) return null;
  16239. var result = [],
  16240. verts = [],
  16241. vertIndices = [];
  16242. /* we want a counter-clockwise polygon in verts */
  16243. var u, v, w;
  16244. if ( area( contour ) > 0.0 ) {
  16245. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16246. } else {
  16247. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16248. }
  16249. var nv = n;
  16250. /* remove nv - 2 vertices, creating 1 triangle every time */
  16251. var count = 2 * nv; /* error detection */
  16252. for( v = nv - 1; nv > 2; ) {
  16253. /* if we loop, it is probably a non-simple polygon */
  16254. if ( ( count-- ) <= 0 ) {
  16255. //** Triangulate: ERROR - probable bad polygon!
  16256. //throw ( "Warning, unable to triangulate polygon!" );
  16257. //return null;
  16258. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16259. console.log( "Warning, unable to triangulate polygon!" );
  16260. if ( indices ) return vertIndices;
  16261. return result;
  16262. }
  16263. /* three consecutive vertices in current polygon, <u,v,w> */
  16264. u = v; if ( nv <= u ) u = 0; /* previous */
  16265. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16266. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16267. if ( snip( contour, u, v, w, nv, verts ) ) {
  16268. var a, b, c, s, t;
  16269. /* true names of the vertices */
  16270. a = verts[ u ];
  16271. b = verts[ v ];
  16272. c = verts[ w ];
  16273. /* output Triangle */
  16274. result.push( [ contour[ a ],
  16275. contour[ b ],
  16276. contour[ c ] ] );
  16277. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16278. /* remove v from the remaining polygon */
  16279. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16280. verts[ s ] = verts[ t ];
  16281. }
  16282. nv--;
  16283. /* reset error detection counter */
  16284. count = 2 * nv;
  16285. }
  16286. }
  16287. if ( indices ) return vertIndices;
  16288. return result;
  16289. };
  16290. // calculate area of the contour polygon
  16291. var area = function ( contour ) {
  16292. var n = contour.length;
  16293. var a = 0.0;
  16294. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16295. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16296. }
  16297. return a * 0.5;
  16298. };
  16299. var snip = function ( contour, u, v, w, n, verts ) {
  16300. var p;
  16301. var ax, ay, bx, by;
  16302. var cx, cy, px, py;
  16303. ax = contour[ verts[ u ] ].x;
  16304. ay = contour[ verts[ u ] ].y;
  16305. bx = contour[ verts[ v ] ].x;
  16306. by = contour[ verts[ v ] ].y;
  16307. cx = contour[ verts[ w ] ].x;
  16308. cy = contour[ verts[ w ] ].y;
  16309. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16310. var aX, aY, bX, bY, cX, cY;
  16311. var apx, apy, bpx, bpy, cpx, cpy;
  16312. var cCROSSap, bCROSScp, aCROSSbp;
  16313. aX = cx - bx; aY = cy - by;
  16314. bX = ax - cx; bY = ay - cy;
  16315. cX = bx - ax; cY = by - ay;
  16316. for ( p = 0; p < n; p++ ) {
  16317. if( (p === u) || (p === v) || (p === w) ) continue;
  16318. px = contour[ verts[ p ] ].x
  16319. py = contour[ verts[ p ] ].y
  16320. apx = px - ax; apy = py - ay;
  16321. bpx = px - bx; bpy = py - by;
  16322. cpx = px - cx; cpy = py - cy;
  16323. // see if p is inside triangle abc
  16324. aCROSSbp = aX*bpy - aY*bpx;
  16325. cCROSSap = cX*apy - cY*apx;
  16326. bCROSScp = bX*cpy - bY*cpx;
  16327. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16328. }
  16329. return true;
  16330. };
  16331. namespace.Triangulate = process;
  16332. namespace.Triangulate.area = area;
  16333. return namespace;
  16334. })(THREE.FontUtils);
  16335. // To use the typeface.js face files, hook up the API
  16336. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16337. * @author zz85 / http://www.lab4games.net/zz85/blog
  16338. * Extensible curve object
  16339. *
  16340. * Some common of Curve methods
  16341. * .getPoint(t), getTangent(t)
  16342. * .getPointAt(u), getTagentAt(u)
  16343. * .getPoints(), .getSpacedPoints()
  16344. * .getLength()
  16345. * .updateArcLengths()
  16346. *
  16347. * This file contains following classes:
  16348. *
  16349. * -- 2d classes --
  16350. * THREE.Curve
  16351. * THREE.LineCurve
  16352. * THREE.QuadraticBezierCurve
  16353. * THREE.CubicBezierCurve
  16354. * THREE.SplineCurve
  16355. * THREE.ArcCurve
  16356. * THREE.EllipseCurve
  16357. *
  16358. * -- 3d classes --
  16359. * THREE.LineCurve3
  16360. * THREE.QuadraticBezierCurve3
  16361. * THREE.CubicBezierCurve3
  16362. * THREE.SplineCurve3
  16363. * THREE.ClosedSplineCurve3
  16364. *
  16365. * A series of curves can be represented as a THREE.CurvePath
  16366. *
  16367. **/
  16368. /**************************************************************
  16369. * Abstract Curve base class
  16370. **************************************************************/
  16371. THREE.Curve = function () {
  16372. };
  16373. // Virtual base class method to overwrite and implement in subclasses
  16374. // - t [0 .. 1]
  16375. THREE.Curve.prototype.getPoint = function ( t ) {
  16376. console.log( "Warning, getPoint() not implemented!" );
  16377. return null;
  16378. };
  16379. // Get point at relative position in curve according to arc length
  16380. // - u [0 .. 1]
  16381. THREE.Curve.prototype.getPointAt = function ( u ) {
  16382. var t = this.getUtoTmapping( u );
  16383. return this.getPoint( t );
  16384. };
  16385. // Get sequence of points using getPoint( t )
  16386. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16387. if ( !divisions ) divisions = 5;
  16388. var d, pts = [];
  16389. for ( d = 0; d <= divisions; d ++ ) {
  16390. pts.push( this.getPoint( d / divisions ) );
  16391. }
  16392. return pts;
  16393. };
  16394. // Get sequence of points using getPointAt( u )
  16395. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16396. if ( !divisions ) divisions = 5;
  16397. var d, pts = [];
  16398. for ( d = 0; d <= divisions; d ++ ) {
  16399. pts.push( this.getPointAt( d / divisions ) );
  16400. }
  16401. return pts;
  16402. };
  16403. // Get total curve arc length
  16404. THREE.Curve.prototype.getLength = function () {
  16405. var lengths = this.getLengths();
  16406. return lengths[ lengths.length - 1 ];
  16407. };
  16408. // Get list of cumulative segment lengths
  16409. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16410. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16411. if ( this.cacheArcLengths
  16412. && ( this.cacheArcLengths.length == divisions + 1 )
  16413. && !this.needsUpdate) {
  16414. //console.log( "cached", this.cacheArcLengths );
  16415. return this.cacheArcLengths;
  16416. }
  16417. this.needsUpdate = false;
  16418. var cache = [];
  16419. var current, last = this.getPoint( 0 );
  16420. var p, sum = 0;
  16421. cache.push( 0 );
  16422. for ( p = 1; p <= divisions; p ++ ) {
  16423. current = this.getPoint ( p / divisions );
  16424. sum += current.distanceTo( last );
  16425. cache.push( sum );
  16426. last = current;
  16427. }
  16428. this.cacheArcLengths = cache;
  16429. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16430. };
  16431. THREE.Curve.prototype.updateArcLengths = function() {
  16432. this.needsUpdate = true;
  16433. this.getLengths();
  16434. };
  16435. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16436. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16437. var arcLengths = this.getLengths();
  16438. var i = 0, il = arcLengths.length;
  16439. var targetArcLength; // The targeted u distance value to get
  16440. if ( distance ) {
  16441. targetArcLength = distance;
  16442. } else {
  16443. targetArcLength = u * arcLengths[ il - 1 ];
  16444. }
  16445. //var time = Date.now();
  16446. // binary search for the index with largest value smaller than target u distance
  16447. var low = 0, high = il - 1, comparison;
  16448. while ( low <= high ) {
  16449. 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
  16450. comparison = arcLengths[ i ] - targetArcLength;
  16451. if ( comparison < 0 ) {
  16452. low = i + 1;
  16453. continue;
  16454. } else if ( comparison > 0 ) {
  16455. high = i - 1;
  16456. continue;
  16457. } else {
  16458. high = i;
  16459. break;
  16460. // DONE
  16461. }
  16462. }
  16463. i = high;
  16464. //console.log('b' , i, low, high, Date.now()- time);
  16465. if ( arcLengths[ i ] == targetArcLength ) {
  16466. var t = i / ( il - 1 );
  16467. return t;
  16468. }
  16469. // we could get finer grain at lengths, or use simple interpolatation between two points
  16470. var lengthBefore = arcLengths[ i ];
  16471. var lengthAfter = arcLengths[ i + 1 ];
  16472. var segmentLength = lengthAfter - lengthBefore;
  16473. // determine where we are between the 'before' and 'after' points
  16474. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16475. // add that fractional amount to t
  16476. var t = ( i + segmentFraction ) / ( il -1 );
  16477. return t;
  16478. };
  16479. // Returns a unit vector tangent at t
  16480. // In case any sub curve does not implement its tangent derivation,
  16481. // 2 points a small delta apart will be used to find its gradient
  16482. // which seems to give a reasonable approximation
  16483. THREE.Curve.prototype.getTangent = function( t ) {
  16484. var delta = 0.0001;
  16485. var t1 = t - delta;
  16486. var t2 = t + delta;
  16487. // Capping in case of danger
  16488. if ( t1 < 0 ) t1 = 0;
  16489. if ( t2 > 1 ) t2 = 1;
  16490. var pt1 = this.getPoint( t1 );
  16491. var pt2 = this.getPoint( t2 );
  16492. var vec = pt2.clone().subSelf(pt1);
  16493. return vec.normalize();
  16494. };
  16495. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16496. var t = this.getUtoTmapping( u );
  16497. return this.getTangent( t );
  16498. };
  16499. /**************************************************************
  16500. * Line
  16501. **************************************************************/
  16502. THREE.LineCurve = function ( v1, v2 ) {
  16503. this.v1 = v1;
  16504. this.v2 = v2;
  16505. };
  16506. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16507. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16508. var point = this.v2.clone().subSelf(this.v1);
  16509. point.multiplyScalar( t ).addSelf( this.v1 );
  16510. return point;
  16511. };
  16512. // Line curve is linear, so we can overwrite default getPointAt
  16513. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16514. return this.getPoint( u );
  16515. };
  16516. THREE.LineCurve.prototype.getTangent = function( t ) {
  16517. var tangent = this.v2.clone().subSelf(this.v1);
  16518. return tangent.normalize();
  16519. };
  16520. /**************************************************************
  16521. * Quadratic Bezier curve
  16522. **************************************************************/
  16523. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16524. this.v0 = v0;
  16525. this.v1 = v1;
  16526. this.v2 = v2;
  16527. };
  16528. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16529. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16530. var tx, ty;
  16531. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16532. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16533. return new THREE.Vector2( tx, ty );
  16534. };
  16535. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16536. var tx, ty;
  16537. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16538. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16539. // returns unit vector
  16540. var tangent = new THREE.Vector2( tx, ty );
  16541. tangent.normalize();
  16542. return tangent;
  16543. };
  16544. /**************************************************************
  16545. * Cubic Bezier curve
  16546. **************************************************************/
  16547. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16548. this.v0 = v0;
  16549. this.v1 = v1;
  16550. this.v2 = v2;
  16551. this.v3 = v3;
  16552. };
  16553. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16554. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16555. var tx, ty;
  16556. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16557. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16558. return new THREE.Vector2( tx, ty );
  16559. };
  16560. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16561. var tx, ty;
  16562. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16563. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16564. var tangent = new THREE.Vector2( tx, ty );
  16565. tangent.normalize();
  16566. return tangent;
  16567. };
  16568. /**************************************************************
  16569. * Spline curve
  16570. **************************************************************/
  16571. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16572. this.points = (points == undefined) ? [] : points;
  16573. };
  16574. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16575. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16576. var v = new THREE.Vector2();
  16577. var c = [];
  16578. var points = this.points, point, intPoint, weight;
  16579. point = ( points.length - 1 ) * t;
  16580. intPoint = Math.floor( point );
  16581. weight = point - intPoint;
  16582. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16583. c[ 1 ] = intPoint;
  16584. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16585. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16586. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16587. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16588. return v;
  16589. };
  16590. /**************************************************************
  16591. * Ellipse curve
  16592. **************************************************************/
  16593. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16594. aStartAngle, aEndAngle,
  16595. aClockwise ) {
  16596. this.aX = aX;
  16597. this.aY = aY;
  16598. this.xRadius = xRadius;
  16599. this.yRadius = yRadius;
  16600. this.aStartAngle = aStartAngle;
  16601. this.aEndAngle = aEndAngle;
  16602. this.aClockwise = aClockwise;
  16603. };
  16604. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16605. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16606. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16607. if ( !this.aClockwise ) {
  16608. t = 1 - t;
  16609. }
  16610. var angle = this.aStartAngle + t * deltaAngle;
  16611. var tx = this.aX + this.xRadius * Math.cos( angle );
  16612. var ty = this.aY + this.yRadius * Math.sin( angle );
  16613. return new THREE.Vector2( tx, ty );
  16614. };
  16615. /**************************************************************
  16616. * Arc curve
  16617. **************************************************************/
  16618. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16619. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16620. };
  16621. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16622. /**************************************************************
  16623. * Utils
  16624. **************************************************************/
  16625. THREE.Curve.Utils = {
  16626. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16627. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16628. },
  16629. // Puay Bing, thanks for helping with this derivative!
  16630. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16631. return -3 * p0 * (1 - t) * (1 - t) +
  16632. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16633. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16634. 3 * t * t * p3;
  16635. },
  16636. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16637. // To check if my formulas are correct
  16638. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16639. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16640. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16641. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16642. return h00 + h10 + h01 + h11;
  16643. },
  16644. // Catmull-Rom
  16645. interpolate: function( p0, p1, p2, p3, t ) {
  16646. var v0 = ( p2 - p0 ) * 0.5;
  16647. var v1 = ( p3 - p1 ) * 0.5;
  16648. var t2 = t * t;
  16649. var t3 = t * t2;
  16650. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16651. }
  16652. };
  16653. // TODO: Transformation for Curves?
  16654. /**************************************************************
  16655. * 3D Curves
  16656. **************************************************************/
  16657. // A Factory method for creating new curve subclasses
  16658. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16659. constructor.prototype = Object.create( THREE.Curve.prototype );
  16660. constructor.prototype.getPoint = getPointFunc;
  16661. return constructor;
  16662. };
  16663. /**************************************************************
  16664. * Line3D
  16665. **************************************************************/
  16666. THREE.LineCurve3 = THREE.Curve.create(
  16667. function ( v1, v2 ) {
  16668. this.v1 = v1;
  16669. this.v2 = v2;
  16670. },
  16671. function ( t ) {
  16672. var r = new THREE.Vector3();
  16673. r.sub( this.v2, this.v1 ); // diff
  16674. r.multiplyScalar( t );
  16675. r.addSelf( this.v1 );
  16676. return r;
  16677. }
  16678. );
  16679. /**************************************************************
  16680. * Quadratic Bezier 3D curve
  16681. **************************************************************/
  16682. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16683. function ( v0, v1, v2 ) {
  16684. this.v0 = v0;
  16685. this.v1 = v1;
  16686. this.v2 = v2;
  16687. },
  16688. function ( t ) {
  16689. var tx, ty, tz;
  16690. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16691. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16692. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16693. return new THREE.Vector3( tx, ty, tz );
  16694. }
  16695. );
  16696. /**************************************************************
  16697. * Cubic Bezier 3D curve
  16698. **************************************************************/
  16699. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16700. function ( v0, v1, v2, v3 ) {
  16701. this.v0 = v0;
  16702. this.v1 = v1;
  16703. this.v2 = v2;
  16704. this.v3 = v3;
  16705. },
  16706. function ( t ) {
  16707. var tx, ty, tz;
  16708. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16709. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16710. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16711. return new THREE.Vector3( tx, ty, tz );
  16712. }
  16713. );
  16714. /**************************************************************
  16715. * Spline 3D curve
  16716. **************************************************************/
  16717. THREE.SplineCurve3 = THREE.Curve.create(
  16718. function ( points /* array of Vector3 */) {
  16719. this.points = (points == undefined) ? [] : points;
  16720. },
  16721. function ( t ) {
  16722. var v = new THREE.Vector3();
  16723. var c = [];
  16724. var points = this.points, point, intPoint, weight;
  16725. point = ( points.length - 1 ) * t;
  16726. intPoint = Math.floor( point );
  16727. weight = point - intPoint;
  16728. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16729. c[ 1 ] = intPoint;
  16730. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16731. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16732. var pt0 = points[ c[0] ],
  16733. pt1 = points[ c[1] ],
  16734. pt2 = points[ c[2] ],
  16735. pt3 = points[ c[3] ];
  16736. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16737. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16738. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16739. return v;
  16740. }
  16741. );
  16742. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16743. // var v = new THREE.Vector3();
  16744. // var c = [];
  16745. // var points = this.points, point, intPoint, weight;
  16746. // point = ( points.length - 1 ) * t;
  16747. // intPoint = Math.floor( point );
  16748. // weight = point - intPoint;
  16749. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16750. // c[ 1 ] = intPoint;
  16751. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16752. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16753. // var pt0 = points[ c[0] ],
  16754. // pt1 = points[ c[1] ],
  16755. // pt2 = points[ c[2] ],
  16756. // pt3 = points[ c[3] ];
  16757. // // t = weight;
  16758. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16759. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16760. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16761. // return v;
  16762. // }
  16763. /**************************************************************
  16764. * Closed Spline 3D curve
  16765. **************************************************************/
  16766. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16767. function ( points /* array of Vector3 */) {
  16768. this.points = (points == undefined) ? [] : points;
  16769. },
  16770. function ( t ) {
  16771. var v = new THREE.Vector3();
  16772. var c = [];
  16773. var points = this.points, point, intPoint, weight;
  16774. point = ( points.length - 0 ) * t;
  16775. // This needs to be from 0-length +1
  16776. intPoint = Math.floor( point );
  16777. weight = point - intPoint;
  16778. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16779. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16780. c[ 1 ] = ( intPoint ) % points.length;
  16781. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16782. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16783. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16784. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16785. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16786. return v;
  16787. }
  16788. );
  16789. /**
  16790. * @author zz85 / http://www.lab4games.net/zz85/blog
  16791. *
  16792. **/
  16793. /**************************************************************
  16794. * Curved Path - a curve path is simply a array of connected
  16795. * curves, but retains the api of a curve
  16796. **************************************************************/
  16797. THREE.CurvePath = function () {
  16798. this.curves = [];
  16799. this.bends = [];
  16800. this.autoClose = false; // Automatically closes the path
  16801. };
  16802. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16803. THREE.CurvePath.prototype.add = function ( curve ) {
  16804. this.curves.push( curve );
  16805. };
  16806. THREE.CurvePath.prototype.checkConnection = function() {
  16807. // TODO
  16808. // If the ending of curve is not connected to the starting
  16809. // or the next curve, then, this is not a real path
  16810. };
  16811. THREE.CurvePath.prototype.closePath = function() {
  16812. // TODO Test
  16813. // and verify for vector3 (needs to implement equals)
  16814. // Add a line curve if start and end of lines are not connected
  16815. var startPoint = this.curves[0].getPoint(0);
  16816. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16817. if (!startPoint.equals(endPoint)) {
  16818. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16819. }
  16820. };
  16821. // To get accurate point with reference to
  16822. // entire path distance at time t,
  16823. // following has to be done:
  16824. // 1. Length of each sub path have to be known
  16825. // 2. Locate and identify type of curve
  16826. // 3. Get t for the curve
  16827. // 4. Return curve.getPointAt(t')
  16828. THREE.CurvePath.prototype.getPoint = function( t ) {
  16829. var d = t * this.getLength();
  16830. var curveLengths = this.getCurveLengths();
  16831. var i = 0, diff, curve;
  16832. // To think about boundaries points.
  16833. while ( i < curveLengths.length ) {
  16834. if ( curveLengths[ i ] >= d ) {
  16835. diff = curveLengths[ i ] - d;
  16836. curve = this.curves[ i ];
  16837. var u = 1 - diff / curve.getLength();
  16838. return curve.getPointAt( u );
  16839. break;
  16840. }
  16841. i ++;
  16842. }
  16843. return null;
  16844. // loop where sum != 0, sum > d , sum+1 <d
  16845. };
  16846. /*
  16847. THREE.CurvePath.prototype.getTangent = function( t ) {
  16848. };*/
  16849. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16850. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16851. // getPoint() depends on getLength
  16852. THREE.CurvePath.prototype.getLength = function() {
  16853. var lens = this.getCurveLengths();
  16854. return lens[ lens.length - 1 ];
  16855. };
  16856. // Compute lengths and cache them
  16857. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16858. THREE.CurvePath.prototype.getCurveLengths = function() {
  16859. // We use cache values if curves and cache array are same length
  16860. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16861. return this.cacheLengths;
  16862. };
  16863. // Get length of subsurve
  16864. // Push sums into cached array
  16865. var lengths = [], sums = 0;
  16866. var i, il = this.curves.length;
  16867. for ( i = 0; i < il; i ++ ) {
  16868. sums += this.curves[ i ].getLength();
  16869. lengths.push( sums );
  16870. }
  16871. this.cacheLengths = lengths;
  16872. return lengths;
  16873. };
  16874. // Returns min and max coordinates, as well as centroid
  16875. THREE.CurvePath.prototype.getBoundingBox = function () {
  16876. var points = this.getPoints();
  16877. var maxX, maxY, maxZ;
  16878. var minX, minY, minZ;
  16879. maxX = maxY = Number.NEGATIVE_INFINITY;
  16880. minX = minY = Number.POSITIVE_INFINITY;
  16881. var p, i, il, sum;
  16882. var v3 = points[0] instanceof THREE.Vector3;
  16883. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16884. for ( i = 0, il = points.length; i < il; i ++ ) {
  16885. p = points[ i ];
  16886. if ( p.x > maxX ) maxX = p.x;
  16887. else if ( p.x < minX ) minX = p.x;
  16888. if ( p.y > maxY ) maxY = p.y;
  16889. else if ( p.y < minY ) minY = p.y;
  16890. if (v3) {
  16891. if ( p.z > maxZ ) maxZ = p.z;
  16892. else if ( p.z < minZ ) minZ = p.z;
  16893. }
  16894. sum.addSelf( p );
  16895. }
  16896. var ret = {
  16897. minX: minX,
  16898. minY: minY,
  16899. maxX: maxX,
  16900. maxY: maxY,
  16901. centroid: sum.divideScalar( il )
  16902. };
  16903. if (v3) {
  16904. ret.maxZ = maxZ;
  16905. ret.minZ = minZ;
  16906. }
  16907. return ret;
  16908. };
  16909. /**************************************************************
  16910. * Create Geometries Helpers
  16911. **************************************************************/
  16912. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16913. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16914. var pts = this.getPoints( divisions, true );
  16915. return this.createGeometry( pts );
  16916. };
  16917. // Generate geometry from equidistance sampling along the path
  16918. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16919. var pts = this.getSpacedPoints( divisions, true );
  16920. return this.createGeometry( pts );
  16921. };
  16922. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16923. var geometry = new THREE.Geometry();
  16924. for ( var i = 0; i < points.length; i ++ ) {
  16925. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16926. }
  16927. return geometry;
  16928. };
  16929. /**************************************************************
  16930. * Bend / Wrap Helper Methods
  16931. **************************************************************/
  16932. // Wrap path / Bend modifiers?
  16933. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16934. this.bends.push( bendpath );
  16935. };
  16936. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16937. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16938. var i, il;
  16939. if ( !bends ) {
  16940. bends = this.bends;
  16941. }
  16942. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16943. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16944. }
  16945. return oldPts;
  16946. };
  16947. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16948. var oldPts = this.getSpacedPoints( segments );
  16949. var i, il;
  16950. if ( !bends ) {
  16951. bends = this.bends;
  16952. }
  16953. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16954. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16955. }
  16956. return oldPts;
  16957. };
  16958. // This returns getPoints() bend/wrapped around the contour of a path.
  16959. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16960. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16961. var bounds = this.getBoundingBox();
  16962. var i, il, p, oldX, oldY, xNorm;
  16963. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16964. p = oldPts[ i ];
  16965. oldX = p.x;
  16966. oldY = p.y;
  16967. xNorm = oldX / bounds.maxX;
  16968. // If using actual distance, for length > path, requires line extrusions
  16969. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16970. xNorm = path.getUtoTmapping( xNorm, oldX );
  16971. // check for out of bounds?
  16972. var pathPt = path.getPoint( xNorm );
  16973. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16974. p.x = pathPt.x + normal.x;
  16975. p.y = pathPt.y + normal.y;
  16976. }
  16977. return oldPts;
  16978. };
  16979. /**
  16980. * @author alteredq / http://alteredqualia.com/
  16981. */
  16982. THREE.Gyroscope = function () {
  16983. THREE.Object3D.call( this );
  16984. };
  16985. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16986. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16987. this.matrixAutoUpdate && this.updateMatrix();
  16988. // update matrixWorld
  16989. if ( this.matrixWorldNeedsUpdate || force ) {
  16990. if ( this.parent ) {
  16991. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  16992. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16993. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16994. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16995. } else {
  16996. this.matrixWorld.copy( this.matrix );
  16997. }
  16998. this.matrixWorldNeedsUpdate = false;
  16999. force = true;
  17000. }
  17001. // update children
  17002. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17003. this.children[ i ].updateMatrixWorld( force );
  17004. }
  17005. };
  17006. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17007. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17008. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  17009. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  17010. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17011. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17012. /**
  17013. * @author zz85 / http://www.lab4games.net/zz85/blog
  17014. * Creates free form 2d path using series of points, lines or curves.
  17015. *
  17016. **/
  17017. THREE.Path = function ( points ) {
  17018. THREE.CurvePath.call(this);
  17019. this.actions = [];
  17020. if ( points ) {
  17021. this.fromPoints( points );
  17022. }
  17023. };
  17024. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17025. THREE.PathActions = {
  17026. MOVE_TO: 'moveTo',
  17027. LINE_TO: 'lineTo',
  17028. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17029. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17030. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17031. ARC: 'arc', // Circle
  17032. ELLIPSE: 'ellipse'
  17033. };
  17034. // TODO Clean up PATH API
  17035. // Create path using straight lines to connect all points
  17036. // - vectors: array of Vector2
  17037. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17038. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17039. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17040. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17041. };
  17042. };
  17043. // startPath() endPath()?
  17044. THREE.Path.prototype.moveTo = function ( x, y ) {
  17045. var args = Array.prototype.slice.call( arguments );
  17046. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17047. };
  17048. THREE.Path.prototype.lineTo = function ( x, y ) {
  17049. var args = Array.prototype.slice.call( arguments );
  17050. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17051. var x0 = lastargs[ lastargs.length - 2 ];
  17052. var y0 = lastargs[ lastargs.length - 1 ];
  17053. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17054. this.curves.push( curve );
  17055. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17056. };
  17057. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17058. var args = Array.prototype.slice.call( arguments );
  17059. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17060. var x0 = lastargs[ lastargs.length - 2 ];
  17061. var y0 = lastargs[ lastargs.length - 1 ];
  17062. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17063. new THREE.Vector2( aCPx, aCPy ),
  17064. new THREE.Vector2( aX, aY ) );
  17065. this.curves.push( curve );
  17066. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17067. };
  17068. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17069. aCP2x, aCP2y,
  17070. aX, aY ) {
  17071. var args = Array.prototype.slice.call( arguments );
  17072. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17073. var x0 = lastargs[ lastargs.length - 2 ];
  17074. var y0 = lastargs[ lastargs.length - 1 ];
  17075. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17076. new THREE.Vector2( aCP1x, aCP1y ),
  17077. new THREE.Vector2( aCP2x, aCP2y ),
  17078. new THREE.Vector2( aX, aY ) );
  17079. this.curves.push( curve );
  17080. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17081. };
  17082. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17083. var args = Array.prototype.slice.call( arguments );
  17084. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17085. var x0 = lastargs[ lastargs.length - 2 ];
  17086. var y0 = lastargs[ lastargs.length - 1 ];
  17087. //---
  17088. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17089. Array.prototype.push.apply( npts, pts );
  17090. var curve = new THREE.SplineCurve( npts );
  17091. this.curves.push( curve );
  17092. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17093. };
  17094. // FUTURE: Change the API or follow canvas API?
  17095. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17096. aStartAngle, aEndAngle, aClockwise ) {
  17097. var lastargs = this.actions[ this.actions.length - 1].args;
  17098. var x0 = lastargs[ lastargs.length - 2 ];
  17099. var y0 = lastargs[ lastargs.length - 1 ];
  17100. this.absarc(aX + x0, aY + y0, aRadius,
  17101. aStartAngle, aEndAngle, aClockwise );
  17102. };
  17103. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17104. aStartAngle, aEndAngle, aClockwise ) {
  17105. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17106. };
  17107. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17108. aStartAngle, aEndAngle, aClockwise ) {
  17109. var lastargs = this.actions[ this.actions.length - 1].args;
  17110. var x0 = lastargs[ lastargs.length - 2 ];
  17111. var y0 = lastargs[ lastargs.length - 1 ];
  17112. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17113. aStartAngle, aEndAngle, aClockwise );
  17114. };
  17115. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17116. aStartAngle, aEndAngle, aClockwise ) {
  17117. var args = Array.prototype.slice.call( arguments );
  17118. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17119. aStartAngle, aEndAngle, aClockwise );
  17120. this.curves.push( curve );
  17121. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17122. args.push(lastPoint.x);
  17123. args.push(lastPoint.y);
  17124. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17125. };
  17126. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17127. if ( ! divisions ) divisions = 40;
  17128. var points = [];
  17129. for ( var i = 0; i < divisions; i ++ ) {
  17130. points.push( this.getPoint( i / divisions ) );
  17131. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17132. }
  17133. // if ( closedPath ) {
  17134. //
  17135. // points.push( points[ 0 ] );
  17136. //
  17137. // }
  17138. return points;
  17139. };
  17140. /* Return an array of vectors based on contour of the path */
  17141. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17142. if (this.useSpacedPoints) {
  17143. console.log('tata');
  17144. return this.getSpacedPoints( divisions, closedPath );
  17145. }
  17146. divisions = divisions || 12;
  17147. var points = [];
  17148. var i, il, item, action, args;
  17149. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17150. laste, j,
  17151. t, tx, ty;
  17152. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17153. item = this.actions[ i ];
  17154. action = item.action;
  17155. args = item.args;
  17156. switch( action ) {
  17157. case THREE.PathActions.MOVE_TO:
  17158. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17159. break;
  17160. case THREE.PathActions.LINE_TO:
  17161. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17162. break;
  17163. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17164. cpx = args[ 2 ];
  17165. cpy = args[ 3 ];
  17166. cpx1 = args[ 0 ];
  17167. cpy1 = args[ 1 ];
  17168. if ( points.length > 0 ) {
  17169. laste = points[ points.length - 1 ];
  17170. cpx0 = laste.x;
  17171. cpy0 = laste.y;
  17172. } else {
  17173. laste = this.actions[ i - 1 ].args;
  17174. cpx0 = laste[ laste.length - 2 ];
  17175. cpy0 = laste[ laste.length - 1 ];
  17176. }
  17177. for ( j = 1; j <= divisions; j ++ ) {
  17178. t = j / divisions;
  17179. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17180. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17181. points.push( new THREE.Vector2( tx, ty ) );
  17182. }
  17183. break;
  17184. case THREE.PathActions.BEZIER_CURVE_TO:
  17185. cpx = args[ 4 ];
  17186. cpy = args[ 5 ];
  17187. cpx1 = args[ 0 ];
  17188. cpy1 = args[ 1 ];
  17189. cpx2 = args[ 2 ];
  17190. cpy2 = args[ 3 ];
  17191. if ( points.length > 0 ) {
  17192. laste = points[ points.length - 1 ];
  17193. cpx0 = laste.x;
  17194. cpy0 = laste.y;
  17195. } else {
  17196. laste = this.actions[ i - 1 ].args;
  17197. cpx0 = laste[ laste.length - 2 ];
  17198. cpy0 = laste[ laste.length - 1 ];
  17199. }
  17200. for ( j = 1; j <= divisions; j ++ ) {
  17201. t = j / divisions;
  17202. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17203. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17204. points.push( new THREE.Vector2( tx, ty ) );
  17205. }
  17206. break;
  17207. case THREE.PathActions.CSPLINE_THRU:
  17208. laste = this.actions[ i - 1 ].args;
  17209. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17210. var spts = [ last ];
  17211. var n = divisions * args[ 0 ].length;
  17212. spts = spts.concat( args[ 0 ] );
  17213. var spline = new THREE.SplineCurve( spts );
  17214. for ( j = 1; j <= n; j ++ ) {
  17215. points.push( spline.getPointAt( j / n ) ) ;
  17216. }
  17217. break;
  17218. case THREE.PathActions.ARC:
  17219. var aX = args[ 0 ], aY = args[ 1 ],
  17220. aRadius = args[ 2 ],
  17221. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17222. aClockwise = !!args[ 5 ];
  17223. var deltaAngle = aEndAngle - aStartAngle;
  17224. var angle;
  17225. var tdivisions = divisions * 2;
  17226. for ( j = 1; j <= tdivisions; j ++ ) {
  17227. t = j / tdivisions;
  17228. if ( ! aClockwise ) {
  17229. t = 1 - t;
  17230. }
  17231. angle = aStartAngle + t * deltaAngle;
  17232. tx = aX + aRadius * Math.cos( angle );
  17233. ty = aY + aRadius * Math.sin( angle );
  17234. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17235. points.push( new THREE.Vector2( tx, ty ) );
  17236. }
  17237. //console.log(points);
  17238. break;
  17239. case THREE.PathActions.ELLIPSE:
  17240. var aX = args[ 0 ], aY = args[ 1 ],
  17241. xRadius = args[ 2 ],
  17242. yRadius = args[ 3 ],
  17243. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17244. aClockwise = !!args[ 6 ];
  17245. var deltaAngle = aEndAngle - aStartAngle;
  17246. var angle;
  17247. var tdivisions = divisions * 2;
  17248. for ( j = 1; j <= tdivisions; j ++ ) {
  17249. t = j / tdivisions;
  17250. if ( ! aClockwise ) {
  17251. t = 1 - t;
  17252. }
  17253. angle = aStartAngle + t * deltaAngle;
  17254. tx = aX + xRadius * Math.cos( angle );
  17255. ty = aY + yRadius * Math.sin( angle );
  17256. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17257. points.push( new THREE.Vector2( tx, ty ) );
  17258. }
  17259. //console.log(points);
  17260. break;
  17261. } // end switch
  17262. }
  17263. // Normalize to remove the closing point by default.
  17264. var lastPoint = points[ points.length - 1];
  17265. var EPSILON = 0.0000000001;
  17266. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17267. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17268. points.splice( points.length - 1, 1);
  17269. if ( closedPath ) {
  17270. points.push( points[ 0 ] );
  17271. }
  17272. return points;
  17273. };
  17274. // Breaks path into shapes
  17275. THREE.Path.prototype.toShapes = function() {
  17276. var i, il, item, action, args;
  17277. var subPaths = [], lastPath = new THREE.Path();
  17278. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17279. item = this.actions[ i ];
  17280. args = item.args;
  17281. action = item.action;
  17282. if ( action == THREE.PathActions.MOVE_TO ) {
  17283. if ( lastPath.actions.length != 0 ) {
  17284. subPaths.push( lastPath );
  17285. lastPath = new THREE.Path();
  17286. }
  17287. }
  17288. lastPath[ action ].apply( lastPath, args );
  17289. }
  17290. if ( lastPath.actions.length != 0 ) {
  17291. subPaths.push( lastPath );
  17292. }
  17293. // console.log(subPaths);
  17294. if ( subPaths.length == 0 ) return [];
  17295. var tmpPath, tmpShape, shapes = [];
  17296. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17297. // console.log("Holes first", holesFirst);
  17298. if ( subPaths.length == 1) {
  17299. tmpPath = subPaths[0];
  17300. tmpShape = new THREE.Shape();
  17301. tmpShape.actions = tmpPath.actions;
  17302. tmpShape.curves = tmpPath.curves;
  17303. shapes.push( tmpShape );
  17304. return shapes;
  17305. };
  17306. if ( holesFirst ) {
  17307. tmpShape = new THREE.Shape();
  17308. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17309. tmpPath = subPaths[ i ];
  17310. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17311. tmpShape.actions = tmpPath.actions;
  17312. tmpShape.curves = tmpPath.curves;
  17313. shapes.push( tmpShape );
  17314. tmpShape = new THREE.Shape();
  17315. //console.log('cw', i);
  17316. } else {
  17317. tmpShape.holes.push( tmpPath );
  17318. //console.log('ccw', i);
  17319. }
  17320. }
  17321. } else {
  17322. // Shapes first
  17323. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17324. tmpPath = subPaths[ i ];
  17325. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17326. if ( tmpShape ) shapes.push( tmpShape );
  17327. tmpShape = new THREE.Shape();
  17328. tmpShape.actions = tmpPath.actions;
  17329. tmpShape.curves = tmpPath.curves;
  17330. } else {
  17331. tmpShape.holes.push( tmpPath );
  17332. }
  17333. }
  17334. shapes.push( tmpShape );
  17335. }
  17336. //console.log("shape", shapes);
  17337. return shapes;
  17338. };
  17339. /**
  17340. * @author zz85 / http://www.lab4games.net/zz85/blog
  17341. * Defines a 2d shape plane using paths.
  17342. **/
  17343. // STEP 1 Create a path.
  17344. // STEP 2 Turn path into shape.
  17345. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17346. // STEP 3a - Extract points from each shape, turn to vertices
  17347. // STEP 3b - Triangulate each shape, add faces.
  17348. THREE.Shape = function ( ) {
  17349. THREE.Path.apply( this, arguments );
  17350. this.holes = [];
  17351. };
  17352. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17353. // Convenience method to return ExtrudeGeometry
  17354. THREE.Shape.prototype.extrude = function ( options ) {
  17355. var extruded = new THREE.ExtrudeGeometry( this, options );
  17356. return extruded;
  17357. };
  17358. // Convenience method to return ShapeGeometry
  17359. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17360. var geometry = new THREE.ShapeGeometry( this, options );
  17361. return geometry;
  17362. };
  17363. // Get points of holes
  17364. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17365. var i, il = this.holes.length, holesPts = [];
  17366. for ( i = 0; i < il; i ++ ) {
  17367. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17368. }
  17369. return holesPts;
  17370. };
  17371. // Get points of holes (spaced by regular distance)
  17372. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17373. var i, il = this.holes.length, holesPts = [];
  17374. for ( i = 0; i < il; i ++ ) {
  17375. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17376. }
  17377. return holesPts;
  17378. };
  17379. // Get points of shape and holes (keypoints based on segments parameter)
  17380. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17381. return {
  17382. shape: this.getTransformedPoints( divisions ),
  17383. holes: this.getPointsHoles( divisions )
  17384. };
  17385. };
  17386. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17387. if (this.useSpacedPoints) {
  17388. return this.extractAllSpacedPoints(divisions);
  17389. }
  17390. return this.extractAllPoints(divisions);
  17391. };
  17392. //
  17393. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17394. //
  17395. // return {
  17396. //
  17397. // shape: this.transform( bend, divisions ),
  17398. // holes: this.getPointsHoles( divisions, bend )
  17399. //
  17400. // };
  17401. //
  17402. // };
  17403. // Get points of shape and holes (spaced by regular distance)
  17404. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17405. return {
  17406. shape: this.getTransformedSpacedPoints( divisions ),
  17407. holes: this.getSpacedPointsHoles( divisions )
  17408. };
  17409. };
  17410. /**************************************************************
  17411. * Utils
  17412. **************************************************************/
  17413. THREE.Shape.Utils = {
  17414. /*
  17415. contour - array of vector2 for contour
  17416. holes - array of array of vector2
  17417. */
  17418. removeHoles: function ( contour, holes ) {
  17419. var shape = contour.concat(); // work on this shape
  17420. var allpoints = shape.concat();
  17421. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17422. var prevShapeVert, nextShapeVert,
  17423. prevHoleVert, nextHoleVert,
  17424. holeIndex, shapeIndex,
  17425. shapeId, shapeGroup,
  17426. h, h2,
  17427. hole, shortest, d,
  17428. p, pts1, pts2,
  17429. tmpShape1, tmpShape2,
  17430. tmpHole1, tmpHole2,
  17431. verts = [];
  17432. for ( h = 0; h < holes.length; h ++ ) {
  17433. hole = holes[ h ];
  17434. /*
  17435. shapeholes[ h ].concat(); // preserves original
  17436. holes.push( hole );
  17437. */
  17438. Array.prototype.push.apply( allpoints, hole );
  17439. shortest = Number.POSITIVE_INFINITY;
  17440. // Find the shortest pair of pts between shape and hole
  17441. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17442. // Using distanceToSquared() intead of distanceTo() should speed a little
  17443. // since running square roots operations are reduced.
  17444. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17445. pts1 = hole[ h2 ];
  17446. var dist = [];
  17447. for ( p = 0; p < shape.length; p++ ) {
  17448. pts2 = shape[ p ];
  17449. d = pts1.distanceToSquared( pts2 );
  17450. dist.push( d );
  17451. if ( d < shortest ) {
  17452. shortest = d;
  17453. holeIndex = h2;
  17454. shapeIndex = p;
  17455. }
  17456. }
  17457. }
  17458. //console.log("shortest", shortest, dist);
  17459. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17460. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17461. var areaapts = [
  17462. hole[ holeIndex ],
  17463. shape[ shapeIndex ],
  17464. shape[ prevShapeVert ]
  17465. ];
  17466. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17467. var areabpts = [
  17468. hole[ holeIndex ],
  17469. hole[ prevHoleVert ],
  17470. shape[ shapeIndex ]
  17471. ];
  17472. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17473. var shapeOffset = 1;
  17474. var holeOffset = -1;
  17475. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17476. shapeIndex += shapeOffset;
  17477. holeIndex += holeOffset;
  17478. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17479. shapeIndex %= shape.length;
  17480. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17481. holeIndex %= hole.length;
  17482. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17483. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17484. areaapts = [
  17485. hole[ holeIndex ],
  17486. shape[ shapeIndex ],
  17487. shape[ prevShapeVert ]
  17488. ];
  17489. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17490. areabpts = [
  17491. hole[ holeIndex ],
  17492. hole[ prevHoleVert ],
  17493. shape[ shapeIndex ]
  17494. ];
  17495. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17496. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17497. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17498. // In case areas are not correct.
  17499. //console.log("USE THIS");
  17500. shapeIndex = oldShapeIndex;
  17501. holeIndex = oldHoleIndex ;
  17502. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17503. shapeIndex %= shape.length;
  17504. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17505. holeIndex %= hole.length;
  17506. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17507. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17508. } else {
  17509. //console.log("USE THAT ")
  17510. }
  17511. tmpShape1 = shape.slice( 0, shapeIndex );
  17512. tmpShape2 = shape.slice( shapeIndex );
  17513. tmpHole1 = hole.slice( holeIndex );
  17514. tmpHole2 = hole.slice( 0, holeIndex );
  17515. // Should check orders here again?
  17516. var trianglea = [
  17517. hole[ holeIndex ],
  17518. shape[ shapeIndex ],
  17519. shape[ prevShapeVert ]
  17520. ];
  17521. var triangleb = [
  17522. hole[ holeIndex ] ,
  17523. hole[ prevHoleVert ],
  17524. shape[ shapeIndex ]
  17525. ];
  17526. verts.push( trianglea );
  17527. verts.push( triangleb );
  17528. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17529. }
  17530. return {
  17531. shape:shape, /* shape with no holes */
  17532. isolatedPts: verts, /* isolated faces */
  17533. allpoints: allpoints
  17534. }
  17535. },
  17536. triangulateShape: function ( contour, holes ) {
  17537. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17538. var shape = shapeWithoutHoles.shape,
  17539. allpoints = shapeWithoutHoles.allpoints,
  17540. isolatedPts = shapeWithoutHoles.isolatedPts;
  17541. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17542. // 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.
  17543. //console.log( "triangles",triangles, triangles.length );
  17544. //console.log( "allpoints",allpoints, allpoints.length );
  17545. var i, il, f, face,
  17546. key, index,
  17547. allPointsMap = {},
  17548. isolatedPointsMap = {};
  17549. // prepare all points map
  17550. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17551. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17552. if ( allPointsMap[ key ] !== undefined ) {
  17553. console.log( "Duplicate point", key );
  17554. }
  17555. allPointsMap[ key ] = i;
  17556. }
  17557. // check all face vertices against all points map
  17558. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17559. face = triangles[ i ];
  17560. for ( f = 0; f < 3; f ++ ) {
  17561. key = face[ f ].x + ":" + face[ f ].y;
  17562. index = allPointsMap[ key ];
  17563. if ( index !== undefined ) {
  17564. face[ f ] = index;
  17565. }
  17566. }
  17567. }
  17568. // check isolated points vertices against all points map
  17569. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17570. face = isolatedPts[ i ];
  17571. for ( f = 0; f < 3; f ++ ) {
  17572. key = face[ f ].x + ":" + face[ f ].y;
  17573. index = allPointsMap[ key ];
  17574. if ( index !== undefined ) {
  17575. face[ f ] = index;
  17576. }
  17577. }
  17578. }
  17579. return triangles.concat( isolatedPts );
  17580. }, // end triangulate shapes
  17581. /*
  17582. triangulate2 : function( pts, holes ) {
  17583. // For use with Poly2Tri.js
  17584. var allpts = pts.concat();
  17585. var shape = [];
  17586. for (var p in pts) {
  17587. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17588. }
  17589. var swctx = new js.poly2tri.SweepContext(shape);
  17590. for (var h in holes) {
  17591. var aHole = holes[h];
  17592. var newHole = []
  17593. for (i in aHole) {
  17594. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17595. allpts.push(aHole[i]);
  17596. }
  17597. swctx.AddHole(newHole);
  17598. }
  17599. var find;
  17600. var findIndexForPt = function (pt) {
  17601. find = new THREE.Vector2(pt.x, pt.y);
  17602. var p;
  17603. for (p=0, pl = allpts.length; p<pl; p++) {
  17604. if (allpts[p].equals(find)) return p;
  17605. }
  17606. return -1;
  17607. };
  17608. // triangulate
  17609. js.poly2tri.sweep.Triangulate(swctx);
  17610. var triangles = swctx.GetTriangles();
  17611. var tr ;
  17612. var facesPts = [];
  17613. for (var t in triangles) {
  17614. tr = triangles[t];
  17615. facesPts.push([
  17616. findIndexForPt(tr.GetPoint(0)),
  17617. findIndexForPt(tr.GetPoint(1)),
  17618. findIndexForPt(tr.GetPoint(2))
  17619. ]);
  17620. }
  17621. // console.log(facesPts);
  17622. // console.log("triangles", triangles.length, triangles);
  17623. // Returns array of faces with 3 element each
  17624. return facesPts;
  17625. },
  17626. */
  17627. isClockWise: function ( pts ) {
  17628. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17629. },
  17630. // Bezier Curves formulas obtained from
  17631. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17632. // Quad Bezier Functions
  17633. b2p0: function ( t, p ) {
  17634. var k = 1 - t;
  17635. return k * k * p;
  17636. },
  17637. b2p1: function ( t, p ) {
  17638. return 2 * ( 1 - t ) * t * p;
  17639. },
  17640. b2p2: function ( t, p ) {
  17641. return t * t * p;
  17642. },
  17643. b2: function ( t, p0, p1, p2 ) {
  17644. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17645. },
  17646. // Cubic Bezier Functions
  17647. b3p0: function ( t, p ) {
  17648. var k = 1 - t;
  17649. return k * k * k * p;
  17650. },
  17651. b3p1: function ( t, p ) {
  17652. var k = 1 - t;
  17653. return 3 * k * k * t * p;
  17654. },
  17655. b3p2: function ( t, p ) {
  17656. var k = 1 - t;
  17657. return 3 * k * t * t * p;
  17658. },
  17659. b3p3: function ( t, p ) {
  17660. return t * t * t * p;
  17661. },
  17662. b3: function ( t, p0, p1, p2, p3 ) {
  17663. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17664. }
  17665. };
  17666. /**
  17667. * @author mikael emtinger / http://gomo.se/
  17668. */
  17669. THREE.AnimationHandler = (function() {
  17670. var playing = [];
  17671. var library = {};
  17672. var that = {};
  17673. //--- update ---
  17674. that.update = function( deltaTimeMS ) {
  17675. for( var i = 0; i < playing.length; i ++ )
  17676. playing[ i ].update( deltaTimeMS );
  17677. };
  17678. //--- add ---
  17679. that.addToUpdate = function( animation ) {
  17680. if ( playing.indexOf( animation ) === -1 )
  17681. playing.push( animation );
  17682. };
  17683. //--- remove ---
  17684. that.removeFromUpdate = function( animation ) {
  17685. var index = playing.indexOf( animation );
  17686. if( index !== -1 )
  17687. playing.splice( index, 1 );
  17688. };
  17689. //--- add ---
  17690. that.add = function( data ) {
  17691. if ( library[ data.name ] !== undefined )
  17692. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17693. library[ data.name ] = data;
  17694. initData( data );
  17695. };
  17696. //--- get ---
  17697. that.get = function( name ) {
  17698. if ( typeof name === "string" ) {
  17699. if ( library[ name ] ) {
  17700. return library[ name ];
  17701. } else {
  17702. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17703. return null;
  17704. }
  17705. } else {
  17706. // todo: add simple tween library
  17707. }
  17708. };
  17709. //--- parse ---
  17710. that.parse = function( root ) {
  17711. // setup hierarchy
  17712. var hierarchy = [];
  17713. if ( root instanceof THREE.SkinnedMesh ) {
  17714. for( var b = 0; b < root.bones.length; b++ ) {
  17715. hierarchy.push( root.bones[ b ] );
  17716. }
  17717. } else {
  17718. parseRecurseHierarchy( root, hierarchy );
  17719. }
  17720. return hierarchy;
  17721. };
  17722. var parseRecurseHierarchy = function( root, hierarchy ) {
  17723. hierarchy.push( root );
  17724. for( var c = 0; c < root.children.length; c++ )
  17725. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17726. }
  17727. //--- init data ---
  17728. var initData = function( data ) {
  17729. if( data.initialized === true )
  17730. return;
  17731. // loop through all keys
  17732. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17733. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17734. // remove minus times
  17735. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17736. data.hierarchy[ h ].keys[ k ].time = 0;
  17737. // create quaternions
  17738. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17739. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17740. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17741. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17742. }
  17743. }
  17744. // prepare morph target keys
  17745. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17746. // get all used
  17747. var usedMorphTargets = {};
  17748. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17749. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17750. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17751. usedMorphTargets[ morphTargetName ] = -1;
  17752. }
  17753. }
  17754. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17755. // set all used on all frames
  17756. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17757. var influences = {};
  17758. for ( var morphTargetName in usedMorphTargets ) {
  17759. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17760. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17761. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17762. break;
  17763. }
  17764. }
  17765. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17766. influences[ morphTargetName ] = 0;
  17767. }
  17768. }
  17769. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17770. }
  17771. }
  17772. // remove all keys that are on the same time
  17773. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17774. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17775. data.hierarchy[ h ].keys.splice( k, 1 );
  17776. k --;
  17777. }
  17778. }
  17779. // set index
  17780. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17781. data.hierarchy[ h ].keys[ k ].index = k;
  17782. }
  17783. }
  17784. // JIT
  17785. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17786. data.JIT = {};
  17787. data.JIT.hierarchy = [];
  17788. for( var h = 0; h < data.hierarchy.length; h ++ )
  17789. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17790. // done
  17791. data.initialized = true;
  17792. };
  17793. // interpolation types
  17794. that.LINEAR = 0;
  17795. that.CATMULLROM = 1;
  17796. that.CATMULLROM_FORWARD = 2;
  17797. return that;
  17798. }());
  17799. /**
  17800. * @author mikael emtinger / http://gomo.se/
  17801. * @author mrdoob / http://mrdoob.com/
  17802. * @author alteredq / http://alteredqualia.com/
  17803. */
  17804. THREE.Animation = function ( root, name, interpolationType ) {
  17805. this.root = root;
  17806. this.data = THREE.AnimationHandler.get( name );
  17807. this.hierarchy = THREE.AnimationHandler.parse( root );
  17808. this.currentTime = 0;
  17809. this.timeScale = 1;
  17810. this.isPlaying = false;
  17811. this.isPaused = true;
  17812. this.loop = true;
  17813. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17814. this.points = [];
  17815. this.target = new THREE.Vector3();
  17816. };
  17817. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17818. if ( this.isPlaying === false ) {
  17819. this.isPlaying = true;
  17820. this.loop = loop !== undefined ? loop : true;
  17821. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17822. // reset key cache
  17823. var h, hl = this.hierarchy.length,
  17824. object;
  17825. for ( h = 0; h < hl; h ++ ) {
  17826. object = this.hierarchy[ h ];
  17827. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17828. object.useQuaternion = true;
  17829. }
  17830. object.matrixAutoUpdate = true;
  17831. if ( object.animationCache === undefined ) {
  17832. object.animationCache = {};
  17833. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17834. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17835. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17836. }
  17837. var prevKey = object.animationCache.prevKey;
  17838. var nextKey = object.animationCache.nextKey;
  17839. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17840. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17841. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17842. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17843. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17844. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17845. }
  17846. this.update( 0 );
  17847. }
  17848. this.isPaused = false;
  17849. THREE.AnimationHandler.addToUpdate( this );
  17850. };
  17851. THREE.Animation.prototype.pause = function() {
  17852. if ( this.isPaused === true ) {
  17853. THREE.AnimationHandler.addToUpdate( this );
  17854. } else {
  17855. THREE.AnimationHandler.removeFromUpdate( this );
  17856. }
  17857. this.isPaused = !this.isPaused;
  17858. };
  17859. THREE.Animation.prototype.stop = function() {
  17860. this.isPlaying = false;
  17861. this.isPaused = false;
  17862. THREE.AnimationHandler.removeFromUpdate( this );
  17863. };
  17864. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17865. // early out
  17866. if ( this.isPlaying === false ) return;
  17867. // vars
  17868. var types = [ "pos", "rot", "scl" ];
  17869. var type;
  17870. var scale;
  17871. var vector;
  17872. var prevXYZ, nextXYZ;
  17873. var prevKey, nextKey;
  17874. var object;
  17875. var animationCache;
  17876. var frame;
  17877. var JIThierarchy = this.data.JIT.hierarchy;
  17878. var currentTime, unloopedCurrentTime;
  17879. var currentPoint, forwardPoint, angle;
  17880. this.currentTime += deltaTimeMS * this.timeScale;
  17881. unloopedCurrentTime = this.currentTime;
  17882. currentTime = this.currentTime = this.currentTime % this.data.length;
  17883. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17884. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17885. object = this.hierarchy[ h ];
  17886. animationCache = object.animationCache;
  17887. // loop through pos/rot/scl
  17888. for ( var t = 0; t < 3; t ++ ) {
  17889. // get keys
  17890. type = types[ t ];
  17891. prevKey = animationCache.prevKey[ type ];
  17892. nextKey = animationCache.nextKey[ type ];
  17893. // switch keys?
  17894. if ( nextKey.time <= unloopedCurrentTime ) {
  17895. // did we loop?
  17896. if ( currentTime < unloopedCurrentTime ) {
  17897. if ( this.loop ) {
  17898. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17899. nextKey = this.getNextKeyWith( type, h, 1 );
  17900. while( nextKey.time < currentTime ) {
  17901. prevKey = nextKey;
  17902. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17903. }
  17904. } else {
  17905. this.stop();
  17906. return;
  17907. }
  17908. } else {
  17909. do {
  17910. prevKey = nextKey;
  17911. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17912. } while( nextKey.time < currentTime )
  17913. }
  17914. animationCache.prevKey[ type ] = prevKey;
  17915. animationCache.nextKey[ type ] = nextKey;
  17916. }
  17917. object.matrixAutoUpdate = true;
  17918. object.matrixWorldNeedsUpdate = true;
  17919. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17920. prevXYZ = prevKey[ type ];
  17921. nextXYZ = nextKey[ type ];
  17922. // check scale error
  17923. if ( scale < 0 || scale > 1 ) {
  17924. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17925. scale = scale < 0 ? 0 : 1;
  17926. }
  17927. // interpolate
  17928. if ( type === "pos" ) {
  17929. vector = object.position;
  17930. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17931. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17932. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17933. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17934. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17935. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17936. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17937. this.points[ 1 ] = prevXYZ;
  17938. this.points[ 2 ] = nextXYZ;
  17939. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17940. scale = scale * 0.33 + 0.33;
  17941. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17942. vector.x = currentPoint[ 0 ];
  17943. vector.y = currentPoint[ 1 ];
  17944. vector.z = currentPoint[ 2 ];
  17945. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17946. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17947. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17948. this.target.subSelf( vector );
  17949. this.target.y = 0;
  17950. this.target.normalize();
  17951. angle = Math.atan2( this.target.x, this.target.z );
  17952. object.rotation.set( 0, angle, 0 );
  17953. }
  17954. }
  17955. } else if ( type === "rot" ) {
  17956. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17957. } else if ( type === "scl" ) {
  17958. vector = object.scale;
  17959. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17960. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17961. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17962. }
  17963. }
  17964. }
  17965. };
  17966. // Catmull-Rom spline
  17967. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17968. var c = [], v3 = [],
  17969. point, intPoint, weight, w2, w3,
  17970. pa, pb, pc, pd;
  17971. point = ( points.length - 1 ) * scale;
  17972. intPoint = Math.floor( point );
  17973. weight = point - intPoint;
  17974. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17975. c[ 1 ] = intPoint;
  17976. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17977. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17978. pa = points[ c[ 0 ] ];
  17979. pb = points[ c[ 1 ] ];
  17980. pc = points[ c[ 2 ] ];
  17981. pd = points[ c[ 3 ] ];
  17982. w2 = weight * weight;
  17983. w3 = weight * w2;
  17984. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17985. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17986. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17987. return v3;
  17988. };
  17989. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17990. var v0 = ( p2 - p0 ) * 0.5,
  17991. v1 = ( p3 - p1 ) * 0.5;
  17992. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17993. };
  17994. // Get next key with
  17995. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17996. var keys = this.data.hierarchy[ h ].keys;
  17997. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17998. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17999. key = key < keys.length - 1 ? key : keys.length - 1;
  18000. } else {
  18001. key = key % keys.length;
  18002. }
  18003. for ( ; key < keys.length; key++ ) {
  18004. if ( keys[ key ][ type ] !== undefined ) {
  18005. return keys[ key ];
  18006. }
  18007. }
  18008. return this.data.hierarchy[ h ].keys[ 0 ];
  18009. };
  18010. // Get previous key with
  18011. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18012. var keys = this.data.hierarchy[ h ].keys;
  18013. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18014. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18015. key = key > 0 ? key : 0;
  18016. } else {
  18017. key = key >= 0 ? key : key + keys.length;
  18018. }
  18019. for ( ; key >= 0; key -- ) {
  18020. if ( keys[ key ][ type ] !== undefined ) {
  18021. return keys[ key ];
  18022. }
  18023. }
  18024. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18025. };
  18026. /**
  18027. * @author mikael emtinger / http://gomo.se/
  18028. * @author mrdoob / http://mrdoob.com/
  18029. * @author alteredq / http://alteredqualia.com/
  18030. * @author khang duong
  18031. * @author erik kitson
  18032. */
  18033. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18034. this.root = root;
  18035. this.data = THREE.AnimationHandler.get( data );
  18036. this.hierarchy = THREE.AnimationHandler.parse( root );
  18037. this.currentTime = 0;
  18038. this.timeScale = 0.001;
  18039. this.isPlaying = false;
  18040. this.isPaused = true;
  18041. this.loop = true;
  18042. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18043. // initialize to first keyframes
  18044. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18045. var keys = this.data.hierarchy[h].keys,
  18046. sids = this.data.hierarchy[h].sids,
  18047. obj = this.hierarchy[h];
  18048. if ( keys.length && sids ) {
  18049. for ( var s = 0; s < sids.length; s++ ) {
  18050. var sid = sids[ s ],
  18051. next = this.getNextKeyWith( sid, h, 0 );
  18052. if ( next ) {
  18053. next.apply( sid );
  18054. }
  18055. }
  18056. obj.matrixAutoUpdate = false;
  18057. this.data.hierarchy[h].node.updateMatrix();
  18058. obj.matrixWorldNeedsUpdate = true;
  18059. }
  18060. }
  18061. };
  18062. // Play
  18063. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18064. if( !this.isPlaying ) {
  18065. this.isPlaying = true;
  18066. this.loop = loop !== undefined ? loop : true;
  18067. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18068. this.startTimeMs = startTimeMS;
  18069. this.startTime = 10000000;
  18070. this.endTime = -this.startTime;
  18071. // reset key cache
  18072. var h, hl = this.hierarchy.length,
  18073. object,
  18074. node;
  18075. for ( h = 0; h < hl; h++ ) {
  18076. object = this.hierarchy[ h ];
  18077. node = this.data.hierarchy[ h ];
  18078. object.useQuaternion = true;
  18079. if ( node.animationCache === undefined ) {
  18080. node.animationCache = {};
  18081. node.animationCache.prevKey = null;
  18082. node.animationCache.nextKey = null;
  18083. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18084. }
  18085. var keys = this.data.hierarchy[h].keys;
  18086. if (keys.length) {
  18087. node.animationCache.prevKey = keys[ 0 ];
  18088. node.animationCache.nextKey = keys[ 1 ];
  18089. this.startTime = Math.min( keys[0].time, this.startTime );
  18090. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18091. }
  18092. }
  18093. this.update( 0 );
  18094. }
  18095. this.isPaused = false;
  18096. THREE.AnimationHandler.addToUpdate( this );
  18097. };
  18098. // Pause
  18099. THREE.KeyFrameAnimation.prototype.pause = function() {
  18100. if( this.isPaused ) {
  18101. THREE.AnimationHandler.addToUpdate( this );
  18102. } else {
  18103. THREE.AnimationHandler.removeFromUpdate( this );
  18104. }
  18105. this.isPaused = !this.isPaused;
  18106. };
  18107. // Stop
  18108. THREE.KeyFrameAnimation.prototype.stop = function() {
  18109. this.isPlaying = false;
  18110. this.isPaused = false;
  18111. THREE.AnimationHandler.removeFromUpdate( this );
  18112. // reset JIT matrix and remove cache
  18113. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18114. var obj = this.hierarchy[ h ];
  18115. var node = this.data.hierarchy[ h ];
  18116. if ( node.animationCache !== undefined ) {
  18117. var original = node.animationCache.originalMatrix;
  18118. if( obj instanceof THREE.Bone ) {
  18119. original.copy( obj.skinMatrix );
  18120. obj.skinMatrix = original;
  18121. } else {
  18122. original.copy( obj.matrix );
  18123. obj.matrix = original;
  18124. }
  18125. delete node.animationCache;
  18126. }
  18127. }
  18128. };
  18129. // Update
  18130. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18131. // early out
  18132. if( !this.isPlaying ) return;
  18133. // vars
  18134. var prevKey, nextKey;
  18135. var object;
  18136. var node;
  18137. var frame;
  18138. var JIThierarchy = this.data.JIT.hierarchy;
  18139. var currentTime, unloopedCurrentTime;
  18140. var looped;
  18141. // update
  18142. this.currentTime += deltaTimeMS * this.timeScale;
  18143. unloopedCurrentTime = this.currentTime;
  18144. currentTime = this.currentTime = this.currentTime % this.data.length;
  18145. // if looped around, the current time should be based on the startTime
  18146. if ( currentTime < this.startTimeMs ) {
  18147. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18148. }
  18149. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18150. looped = currentTime < unloopedCurrentTime;
  18151. if ( looped && !this.loop ) {
  18152. // Set the animation to the last keyframes and stop
  18153. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18154. var keys = this.data.hierarchy[h].keys,
  18155. sids = this.data.hierarchy[h].sids,
  18156. end = keys.length-1,
  18157. obj = this.hierarchy[h];
  18158. if ( keys.length ) {
  18159. for ( var s = 0; s < sids.length; s++ ) {
  18160. var sid = sids[ s ],
  18161. prev = this.getPrevKeyWith( sid, h, end );
  18162. if ( prev ) {
  18163. prev.apply( sid );
  18164. }
  18165. }
  18166. this.data.hierarchy[h].node.updateMatrix();
  18167. obj.matrixWorldNeedsUpdate = true;
  18168. }
  18169. }
  18170. this.stop();
  18171. return;
  18172. }
  18173. // check pre-infinity
  18174. if ( currentTime < this.startTime ) {
  18175. return;
  18176. }
  18177. // update
  18178. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18179. object = this.hierarchy[ h ];
  18180. node = this.data.hierarchy[ h ];
  18181. var keys = node.keys,
  18182. animationCache = node.animationCache;
  18183. // use JIT?
  18184. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18185. if( object instanceof THREE.Bone ) {
  18186. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18187. object.matrixWorldNeedsUpdate = false;
  18188. } else {
  18189. object.matrix = JIThierarchy[ h ][ frame ];
  18190. object.matrixWorldNeedsUpdate = true;
  18191. }
  18192. // use interpolation
  18193. } else if ( keys.length ) {
  18194. // make sure so original matrix and not JIT matrix is set
  18195. if ( this.JITCompile && animationCache ) {
  18196. if( object instanceof THREE.Bone ) {
  18197. object.skinMatrix = animationCache.originalMatrix;
  18198. } else {
  18199. object.matrix = animationCache.originalMatrix;
  18200. }
  18201. }
  18202. prevKey = animationCache.prevKey;
  18203. nextKey = animationCache.nextKey;
  18204. if ( prevKey && nextKey ) {
  18205. // switch keys?
  18206. if ( nextKey.time <= unloopedCurrentTime ) {
  18207. // did we loop?
  18208. if ( looped && this.loop ) {
  18209. prevKey = keys[ 0 ];
  18210. nextKey = keys[ 1 ];
  18211. while ( nextKey.time < currentTime ) {
  18212. prevKey = nextKey;
  18213. nextKey = keys[ prevKey.index + 1 ];
  18214. }
  18215. } else if ( !looped ) {
  18216. var lastIndex = keys.length - 1;
  18217. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18218. prevKey = nextKey;
  18219. nextKey = keys[ prevKey.index + 1 ];
  18220. }
  18221. }
  18222. animationCache.prevKey = prevKey;
  18223. animationCache.nextKey = nextKey;
  18224. }
  18225. if(nextKey.time >= currentTime)
  18226. prevKey.interpolate( nextKey, currentTime );
  18227. else
  18228. prevKey.interpolate( nextKey, nextKey.time);
  18229. }
  18230. this.data.hierarchy[h].node.updateMatrix();
  18231. object.matrixWorldNeedsUpdate = true;
  18232. }
  18233. }
  18234. // update JIT?
  18235. if ( this.JITCompile ) {
  18236. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18237. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18238. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18239. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18240. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18241. } else {
  18242. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18243. }
  18244. }
  18245. }
  18246. }
  18247. };
  18248. // Get next key with
  18249. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18250. var keys = this.data.hierarchy[ h ].keys;
  18251. key = key % keys.length;
  18252. for ( ; key < keys.length; key++ ) {
  18253. if ( keys[ key ].hasTarget( sid ) ) {
  18254. return keys[ key ];
  18255. }
  18256. }
  18257. return keys[ 0 ];
  18258. };
  18259. // Get previous key with
  18260. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18261. var keys = this.data.hierarchy[ h ].keys;
  18262. key = key >= 0 ? key : key + keys.length;
  18263. for ( ; key >= 0; key-- ) {
  18264. if ( keys[ key ].hasTarget( sid ) ) {
  18265. return keys[ key ];
  18266. }
  18267. }
  18268. return keys[ keys.length - 1 ];
  18269. };
  18270. /**
  18271. * Camera for rendering cube maps
  18272. * - renders scene into axis-aligned cube
  18273. *
  18274. * @author alteredq / http://alteredqualia.com/
  18275. */
  18276. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18277. THREE.Object3D.call( this );
  18278. var fov = 90, aspect = 1;
  18279. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18280. cameraPX.up.set( 0, -1, 0 );
  18281. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18282. this.add( cameraPX );
  18283. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18284. cameraNX.up.set( 0, -1, 0 );
  18285. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18286. this.add( cameraNX );
  18287. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18288. cameraPY.up.set( 0, 0, 1 );
  18289. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18290. this.add( cameraPY );
  18291. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18292. cameraNY.up.set( 0, 0, -1 );
  18293. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18294. this.add( cameraNY );
  18295. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18296. cameraPZ.up.set( 0, -1, 0 );
  18297. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18298. this.add( cameraPZ );
  18299. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18300. cameraNZ.up.set( 0, -1, 0 );
  18301. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18302. this.add( cameraNZ );
  18303. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18304. this.updateCubeMap = function ( renderer, scene ) {
  18305. var renderTarget = this.renderTarget;
  18306. var generateMipmaps = renderTarget.generateMipmaps;
  18307. renderTarget.generateMipmaps = false;
  18308. renderTarget.activeCubeFace = 0;
  18309. renderer.render( scene, cameraPX, renderTarget );
  18310. renderTarget.activeCubeFace = 1;
  18311. renderer.render( scene, cameraNX, renderTarget );
  18312. renderTarget.activeCubeFace = 2;
  18313. renderer.render( scene, cameraPY, renderTarget );
  18314. renderTarget.activeCubeFace = 3;
  18315. renderer.render( scene, cameraNY, renderTarget );
  18316. renderTarget.activeCubeFace = 4;
  18317. renderer.render( scene, cameraPZ, renderTarget );
  18318. renderTarget.generateMipmaps = generateMipmaps;
  18319. renderTarget.activeCubeFace = 5;
  18320. renderer.render( scene, cameraNZ, renderTarget );
  18321. };
  18322. };
  18323. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18324. /*
  18325. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18326. *
  18327. * A general perpose camera, for setting FOV, Lens Focal Length,
  18328. * and switching between perspective and orthographic views easily.
  18329. * Use this only if you do not wish to manage
  18330. * both a Orthographic and Perspective Camera
  18331. *
  18332. */
  18333. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18334. THREE.Camera.call( this );
  18335. this.fov = fov;
  18336. this.left = -width / 2;
  18337. this.right = width / 2
  18338. this.top = height / 2;
  18339. this.bottom = -height / 2;
  18340. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18341. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18342. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18343. this.zoom = 1;
  18344. this.toPerspective();
  18345. var aspect = width/height;
  18346. };
  18347. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18348. THREE.CombinedCamera.prototype.toPerspective = function () {
  18349. // Switches to the Perspective Camera
  18350. this.near = this.cameraP.near;
  18351. this.far = this.cameraP.far;
  18352. this.cameraP.fov = this.fov / this.zoom ;
  18353. this.cameraP.updateProjectionMatrix();
  18354. this.projectionMatrix = this.cameraP.projectionMatrix;
  18355. this.inPerspectiveMode = true;
  18356. this.inOrthographicMode = false;
  18357. };
  18358. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18359. // Switches to the Orthographic camera estimating viewport from Perspective
  18360. var fov = this.fov;
  18361. var aspect = this.cameraP.aspect;
  18362. var near = this.cameraP.near;
  18363. var far = this.cameraP.far;
  18364. // The size that we set is the mid plane of the viewing frustum
  18365. var hyperfocus = ( near + far ) / 2;
  18366. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18367. var planeHeight = 2 * halfHeight;
  18368. var planeWidth = planeHeight * aspect;
  18369. var halfWidth = planeWidth / 2;
  18370. halfHeight /= this.zoom;
  18371. halfWidth /= this.zoom;
  18372. this.cameraO.left = -halfWidth;
  18373. this.cameraO.right = halfWidth;
  18374. this.cameraO.top = halfHeight;
  18375. this.cameraO.bottom = -halfHeight;
  18376. // this.cameraO.left = -farHalfWidth;
  18377. // this.cameraO.right = farHalfWidth;
  18378. // this.cameraO.top = farHalfHeight;
  18379. // this.cameraO.bottom = -farHalfHeight;
  18380. // this.cameraO.left = this.left / this.zoom;
  18381. // this.cameraO.right = this.right / this.zoom;
  18382. // this.cameraO.top = this.top / this.zoom;
  18383. // this.cameraO.bottom = this.bottom / this.zoom;
  18384. this.cameraO.updateProjectionMatrix();
  18385. this.near = this.cameraO.near;
  18386. this.far = this.cameraO.far;
  18387. this.projectionMatrix = this.cameraO.projectionMatrix;
  18388. this.inPerspectiveMode = false;
  18389. this.inOrthographicMode = true;
  18390. };
  18391. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18392. this.cameraP.aspect = width / height;
  18393. this.left = -width / 2;
  18394. this.right = width / 2
  18395. this.top = height / 2;
  18396. this.bottom = -height / 2;
  18397. };
  18398. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18399. this.fov = fov;
  18400. if ( this.inPerspectiveMode ) {
  18401. this.toPerspective();
  18402. } else {
  18403. this.toOrthographic();
  18404. }
  18405. };
  18406. // For mantaining similar API with PerspectiveCamera
  18407. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18408. if ( this.inPerspectiveMode ) {
  18409. this.toPerspective();
  18410. } else {
  18411. this.toPerspective();
  18412. this.toOrthographic();
  18413. }
  18414. };
  18415. /*
  18416. * Uses Focal Length (in mm) to estimate and set FOV
  18417. * 35mm (fullframe) camera is used if frame size is not specified;
  18418. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18419. */
  18420. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18421. if ( frameHeight === undefined ) frameHeight = 24;
  18422. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  18423. this.setFov( fov );
  18424. return fov;
  18425. };
  18426. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18427. this.zoom = zoom;
  18428. if ( this.inPerspectiveMode ) {
  18429. this.toPerspective();
  18430. } else {
  18431. this.toOrthographic();
  18432. }
  18433. };
  18434. THREE.CombinedCamera.prototype.toFrontView = function() {
  18435. this.rotation.x = 0;
  18436. this.rotation.y = 0;
  18437. this.rotation.z = 0;
  18438. // should we be modifing the matrix instead?
  18439. this.rotationAutoUpdate = false;
  18440. };
  18441. THREE.CombinedCamera.prototype.toBackView = function() {
  18442. this.rotation.x = 0;
  18443. this.rotation.y = Math.PI;
  18444. this.rotation.z = 0;
  18445. this.rotationAutoUpdate = false;
  18446. };
  18447. THREE.CombinedCamera.prototype.toLeftView = function() {
  18448. this.rotation.x = 0;
  18449. this.rotation.y = - Math.PI / 2;
  18450. this.rotation.z = 0;
  18451. this.rotationAutoUpdate = false;
  18452. };
  18453. THREE.CombinedCamera.prototype.toRightView = function() {
  18454. this.rotation.x = 0;
  18455. this.rotation.y = Math.PI / 2;
  18456. this.rotation.z = 0;
  18457. this.rotationAutoUpdate = false;
  18458. };
  18459. THREE.CombinedCamera.prototype.toTopView = function() {
  18460. this.rotation.x = - Math.PI / 2;
  18461. this.rotation.y = 0;
  18462. this.rotation.z = 0;
  18463. this.rotationAutoUpdate = false;
  18464. };
  18465. THREE.CombinedCamera.prototype.toBottomView = function() {
  18466. this.rotation.x = Math.PI / 2;
  18467. this.rotation.y = 0;
  18468. this.rotation.z = 0;
  18469. this.rotationAutoUpdate = false;
  18470. };
  18471. /**
  18472. * @author alteredq / http://alteredqualia.com/
  18473. *
  18474. * - 3d asterisk shape (for line pieces THREE.Line)
  18475. */
  18476. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18477. THREE.Geometry.call( this );
  18478. var sd = innerRadius;
  18479. var ed = outerRadius;
  18480. var sd2 = 0.707 * sd;
  18481. var ed2 = 0.707 * ed;
  18482. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18483. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18484. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18485. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18486. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18487. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18488. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18489. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18490. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18491. ];
  18492. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18493. var x = rays[ i ][ 0 ];
  18494. var y = rays[ i ][ 1 ];
  18495. var z = rays[ i ][ 2 ];
  18496. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18497. }
  18498. };
  18499. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18500. * @author hughes
  18501. */
  18502. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18503. THREE.Geometry.call( this );
  18504. radius = radius || 50;
  18505. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18506. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18507. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18508. var i, uvs = [],
  18509. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18510. this.vertices.push(center);
  18511. uvs.push( centerUV );
  18512. for ( i = 0; i <= segments; i ++ ) {
  18513. var vertex = new THREE.Vector3();
  18514. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18515. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18516. this.vertices.push( vertex );
  18517. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18518. }
  18519. var n = new THREE.Vector3( 0, 0, -1 );
  18520. for ( i = 1; i <= segments; i ++ ) {
  18521. var v1 = i;
  18522. var v2 = i + 1 ;
  18523. var v3 = 0;
  18524. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18525. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18526. }
  18527. this.computeCentroids();
  18528. this.computeFaceNormals();
  18529. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18530. };
  18531. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18532. /**
  18533. * @author mrdoob / http://mrdoob.com/
  18534. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18535. */
  18536. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18537. THREE.Geometry.call( this );
  18538. var scope = this;
  18539. this.width = width;
  18540. this.height = height;
  18541. this.depth = depth;
  18542. this.widthSegments = widthSegments || 1;
  18543. this.heightSegments = heightSegments || 1;
  18544. this.depthSegments = depthSegments || 1;
  18545. var width_half = this.width / 2;
  18546. var height_half = this.height / 2;
  18547. var depth_half = this.depth / 2;
  18548. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18549. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18550. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18551. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18552. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18553. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18554. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18555. var w, ix, iy,
  18556. gridX = scope.widthSegments,
  18557. gridY = scope.heightSegments,
  18558. width_half = width / 2,
  18559. height_half = height / 2,
  18560. offset = scope.vertices.length;
  18561. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18562. w = 'z';
  18563. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18564. w = 'y';
  18565. gridY = scope.depthSegments;
  18566. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18567. w = 'x';
  18568. gridX = scope.depthSegments;
  18569. }
  18570. var gridX1 = gridX + 1,
  18571. gridY1 = gridY + 1,
  18572. segment_width = width / gridX,
  18573. segment_height = height / gridY,
  18574. normal = new THREE.Vector3();
  18575. normal[ w ] = depth > 0 ? 1 : - 1;
  18576. for ( iy = 0; iy < gridY1; iy ++ ) {
  18577. for ( ix = 0; ix < gridX1; ix ++ ) {
  18578. var vector = new THREE.Vector3();
  18579. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18580. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18581. vector[ w ] = depth;
  18582. scope.vertices.push( vector );
  18583. }
  18584. }
  18585. for ( iy = 0; iy < gridY; iy++ ) {
  18586. for ( ix = 0; ix < gridX; ix++ ) {
  18587. var a = ix + gridX1 * iy;
  18588. var b = ix + gridX1 * ( iy + 1 );
  18589. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18590. var d = ( ix + 1 ) + gridX1 * iy;
  18591. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18592. face.normal.copy( normal );
  18593. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18594. face.materialIndex = materialIndex;
  18595. scope.faces.push( face );
  18596. scope.faceVertexUvs[ 0 ].push( [
  18597. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18598. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18599. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18600. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18601. ] );
  18602. }
  18603. }
  18604. }
  18605. this.computeCentroids();
  18606. this.mergeVertices();
  18607. };
  18608. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18609. /**
  18610. * @author mrdoob / http://mrdoob.com/
  18611. */
  18612. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18613. THREE.Geometry.call( this );
  18614. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18615. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18616. height = height !== undefined ? height : 100;
  18617. var heightHalf = height / 2;
  18618. var segmentsX = radiusSegments || 8;
  18619. var segmentsY = heightSegments || 1;
  18620. var x, y, vertices = [], uvs = [];
  18621. for ( y = 0; y <= segmentsY; y ++ ) {
  18622. var verticesRow = [];
  18623. var uvsRow = [];
  18624. var v = y / segmentsY;
  18625. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18626. for ( x = 0; x <= segmentsX; x ++ ) {
  18627. var u = x / segmentsX;
  18628. var vertex = new THREE.Vector3();
  18629. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18630. vertex.y = - v * height + heightHalf;
  18631. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18632. this.vertices.push( vertex );
  18633. verticesRow.push( this.vertices.length - 1 );
  18634. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18635. }
  18636. vertices.push( verticesRow );
  18637. uvs.push( uvsRow );
  18638. }
  18639. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18640. var na, nb;
  18641. for ( x = 0; x < segmentsX; x ++ ) {
  18642. if ( radiusTop !== 0 ) {
  18643. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18644. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18645. } else {
  18646. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18647. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18648. }
  18649. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18650. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18651. for ( y = 0; y < segmentsY; y ++ ) {
  18652. var v1 = vertices[ y ][ x ];
  18653. var v2 = vertices[ y + 1 ][ x ];
  18654. var v3 = vertices[ y + 1 ][ x + 1 ];
  18655. var v4 = vertices[ y ][ x + 1 ];
  18656. var n1 = na.clone();
  18657. var n2 = na.clone();
  18658. var n3 = nb.clone();
  18659. var n4 = nb.clone();
  18660. var uv1 = uvs[ y ][ x ].clone();
  18661. var uv2 = uvs[ y + 1 ][ x ].clone();
  18662. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18663. var uv4 = uvs[ y ][ x + 1 ].clone();
  18664. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18665. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18666. }
  18667. }
  18668. // top cap
  18669. if ( !openEnded && radiusTop > 0 ) {
  18670. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18671. for ( x = 0; x < segmentsX; x ++ ) {
  18672. var v1 = vertices[ 0 ][ x ];
  18673. var v2 = vertices[ 0 ][ x + 1 ];
  18674. var v3 = this.vertices.length - 1;
  18675. var n1 = new THREE.Vector3( 0, 1, 0 );
  18676. var n2 = new THREE.Vector3( 0, 1, 0 );
  18677. var n3 = new THREE.Vector3( 0, 1, 0 );
  18678. var uv1 = uvs[ 0 ][ x ].clone();
  18679. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18680. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18681. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18682. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18683. }
  18684. }
  18685. // bottom cap
  18686. if ( !openEnded && radiusBottom > 0 ) {
  18687. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18688. for ( x = 0; x < segmentsX; x ++ ) {
  18689. var v1 = vertices[ y ][ x + 1 ];
  18690. var v2 = vertices[ y ][ x ];
  18691. var v3 = this.vertices.length - 1;
  18692. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18693. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18694. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18695. var uv1 = uvs[ y ][ x + 1 ].clone();
  18696. var uv2 = uvs[ y ][ x ].clone();
  18697. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18698. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18699. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18700. }
  18701. }
  18702. this.computeCentroids();
  18703. this.computeFaceNormals();
  18704. }
  18705. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18706. /**
  18707. * @author zz85 / http://www.lab4games.net/zz85/blog
  18708. *
  18709. * Creates extruded geometry from a path shape.
  18710. *
  18711. * parameters = {
  18712. *
  18713. * size: <float>, // size of the text
  18714. * height: <float>, // thickness to extrude text
  18715. * curveSegments: <int>, // number of points on the curves
  18716. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18717. * amount: <int>, // Amount
  18718. *
  18719. * bevelEnabled: <bool>, // turn on bevel
  18720. * bevelThickness: <float>, // how deep into text bevel goes
  18721. * bevelSize: <float>, // how far from text outline is bevel
  18722. * bevelSegments: <int>, // number of bevel layers
  18723. *
  18724. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18725. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18726. *
  18727. * material: <int> // material index for front and back faces
  18728. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18729. * uvGenerator: <Object> // object that provides UV generator functions
  18730. *
  18731. * }
  18732. **/
  18733. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18734. if ( typeof( shapes ) === "undefined" ) {
  18735. shapes = [];
  18736. return;
  18737. }
  18738. THREE.Geometry.call( this );
  18739. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18740. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18741. this.addShapeList( shapes, options );
  18742. this.computeCentroids();
  18743. this.computeFaceNormals();
  18744. // can't really use automatic vertex normals
  18745. // as then front and back sides get smoothed too
  18746. // should do separate smoothing just for sides
  18747. //this.computeVertexNormals();
  18748. //console.log( "took", ( Date.now() - startTime ) );
  18749. };
  18750. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18751. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18752. var sl = shapes.length;
  18753. for ( var s = 0; s < sl; s ++ ) {
  18754. var shape = shapes[ s ];
  18755. this.addShape( shape, options );
  18756. }
  18757. };
  18758. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18759. var amount = options.amount !== undefined ? options.amount : 100;
  18760. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18761. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18762. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18763. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18764. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18765. var steps = options.steps !== undefined ? options.steps : 1;
  18766. var extrudePath = options.extrudePath;
  18767. var extrudePts, extrudeByPath = false;
  18768. var material = options.material;
  18769. var extrudeMaterial = options.extrudeMaterial;
  18770. // Use default WorldUVGenerator if no UV generators are specified.
  18771. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18772. var shapebb = this.shapebb;
  18773. //shapebb = shape.getBoundingBox();
  18774. var splineTube, binormal, normal, position2;
  18775. if ( extrudePath ) {
  18776. extrudePts = extrudePath.getSpacedPoints( steps );
  18777. extrudeByPath = true;
  18778. bevelEnabled = false; // bevels not supported for path extrusion
  18779. // SETUP TNB variables
  18780. // Reuse TNB from TubeGeomtry for now.
  18781. // TODO1 - have a .isClosed in spline?
  18782. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18783. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18784. binormal = new THREE.Vector3();
  18785. normal = new THREE.Vector3();
  18786. position2 = new THREE.Vector3();
  18787. }
  18788. // Safeguards if bevels are not enabled
  18789. if ( ! bevelEnabled ) {
  18790. bevelSegments = 0;
  18791. bevelThickness = 0;
  18792. bevelSize = 0;
  18793. }
  18794. // Variables initalization
  18795. var ahole, h, hl; // looping of holes
  18796. var scope = this;
  18797. var bevelPoints = [];
  18798. var shapesOffset = this.vertices.length;
  18799. var shapePoints = shape.extractPoints( curveSegments );
  18800. var vertices = shapePoints.shape;
  18801. var holes = shapePoints.holes;
  18802. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18803. if ( reverse ) {
  18804. vertices = vertices.reverse();
  18805. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18806. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18807. ahole = holes[ h ];
  18808. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18809. holes[ h ] = ahole.reverse();
  18810. }
  18811. }
  18812. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18813. }
  18814. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18815. /* Vertices */
  18816. var contour = vertices; // vertices has all points but contour has only points of circumference
  18817. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18818. ahole = holes[ h ];
  18819. vertices = vertices.concat( ahole );
  18820. }
  18821. function scalePt2 ( pt, vec, size ) {
  18822. if ( !vec ) console.log( "die" );
  18823. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18824. }
  18825. var b, bs, t, z,
  18826. vert, vlen = vertices.length,
  18827. face, flen = faces.length,
  18828. cont, clen = contour.length;
  18829. // Find directions for point movement
  18830. var RAD_TO_DEGREES = 180 / Math.PI;
  18831. function getBevelVec( pt_i, pt_j, pt_k ) {
  18832. // Algorithm 2
  18833. return getBevelVec2( pt_i, pt_j, pt_k );
  18834. }
  18835. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18836. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18837. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18838. if ( anglea > angleb ) {
  18839. angleb += Math.PI * 2;
  18840. }
  18841. var anglec = ( anglea + angleb ) / 2;
  18842. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18843. var x = - Math.cos( anglec );
  18844. var y = - Math.sin( anglec );
  18845. var vec = new THREE.Vector2( x, y ); //.normalize();
  18846. return vec;
  18847. }
  18848. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18849. var a = THREE.ExtrudeGeometry.__v1,
  18850. b = THREE.ExtrudeGeometry.__v2,
  18851. v_hat = THREE.ExtrudeGeometry.__v3,
  18852. w_hat = THREE.ExtrudeGeometry.__v4,
  18853. p = THREE.ExtrudeGeometry.__v5,
  18854. q = THREE.ExtrudeGeometry.__v6,
  18855. v, w,
  18856. v_dot_w_hat, q_sub_p_dot_w_hat,
  18857. s, intersection;
  18858. // good reading for line-line intersection
  18859. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18860. // define a as vector j->i
  18861. // define b as vectot k->i
  18862. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18863. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18864. // get unit vectors
  18865. v = a.normalize();
  18866. w = b.normalize();
  18867. // normals from pt i
  18868. v_hat.set( -v.y, v.x );
  18869. w_hat.set( w.y, -w.x );
  18870. // pts from i
  18871. p.copy( pt_i ).addSelf( v_hat );
  18872. q.copy( pt_i ).addSelf( w_hat );
  18873. if ( p.equals( q ) ) {
  18874. //console.log("Warning: lines are straight");
  18875. return w_hat.clone();
  18876. }
  18877. // Points from j, k. helps prevents points cross overover most of the time
  18878. p.copy( pt_j ).addSelf( v_hat );
  18879. q.copy( pt_k ).addSelf( w_hat );
  18880. v_dot_w_hat = v.dot( w_hat );
  18881. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18882. // We should not reach these conditions
  18883. if ( v_dot_w_hat === 0 ) {
  18884. console.log( "Either infinite or no solutions!" );
  18885. if ( q_sub_p_dot_w_hat === 0 ) {
  18886. console.log( "Its finite solutions." );
  18887. } else {
  18888. console.log( "Too bad, no solutions." );
  18889. }
  18890. }
  18891. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18892. if ( s < 0 ) {
  18893. // in case of emergecy, revert to algorithm 1.
  18894. return getBevelVec1( pt_i, pt_j, pt_k );
  18895. }
  18896. intersection = v.multiplyScalar( s ).addSelf( p );
  18897. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18898. }
  18899. var contourMovements = [];
  18900. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18901. if ( j === il ) j = 0;
  18902. if ( k === il ) k = 0;
  18903. // (j)---(i)---(k)
  18904. // console.log('i,j,k', i, j , k)
  18905. var pt_i = contour[ i ];
  18906. var pt_j = contour[ j ];
  18907. var pt_k = contour[ k ];
  18908. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18909. }
  18910. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18911. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18912. ahole = holes[ h ];
  18913. oneHoleMovements = [];
  18914. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18915. if ( j === il ) j = 0;
  18916. if ( k === il ) k = 0;
  18917. // (j)---(i)---(k)
  18918. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18919. }
  18920. holesMovements.push( oneHoleMovements );
  18921. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18922. }
  18923. // Loop bevelSegments, 1 for the front, 1 for the back
  18924. for ( b = 0; b < bevelSegments; b ++ ) {
  18925. //for ( b = bevelSegments; b > 0; b -- ) {
  18926. t = b / bevelSegments;
  18927. z = bevelThickness * ( 1 - t );
  18928. //z = bevelThickness * t;
  18929. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18930. //bs = bevelSize * t ; // linear
  18931. // contract shape
  18932. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18933. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18934. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18935. v( vert.x, vert.y, - z );
  18936. }
  18937. // expand holes
  18938. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18939. ahole = holes[ h ];
  18940. oneHoleMovements = holesMovements[ h ];
  18941. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18942. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18943. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18944. v( vert.x, vert.y, -z );
  18945. }
  18946. }
  18947. }
  18948. bs = bevelSize;
  18949. // Back facing vertices
  18950. for ( i = 0; i < vlen; i ++ ) {
  18951. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18952. if ( !extrudeByPath ) {
  18953. v( vert.x, vert.y, 0 );
  18954. } else {
  18955. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18956. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18957. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18958. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18959. v( position2.x, position2.y, position2.z );
  18960. }
  18961. }
  18962. // Add stepped vertices...
  18963. // Including front facing vertices
  18964. var s;
  18965. for ( s = 1; s <= steps; s ++ ) {
  18966. for ( i = 0; i < vlen; i ++ ) {
  18967. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18968. if ( !extrudeByPath ) {
  18969. v( vert.x, vert.y, amount / steps * s );
  18970. } else {
  18971. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18972. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18973. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18974. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18975. v( position2.x, position2.y, position2.z );
  18976. }
  18977. }
  18978. }
  18979. // Add bevel segments planes
  18980. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18981. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18982. t = b / bevelSegments;
  18983. z = bevelThickness * ( 1 - t );
  18984. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18985. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18986. // contract shape
  18987. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18988. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18989. v( vert.x, vert.y, amount + z );
  18990. }
  18991. // expand holes
  18992. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18993. ahole = holes[ h ];
  18994. oneHoleMovements = holesMovements[ h ];
  18995. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18996. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18997. if ( !extrudeByPath ) {
  18998. v( vert.x, vert.y, amount + z );
  18999. } else {
  19000. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19001. }
  19002. }
  19003. }
  19004. }
  19005. /* Faces */
  19006. // Top and bottom faces
  19007. buildLidFaces();
  19008. // Sides faces
  19009. buildSideFaces();
  19010. ///// Internal functions
  19011. function buildLidFaces() {
  19012. if ( bevelEnabled ) {
  19013. var layer = 0 ; // steps + 1
  19014. var offset = vlen * layer;
  19015. // Bottom faces
  19016. for ( i = 0; i < flen; i ++ ) {
  19017. face = faces[ i ];
  19018. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19019. }
  19020. layer = steps + bevelSegments * 2;
  19021. offset = vlen * layer;
  19022. // Top faces
  19023. for ( i = 0; i < flen; i ++ ) {
  19024. face = faces[ i ];
  19025. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19026. }
  19027. } else {
  19028. // Bottom faces
  19029. for ( i = 0; i < flen; i++ ) {
  19030. face = faces[ i ];
  19031. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19032. }
  19033. // Top faces
  19034. for ( i = 0; i < flen; i ++ ) {
  19035. face = faces[ i ];
  19036. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19037. }
  19038. }
  19039. }
  19040. // Create faces for the z-sides of the shape
  19041. function buildSideFaces() {
  19042. var layeroffset = 0;
  19043. sidewalls( contour, layeroffset );
  19044. layeroffset += contour.length;
  19045. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19046. ahole = holes[ h ];
  19047. sidewalls( ahole, layeroffset );
  19048. //, true
  19049. layeroffset += ahole.length;
  19050. }
  19051. }
  19052. function sidewalls( contour, layeroffset ) {
  19053. var j, k;
  19054. i = contour.length;
  19055. while ( --i >= 0 ) {
  19056. j = i;
  19057. k = i - 1;
  19058. if ( k < 0 ) k = contour.length - 1;
  19059. //console.log('b', i,j, i-1, k,vertices.length);
  19060. var s = 0, sl = steps + bevelSegments * 2;
  19061. for ( s = 0; s < sl; s ++ ) {
  19062. var slen1 = vlen * s;
  19063. var slen2 = vlen * ( s + 1 );
  19064. var a = layeroffset + j + slen1,
  19065. b = layeroffset + k + slen1,
  19066. c = layeroffset + k + slen2,
  19067. d = layeroffset + j + slen2;
  19068. f4( a, b, c, d, contour, s, sl, j, k );
  19069. }
  19070. }
  19071. }
  19072. function v( x, y, z ) {
  19073. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19074. }
  19075. function f3( a, b, c, isBottom ) {
  19076. a += shapesOffset;
  19077. b += shapesOffset;
  19078. c += shapesOffset;
  19079. // normal, color, material
  19080. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19081. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19082. scope.faceVertexUvs[ 0 ].push( uvs );
  19083. }
  19084. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19085. a += shapesOffset;
  19086. b += shapesOffset;
  19087. c += shapesOffset;
  19088. d += shapesOffset;
  19089. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19090. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19091. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19092. scope.faceVertexUvs[ 0 ].push( uvs );
  19093. }
  19094. };
  19095. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19096. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19097. var ax = geometry.vertices[ indexA ].x,
  19098. ay = geometry.vertices[ indexA ].y,
  19099. bx = geometry.vertices[ indexB ].x,
  19100. by = geometry.vertices[ indexB ].y,
  19101. cx = geometry.vertices[ indexC ].x,
  19102. cy = geometry.vertices[ indexC ].y;
  19103. return [
  19104. new THREE.Vector2( ax, ay ),
  19105. new THREE.Vector2( bx, by ),
  19106. new THREE.Vector2( cx, cy )
  19107. ];
  19108. },
  19109. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19110. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19111. },
  19112. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19113. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19114. contourIndex1, contourIndex2 ) {
  19115. var ax = geometry.vertices[ indexA ].x,
  19116. ay = geometry.vertices[ indexA ].y,
  19117. az = geometry.vertices[ indexA ].z,
  19118. bx = geometry.vertices[ indexB ].x,
  19119. by = geometry.vertices[ indexB ].y,
  19120. bz = geometry.vertices[ indexB ].z,
  19121. cx = geometry.vertices[ indexC ].x,
  19122. cy = geometry.vertices[ indexC ].y,
  19123. cz = geometry.vertices[ indexC ].z,
  19124. dx = geometry.vertices[ indexD ].x,
  19125. dy = geometry.vertices[ indexD ].y,
  19126. dz = geometry.vertices[ indexD ].z;
  19127. if ( Math.abs( ay - by ) < 0.01 ) {
  19128. return [
  19129. new THREE.Vector2( ax, 1 - az ),
  19130. new THREE.Vector2( bx, 1 - bz ),
  19131. new THREE.Vector2( cx, 1 - cz ),
  19132. new THREE.Vector2( dx, 1 - dz )
  19133. ];
  19134. } else {
  19135. return [
  19136. new THREE.Vector2( ay, 1 - az ),
  19137. new THREE.Vector2( by, 1 - bz ),
  19138. new THREE.Vector2( cy, 1 - cz ),
  19139. new THREE.Vector2( dy, 1 - dz )
  19140. ];
  19141. }
  19142. }
  19143. };
  19144. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19145. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19146. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19147. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19148. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19149. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19150. /**
  19151. * @author jonobr1 / http://jonobr1.com
  19152. *
  19153. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19154. * ExtrudeGeometry.
  19155. *
  19156. * parameters = {
  19157. *
  19158. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19159. *
  19160. * material: <int> // material index for front and back faces
  19161. * uvGenerator: <Object> // object that provides UV generator functions
  19162. *
  19163. * }
  19164. **/
  19165. THREE.ShapeGeometry = function ( shapes, options ) {
  19166. THREE.Geometry.call( this );
  19167. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19168. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19169. this.addShapeList( shapes, options );
  19170. this.computeCentroids();
  19171. this.computeFaceNormals();
  19172. };
  19173. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19174. /**
  19175. * Add an array of shapes to THREE.ShapeGeometry.
  19176. */
  19177. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19178. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19179. this.addShape( shapes[ i ], options );
  19180. }
  19181. return this;
  19182. };
  19183. /**
  19184. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19185. */
  19186. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19187. if ( options === undefined ) options = {};
  19188. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19189. var material = options.material;
  19190. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19191. var shapebb = this.shapebb;
  19192. //
  19193. var i, l, hole, s;
  19194. var shapesOffset = this.vertices.length;
  19195. var shapePoints = shape.extractPoints( curveSegments );
  19196. var vertices = shapePoints.shape;
  19197. var holes = shapePoints.holes;
  19198. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19199. if ( reverse ) {
  19200. vertices = vertices.reverse();
  19201. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19202. for ( i = 0, l = holes.length; i < l; i++ ) {
  19203. hole = holes[ i ];
  19204. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19205. holes[ i ] = hole.reverse();
  19206. }
  19207. }
  19208. reverse = false;
  19209. }
  19210. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19211. // Vertices
  19212. var contour = vertices;
  19213. for ( i = 0, l = holes.length; i < l; i++ ) {
  19214. hole = holes[ i ];
  19215. vertices = vertices.concat( hole );
  19216. }
  19217. //
  19218. var vert, vlen = vertices.length;
  19219. var face, flen = faces.length;
  19220. var cont, clen = contour.length;
  19221. for ( i = 0; i < vlen; i++ ) {
  19222. vert = vertices[ i ];
  19223. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19224. }
  19225. for ( i = 0; i < flen; i++ ) {
  19226. face = faces[ i ];
  19227. var a = face[ 0 ] + shapesOffset;
  19228. var b = face[ 1 ] + shapesOffset;
  19229. var c = face[ 2 ] + shapesOffset;
  19230. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19231. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19232. }
  19233. };
  19234. /**
  19235. * @author astrodud / http://astrodud.isgreat.org/
  19236. * @author zz85 / https://github.com/zz85
  19237. */
  19238. THREE.LatheGeometry = function ( points, steps, angle ) {
  19239. THREE.Geometry.call( this );
  19240. var _steps = steps || 12;
  19241. var _angle = angle || 2 * Math.PI;
  19242. var _newV = [];
  19243. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  19244. for ( var j = 0; j < points.length; j ++ ) {
  19245. _newV[ j ] = points[ j ].clone();
  19246. this.vertices.push( _newV[ j ] );
  19247. }
  19248. var i, il = _steps + 1;
  19249. for ( i = 0; i < il; i ++ ) {
  19250. for ( var j = 0; j < _newV.length; j ++ ) {
  19251. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  19252. this.vertices.push( _newV[ j ] );
  19253. }
  19254. }
  19255. for ( i = 0; i < _steps; i ++ ) {
  19256. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  19257. var a = i * kl + k;
  19258. var b = ( ( i + 1 ) % il ) * kl + k;
  19259. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  19260. var d = i * kl + ( k + 1 ) % kl;
  19261. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19262. this.faceVertexUvs[ 0 ].push( [
  19263. new THREE.Vector2( 1 - i / _steps, k / kl ),
  19264. new THREE.Vector2( 1 - ( i + 1 ) / _steps, k / kl ),
  19265. new THREE.Vector2( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  19266. new THREE.Vector2( 1 - i / _steps, ( k + 1 ) / kl )
  19267. ] );
  19268. }
  19269. }
  19270. this.computeCentroids();
  19271. this.computeFaceNormals();
  19272. this.computeVertexNormals();
  19273. };
  19274. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19275. /**
  19276. * @author mrdoob / http://mrdoob.com/
  19277. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19278. */
  19279. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19280. THREE.Geometry.call( this );
  19281. this.width = width;
  19282. this.height = height;
  19283. this.widthSegments = widthSegments || 1;
  19284. this.heightSegments = heightSegments || 1;
  19285. var ix, iz;
  19286. var width_half = width / 2;
  19287. var height_half = height / 2;
  19288. var gridX = this.widthSegments;
  19289. var gridZ = this.heightSegments;
  19290. var gridX1 = gridX + 1;
  19291. var gridZ1 = gridZ + 1;
  19292. var segment_width = this.width / gridX;
  19293. var segment_height = this.height / gridZ;
  19294. var normal = new THREE.Vector3( 0, 0, 1 );
  19295. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19296. for ( ix = 0; ix < gridX1; ix ++ ) {
  19297. var x = ix * segment_width - width_half;
  19298. var y = iz * segment_height - height_half;
  19299. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19300. }
  19301. }
  19302. for ( iz = 0; iz < gridZ; iz ++ ) {
  19303. for ( ix = 0; ix < gridX; ix ++ ) {
  19304. var a = ix + gridX1 * iz;
  19305. var b = ix + gridX1 * ( iz + 1 );
  19306. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19307. var d = ( ix + 1 ) + gridX1 * iz;
  19308. var face = new THREE.Face4( a, b, c, d );
  19309. face.normal.copy( normal );
  19310. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19311. this.faces.push( face );
  19312. this.faceVertexUvs[ 0 ].push( [
  19313. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19314. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19315. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19316. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19317. ] );
  19318. }
  19319. }
  19320. this.computeCentroids();
  19321. };
  19322. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19323. /**
  19324. * @author mrdoob / http://mrdoob.com/
  19325. */
  19326. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19327. THREE.Geometry.call( this );
  19328. this.radius = radius || 50;
  19329. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19330. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19331. phiStart = phiStart !== undefined ? phiStart : 0;
  19332. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19333. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19334. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19335. var x, y, vertices = [], uvs = [];
  19336. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19337. var verticesRow = [];
  19338. var uvsRow = [];
  19339. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19340. var u = x / this.widthSegments;
  19341. var v = y / this.heightSegments;
  19342. var vertex = new THREE.Vector3();
  19343. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19344. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19345. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19346. this.vertices.push( vertex );
  19347. verticesRow.push( this.vertices.length - 1 );
  19348. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19349. }
  19350. vertices.push( verticesRow );
  19351. uvs.push( uvsRow );
  19352. }
  19353. for ( y = 0; y < this.heightSegments; y ++ ) {
  19354. for ( x = 0; x < this.widthSegments; x ++ ) {
  19355. var v1 = vertices[ y ][ x + 1 ];
  19356. var v2 = vertices[ y ][ x ];
  19357. var v3 = vertices[ y + 1 ][ x ];
  19358. var v4 = vertices[ y + 1 ][ x + 1 ];
  19359. var n1 = this.vertices[ v1 ].clone().normalize();
  19360. var n2 = this.vertices[ v2 ].clone().normalize();
  19361. var n3 = this.vertices[ v3 ].clone().normalize();
  19362. var n4 = this.vertices[ v4 ].clone().normalize();
  19363. var uv1 = uvs[ y ][ x + 1 ].clone();
  19364. var uv2 = uvs[ y ][ x ].clone();
  19365. var uv3 = uvs[ y + 1 ][ x ].clone();
  19366. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19367. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19368. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19369. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19370. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19371. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19372. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19373. } else {
  19374. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19375. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19376. }
  19377. }
  19378. }
  19379. this.computeCentroids();
  19380. this.computeFaceNormals();
  19381. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19382. };
  19383. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19384. /**
  19385. * @author zz85 / http://www.lab4games.net/zz85/blog
  19386. * @author alteredq / http://alteredqualia.com/
  19387. *
  19388. * For creating 3D text geometry in three.js
  19389. *
  19390. * Text = 3D Text
  19391. *
  19392. * parameters = {
  19393. * size: <float>, // size of the text
  19394. * height: <float>, // thickness to extrude text
  19395. * curveSegments: <int>, // number of points on the curves
  19396. *
  19397. * font: <string>, // font name
  19398. * weight: <string>, // font weight (normal, bold)
  19399. * style: <string>, // font style (normal, italics)
  19400. *
  19401. * bevelEnabled: <bool>, // turn on bevel
  19402. * bevelThickness: <float>, // how deep into text bevel goes
  19403. * bevelSize: <float>, // how far from text outline is bevel
  19404. * }
  19405. *
  19406. */
  19407. /* Usage Examples
  19408. // TextGeometry wrapper
  19409. var text3d = new TextGeometry( text, options );
  19410. // Complete manner
  19411. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19412. var text3d = new ExtrudeGeometry( textShapes, options );
  19413. */
  19414. THREE.TextGeometry = function ( text, parameters ) {
  19415. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19416. // translate parameters to ExtrudeGeometry API
  19417. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19418. // defaults
  19419. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19420. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19421. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19422. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19423. };
  19424. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19425. /**
  19426. * @author oosmoxiecode
  19427. * @author mrdoob / http://mrdoob.com/
  19428. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19429. */
  19430. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19431. THREE.Geometry.call( this );
  19432. var scope = this;
  19433. this.radius = radius || 100;
  19434. this.tube = tube || 40;
  19435. this.radialSegments = radialSegments || 8;
  19436. this.tubularSegments = tubularSegments || 6;
  19437. this.arc = arc || Math.PI * 2;
  19438. var center = new THREE.Vector3(), uvs = [], normals = [];
  19439. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19440. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19441. var u = i / this.tubularSegments * this.arc;
  19442. var v = j / this.radialSegments * Math.PI * 2;
  19443. center.x = this.radius * Math.cos( u );
  19444. center.y = this.radius * Math.sin( u );
  19445. var vertex = new THREE.Vector3();
  19446. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19447. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19448. vertex.z = this.tube * Math.sin( v );
  19449. this.vertices.push( vertex );
  19450. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19451. normals.push( vertex.clone().subSelf( center ).normalize() );
  19452. }
  19453. }
  19454. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19455. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19456. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19457. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19458. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19459. var d = ( this.tubularSegments + 1 ) * j + i;
  19460. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19461. face.normal.addSelf( normals[ a ] );
  19462. face.normal.addSelf( normals[ b ] );
  19463. face.normal.addSelf( normals[ c ] );
  19464. face.normal.addSelf( normals[ d ] );
  19465. face.normal.normalize();
  19466. this.faces.push( face );
  19467. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19468. }
  19469. }
  19470. this.computeCentroids();
  19471. };
  19472. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19473. /**
  19474. * @author oosmoxiecode
  19475. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19476. */
  19477. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19478. THREE.Geometry.call( this );
  19479. var scope = this;
  19480. this.radius = radius || 200;
  19481. this.tube = tube || 40;
  19482. this.radialSegments = radialSegments || 64;
  19483. this.tubularSegments = tubularSegments || 8;
  19484. this.p = p || 2;
  19485. this.q = q || 3;
  19486. this.heightScale = heightScale || 1;
  19487. this.grid = new Array(this.radialSegments);
  19488. var tang = new THREE.Vector3();
  19489. var n = new THREE.Vector3();
  19490. var bitan = new THREE.Vector3();
  19491. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19492. this.grid[ i ] = new Array( this.tubularSegments );
  19493. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19494. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19495. var v = j / this.tubularSegments * 2 * Math.PI;
  19496. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19497. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19498. var cx, cy;
  19499. tang.sub( p2, p1 );
  19500. n.add( p2, p1 );
  19501. bitan.cross( tang, n );
  19502. n.cross( bitan, tang );
  19503. bitan.normalize();
  19504. n.normalize();
  19505. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19506. cy = this.tube * Math.sin( v );
  19507. p1.x += cx * n.x + cy * bitan.x;
  19508. p1.y += cx * n.y + cy * bitan.y;
  19509. p1.z += cx * n.z + cy * bitan.z;
  19510. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19511. }
  19512. }
  19513. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19514. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19515. var ip = ( i + 1 ) % this.radialSegments;
  19516. var jp = ( j + 1 ) % this.tubularSegments;
  19517. var a = this.grid[ i ][ j ];
  19518. var b = this.grid[ ip ][ j ];
  19519. var c = this.grid[ ip ][ jp ];
  19520. var d = this.grid[ i ][ jp ];
  19521. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19522. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19523. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19524. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19525. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19526. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19527. }
  19528. }
  19529. this.computeCentroids();
  19530. this.computeFaceNormals();
  19531. this.computeVertexNormals();
  19532. function vert( x, y, z ) {
  19533. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19534. }
  19535. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19536. var cu = Math.cos( u );
  19537. var cv = Math.cos( v );
  19538. var su = Math.sin( u );
  19539. var quOverP = in_q / in_p * u;
  19540. var cs = Math.cos( quOverP );
  19541. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19542. var ty = radius * ( 2 + cs ) * su * 0.5;
  19543. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19544. return new THREE.Vector3( tx, ty, tz );
  19545. }
  19546. };
  19547. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19548. /**
  19549. * @author WestLangley / https://github.com/WestLangley
  19550. * @author zz85 / https://github.com/zz85
  19551. * @author miningold / https://github.com/miningold
  19552. *
  19553. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19554. *
  19555. * Creates a tube which extrudes along a 3d spline
  19556. *
  19557. * Uses parallel transport frames as described in
  19558. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19559. */
  19560. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19561. THREE.Geometry.call( this );
  19562. this.path = path;
  19563. this.segments = segments || 64;
  19564. this.radius = radius || 1;
  19565. this.radiusSegments = radiusSegments || 8;
  19566. this.closed = closed || false;
  19567. if ( debug ) this.debug = new THREE.Object3D();
  19568. this.grid = [];
  19569. var scope = this,
  19570. tangent,
  19571. normal,
  19572. binormal,
  19573. numpoints = this.segments + 1,
  19574. x, y, z,
  19575. tx, ty, tz,
  19576. u, v,
  19577. cx, cy,
  19578. pos, pos2 = new THREE.Vector3(),
  19579. i, j,
  19580. ip, jp,
  19581. a, b, c, d,
  19582. uva, uvb, uvc, uvd;
  19583. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19584. tangents = frames.tangents,
  19585. normals = frames.normals,
  19586. binormals = frames.binormals;
  19587. // proxy internals
  19588. this.tangents = tangents;
  19589. this.normals = normals;
  19590. this.binormals = binormals;
  19591. function vert( x, y, z ) {
  19592. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19593. }
  19594. // consruct the grid
  19595. for ( i = 0; i < numpoints; i++ ) {
  19596. this.grid[ i ] = [];
  19597. u = i / ( numpoints - 1 );
  19598. pos = path.getPointAt( u );
  19599. tangent = tangents[ i ];
  19600. normal = normals[ i ];
  19601. binormal = binormals[ i ];
  19602. if ( this.debug ) {
  19603. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19604. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19605. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19606. }
  19607. for ( j = 0; j < this.radiusSegments; j++ ) {
  19608. v = j / this.radiusSegments * 2 * Math.PI;
  19609. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19610. cy = this.radius * Math.sin( v );
  19611. pos2.copy( pos );
  19612. pos2.x += cx * normal.x + cy * binormal.x;
  19613. pos2.y += cx * normal.y + cy * binormal.y;
  19614. pos2.z += cx * normal.z + cy * binormal.z;
  19615. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19616. }
  19617. }
  19618. // construct the mesh
  19619. for ( i = 0; i < this.segments; i++ ) {
  19620. for ( j = 0; j < this.radiusSegments; j++ ) {
  19621. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19622. jp = (j + 1) % this.radiusSegments;
  19623. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19624. b = this.grid[ ip ][ j ];
  19625. c = this.grid[ ip ][ jp ];
  19626. d = this.grid[ i ][ jp ];
  19627. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19628. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19629. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19630. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19631. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19632. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19633. }
  19634. }
  19635. this.computeCentroids();
  19636. this.computeFaceNormals();
  19637. this.computeVertexNormals();
  19638. };
  19639. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19640. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19641. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19642. var tangent = new THREE.Vector3(),
  19643. normal = new THREE.Vector3(),
  19644. binormal = new THREE.Vector3(),
  19645. tangents = [],
  19646. normals = [],
  19647. binormals = [],
  19648. vec = new THREE.Vector3(),
  19649. mat = new THREE.Matrix4(),
  19650. numpoints = segments + 1,
  19651. theta,
  19652. epsilon = 0.0001,
  19653. smallest,
  19654. tx, ty, tz,
  19655. i, u, v;
  19656. // expose internals
  19657. this.tangents = tangents;
  19658. this.normals = normals;
  19659. this.binormals = binormals;
  19660. // compute the tangent vectors for each segment on the path
  19661. for ( i = 0; i < numpoints; i++ ) {
  19662. u = i / ( numpoints - 1 );
  19663. tangents[ i ] = path.getTangentAt( u );
  19664. tangents[ i ].normalize();
  19665. }
  19666. initialNormal3();
  19667. function initialNormal1(lastBinormal) {
  19668. // fixed start binormal. Has dangers of 0 vectors
  19669. normals[ 0 ] = new THREE.Vector3();
  19670. binormals[ 0 ] = new THREE.Vector3();
  19671. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19672. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  19673. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19674. }
  19675. function initialNormal2() {
  19676. // This uses the Frenet-Serret formula for deriving binormal
  19677. var t2 = path.getTangentAt( epsilon );
  19678. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  19679. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  19680. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19681. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19682. }
  19683. function initialNormal3() {
  19684. // select an initial normal vector perpenicular to the first tangent vector,
  19685. // and in the direction of the smallest tangent xyz component
  19686. normals[ 0 ] = new THREE.Vector3();
  19687. binormals[ 0 ] = new THREE.Vector3();
  19688. smallest = Number.MAX_VALUE;
  19689. tx = Math.abs( tangents[ 0 ].x );
  19690. ty = Math.abs( tangents[ 0 ].y );
  19691. tz = Math.abs( tangents[ 0 ].z );
  19692. if ( tx <= smallest ) {
  19693. smallest = tx;
  19694. normal.set( 1, 0, 0 );
  19695. }
  19696. if ( ty <= smallest ) {
  19697. smallest = ty;
  19698. normal.set( 0, 1, 0 );
  19699. }
  19700. if ( tz <= smallest ) {
  19701. normal.set( 0, 0, 1 );
  19702. }
  19703. vec.cross( tangents[ 0 ], normal ).normalize();
  19704. normals[ 0 ].cross( tangents[ 0 ], vec );
  19705. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  19706. }
  19707. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19708. for ( i = 1; i < numpoints; i++ ) {
  19709. normals[ i ] = normals[ i-1 ].clone();
  19710. binormals[ i ] = binormals[ i-1 ].clone();
  19711. vec.cross( tangents[ i-1 ], tangents[ i ] );
  19712. if ( vec.length() > epsilon ) {
  19713. vec.normalize();
  19714. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19715. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19716. }
  19717. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19718. }
  19719. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19720. if ( closed ) {
  19721. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19722. theta /= ( numpoints - 1 );
  19723. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19724. theta = -theta;
  19725. }
  19726. for ( i = 1; i < numpoints; i++ ) {
  19727. // twist a little...
  19728. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19729. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19730. }
  19731. }
  19732. };
  19733. /**
  19734. * @author clockworkgeek / https://github.com/clockworkgeek
  19735. * @author timothypratley / https://github.com/timothypratley
  19736. */
  19737. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19738. THREE.Geometry.call( this );
  19739. radius = radius || 1;
  19740. detail = detail || 0;
  19741. var that = this;
  19742. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19743. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19744. }
  19745. var midpoints = [], p = this.vertices;
  19746. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19747. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19748. }
  19749. this.mergeVertices();
  19750. // Apply radius
  19751. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19752. this.vertices[ i ].multiplyScalar( radius );
  19753. }
  19754. // Project vector onto sphere's surface
  19755. function prepare( vector ) {
  19756. var vertex = vector.normalize().clone();
  19757. vertex.index = that.vertices.push( vertex ) - 1;
  19758. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19759. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19760. var v = inclination( vector ) / Math.PI + 0.5;
  19761. vertex.uv = new THREE.Vector2( u, 1 - v );
  19762. return vertex;
  19763. }
  19764. // Approximate a curved face with recursively sub-divided triangles.
  19765. function make( v1, v2, v3, detail ) {
  19766. if ( detail < 1 ) {
  19767. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19768. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19769. face.normal = face.centroid.clone().normalize();
  19770. that.faces.push( face );
  19771. var azi = azimuth( face.centroid );
  19772. that.faceVertexUvs[ 0 ].push( [
  19773. correctUV( v1.uv, v1, azi ),
  19774. correctUV( v2.uv, v2, azi ),
  19775. correctUV( v3.uv, v3, azi )
  19776. ] );
  19777. } else {
  19778. detail -= 1;
  19779. // split triangle into 4 smaller triangles
  19780. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19781. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19782. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19783. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19784. }
  19785. }
  19786. function midpoint( v1, v2 ) {
  19787. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19788. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19789. var mid = midpoints[ v1.index ][ v2.index ];
  19790. if ( mid === undefined ) {
  19791. // generate mean point and project to surface with prepare()
  19792. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19793. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19794. );
  19795. }
  19796. return mid;
  19797. }
  19798. // Angle around the Y axis, counter-clockwise when looking from above.
  19799. function azimuth( vector ) {
  19800. return Math.atan2( vector.z, -vector.x );
  19801. }
  19802. // Angle above the XZ plane.
  19803. function inclination( vector ) {
  19804. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19805. }
  19806. // Texture fixing helper. Spheres have some odd behaviours.
  19807. function correctUV( uv, vector, azimuth ) {
  19808. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19809. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19810. return uv;
  19811. }
  19812. this.computeCentroids();
  19813. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19814. };
  19815. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19816. /**
  19817. * @author timothypratley / https://github.com/timothypratley
  19818. */
  19819. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19820. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19821. var vertices = [
  19822. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19823. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19824. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19825. ];
  19826. var faces = [
  19827. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19828. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19829. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19830. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19831. ];
  19832. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19833. };
  19834. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19835. /**
  19836. * @author timothypratley / https://github.com/timothypratley
  19837. */
  19838. THREE.OctahedronGeometry = function ( radius, detail ) {
  19839. var vertices = [
  19840. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19841. ];
  19842. var faces = [
  19843. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19844. ];
  19845. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19846. };
  19847. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19848. /**
  19849. * @author timothypratley / https://github.com/timothypratley
  19850. */
  19851. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19852. var vertices = [
  19853. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19854. ];
  19855. var faces = [
  19856. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19857. ];
  19858. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19859. };
  19860. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19861. /**
  19862. * @author zz85 / https://github.com/zz85
  19863. * Parametric Surfaces Geometry
  19864. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19865. *
  19866. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19867. *
  19868. */
  19869. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19870. THREE.Geometry.call( this );
  19871. var verts = this.vertices;
  19872. var faces = this.faces;
  19873. var uvs = this.faceVertexUvs[ 0 ];
  19874. useTris = (useTris === undefined) ? false : useTris;
  19875. var i, il, j, p;
  19876. var u, v;
  19877. var stackCount = stacks + 1;
  19878. var sliceCount = slices + 1;
  19879. for ( i = 0; i <= stacks; i ++ ) {
  19880. v = i / stacks;
  19881. for ( j = 0; j <= slices; j ++ ) {
  19882. u = j / slices;
  19883. p = func( u, v );
  19884. verts.push( p );
  19885. }
  19886. }
  19887. var a, b, c, d;
  19888. var uva, uvb, uvc, uvd;
  19889. for ( i = 0; i < stacks; i ++ ) {
  19890. for ( j = 0; j < slices; j ++ ) {
  19891. a = i * sliceCount + j;
  19892. b = i * sliceCount + j + 1;
  19893. c = (i + 1) * sliceCount + j;
  19894. d = (i + 1) * sliceCount + j + 1;
  19895. uva = new THREE.Vector2( j / slices, i / stacks );
  19896. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19897. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19898. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19899. if ( useTris ) {
  19900. faces.push( new THREE.Face3( a, b, c ) );
  19901. faces.push( new THREE.Face3( b, d, c ) );
  19902. uvs.push( [ uva, uvb, uvc ] );
  19903. uvs.push( [ uvb, uvd, uvc ] );
  19904. } else {
  19905. faces.push( new THREE.Face4( a, b, d, c ) );
  19906. uvs.push( [ uva, uvb, uvd, uvc ] );
  19907. }
  19908. }
  19909. }
  19910. // console.log(this);
  19911. // magic bullet
  19912. // var diff = this.mergeVertices();
  19913. // console.log('removed ', diff, ' vertices by merging');
  19914. this.computeCentroids();
  19915. this.computeFaceNormals();
  19916. this.computeVertexNormals();
  19917. };
  19918. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19919. /**
  19920. * @author qiao / https://github.com/qiao
  19921. * @fileoverview This is a convex hull generator using the incremental method.
  19922. * The complexity is O(n^2) where n is the number of vertices.
  19923. * O(nlogn) algorithms do exist, but they are much more complicated.
  19924. *
  19925. * Benchmark:
  19926. *
  19927. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19928. *
  19929. * Num Vertices Time(ms)
  19930. *
  19931. * 10 1
  19932. * 20 3
  19933. * 30 19
  19934. * 40 48
  19935. * 50 107
  19936. */
  19937. THREE.ConvexGeometry = function( vertices ) {
  19938. THREE.Geometry.call( this );
  19939. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19940. for ( var i = 3; i < vertices.length; i++ ) {
  19941. addPoint( i );
  19942. }
  19943. function addPoint( vertexId ) {
  19944. var vertex = vertices[ vertexId ].clone();
  19945. var mag = vertex.length();
  19946. vertex.x += mag * randomOffset();
  19947. vertex.y += mag * randomOffset();
  19948. vertex.z += mag * randomOffset();
  19949. var hole = [];
  19950. for ( var f = 0; f < faces.length; ) {
  19951. var face = faces[ f ];
  19952. // for each face, if the vertex can see it,
  19953. // then we try to add the face's edges into the hole.
  19954. if ( visible( face, vertex ) ) {
  19955. for ( var e = 0; e < 3; e++ ) {
  19956. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19957. var boundary = true;
  19958. // remove duplicated edges.
  19959. for ( var h = 0; h < hole.length; h++ ) {
  19960. if ( equalEdge( hole[ h ], edge ) ) {
  19961. hole[ h ] = hole[ hole.length - 1 ];
  19962. hole.pop();
  19963. boundary = false;
  19964. break;
  19965. }
  19966. }
  19967. if ( boundary ) {
  19968. hole.push( edge );
  19969. }
  19970. }
  19971. // remove faces[ f ]
  19972. faces[ f ] = faces[ faces.length - 1 ];
  19973. faces.pop();
  19974. } else { // not visible
  19975. f++;
  19976. }
  19977. }
  19978. // construct the new faces formed by the edges of the hole and the vertex
  19979. for ( var h = 0; h < hole.length; h++ ) {
  19980. faces.push( [
  19981. hole[ h ][ 0 ],
  19982. hole[ h ][ 1 ],
  19983. vertexId
  19984. ] );
  19985. }
  19986. }
  19987. /**
  19988. * Whether the face is visible from the vertex
  19989. */
  19990. function visible( face, vertex ) {
  19991. var va = vertices[ face[ 0 ] ];
  19992. var vb = vertices[ face[ 1 ] ];
  19993. var vc = vertices[ face[ 2 ] ];
  19994. var n = normal( va, vb, vc );
  19995. // distance from face to origin
  19996. var dist = n.dot( va );
  19997. return n.dot( vertex ) >= dist;
  19998. }
  19999. /**
  20000. * Face normal
  20001. */
  20002. function normal( va, vb, vc ) {
  20003. var cb = new THREE.Vector3();
  20004. var ab = new THREE.Vector3();
  20005. cb.sub( vc, vb );
  20006. ab.sub( va, vb );
  20007. cb.crossSelf( ab );
  20008. cb.normalize();
  20009. return cb;
  20010. }
  20011. /**
  20012. * Detect whether two edges are equal.
  20013. * Note that when constructing the convex hull, two same edges can only
  20014. * be of the negative direction.
  20015. */
  20016. function equalEdge( ea, eb ) {
  20017. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20018. }
  20019. /**
  20020. * Create a random offset between -1e-6 and 1e-6.
  20021. */
  20022. function randomOffset() {
  20023. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20024. }
  20025. /**
  20026. * XXX: Not sure if this is the correct approach. Need someone to review.
  20027. */
  20028. function vertexUv( vertex ) {
  20029. var mag = vertex.length();
  20030. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20031. }
  20032. // Push vertices into `this.vertices`, skipping those inside the hull
  20033. var id = 0;
  20034. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20035. for ( var i = 0; i < faces.length; i++ ) {
  20036. var face = faces[ i ];
  20037. for ( var j = 0; j < 3; j++ ) {
  20038. if ( newId[ face[ j ] ] === undefined ) {
  20039. newId[ face[ j ] ] = id++;
  20040. this.vertices.push( vertices[ face[ j ] ] );
  20041. }
  20042. face[ j ] = newId[ face[ j ] ];
  20043. }
  20044. }
  20045. // Convert faces into instances of THREE.Face3
  20046. for ( var i = 0; i < faces.length; i++ ) {
  20047. this.faces.push( new THREE.Face3(
  20048. faces[ i ][ 0 ],
  20049. faces[ i ][ 1 ],
  20050. faces[ i ][ 2 ]
  20051. ) );
  20052. }
  20053. // Compute UVs
  20054. for ( var i = 0; i < this.faces.length; i++ ) {
  20055. var face = this.faces[ i ];
  20056. this.faceVertexUvs[ 0 ].push( [
  20057. vertexUv( this.vertices[ face.a ] ),
  20058. vertexUv( this.vertices[ face.b ] ),
  20059. vertexUv( this.vertices[ face.c ])
  20060. ] );
  20061. }
  20062. this.computeCentroids();
  20063. this.computeFaceNormals();
  20064. this.computeVertexNormals();
  20065. };
  20066. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20067. /**
  20068. * @author sroucheray / http://sroucheray.org/
  20069. * @author mrdoob / http://mrdoob.com/
  20070. */
  20071. THREE.AxisHelper = function ( size ) {
  20072. var geometry = new THREE.Geometry();
  20073. geometry.vertices.push(
  20074. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  20075. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  20076. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  20077. );
  20078. geometry.colors.push(
  20079. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20080. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20081. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20082. );
  20083. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20084. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20085. };
  20086. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20087. /**
  20088. * @author WestLangley / http://github.com/WestLangley
  20089. * @author zz85 / https://github.com/zz85
  20090. *
  20091. * Creates an arrow for visualizing directions
  20092. *
  20093. * Parameters:
  20094. * dir - Vector3
  20095. * origin - Vector3
  20096. * length - Number
  20097. * hex - color in hex value
  20098. */
  20099. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20100. THREE.Object3D.call( this );
  20101. if ( hex === undefined ) hex = 0xffff00;
  20102. if ( length === undefined ) length = 20;
  20103. var lineGeometry = new THREE.Geometry();
  20104. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20105. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20106. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20107. this.add( this.line );
  20108. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20109. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20110. this.cone.position.set( 0, 1, 0 );
  20111. this.add( this.cone );
  20112. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  20113. this.setDirection( dir );
  20114. this.setLength( length );
  20115. };
  20116. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20117. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  20118. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  20119. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  20120. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  20121. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  20122. };
  20123. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20124. this.scale.set( length, length, length );
  20125. };
  20126. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20127. this.line.material.color.setHex( hex );
  20128. this.cone.material.color.setHex( hex );
  20129. };
  20130. /**
  20131. * @author alteredq / http://alteredqualia.com/
  20132. *
  20133. * - shows frustum, line of sight and up of the camera
  20134. * - suitable for fast updates
  20135. * - based on frustum visualization in lightgl.js shadowmap example
  20136. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20137. */
  20138. THREE.CameraHelper = function ( camera ) {
  20139. THREE.Line.call( this );
  20140. var scope = this;
  20141. this.geometry = new THREE.Geometry();
  20142. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20143. this.type = THREE.LinePieces;
  20144. this.matrixWorld = camera.matrixWorld;
  20145. this.matrixAutoUpdate = false;
  20146. this.pointMap = {};
  20147. // colors
  20148. var hexFrustum = 0xffaa00;
  20149. var hexCone = 0xff0000;
  20150. var hexUp = 0x00aaff;
  20151. var hexTarget = 0xffffff;
  20152. var hexCross = 0x333333;
  20153. // near
  20154. addLine( "n1", "n2", hexFrustum );
  20155. addLine( "n2", "n4", hexFrustum );
  20156. addLine( "n4", "n3", hexFrustum );
  20157. addLine( "n3", "n1", hexFrustum );
  20158. // far
  20159. addLine( "f1", "f2", hexFrustum );
  20160. addLine( "f2", "f4", hexFrustum );
  20161. addLine( "f4", "f3", hexFrustum );
  20162. addLine( "f3", "f1", hexFrustum );
  20163. // sides
  20164. addLine( "n1", "f1", hexFrustum );
  20165. addLine( "n2", "f2", hexFrustum );
  20166. addLine( "n3", "f3", hexFrustum );
  20167. addLine( "n4", "f4", hexFrustum );
  20168. // cone
  20169. addLine( "p", "n1", hexCone );
  20170. addLine( "p", "n2", hexCone );
  20171. addLine( "p", "n3", hexCone );
  20172. addLine( "p", "n4", hexCone );
  20173. // up
  20174. addLine( "u1", "u2", hexUp );
  20175. addLine( "u2", "u3", hexUp );
  20176. addLine( "u3", "u1", hexUp );
  20177. // target
  20178. addLine( "c", "t", hexTarget );
  20179. addLine( "p", "c", hexCross );
  20180. // cross
  20181. addLine( "cn1", "cn2", hexCross );
  20182. addLine( "cn3", "cn4", hexCross );
  20183. addLine( "cf1", "cf2", hexCross );
  20184. addLine( "cf3", "cf4", hexCross );
  20185. this.camera = camera;
  20186. function addLine( a, b, hex ) {
  20187. addPoint( a, hex );
  20188. addPoint( b, hex );
  20189. }
  20190. function addPoint( id, hex ) {
  20191. scope.geometry.vertices.push( new THREE.Vector3() );
  20192. scope.geometry.colors.push( new THREE.Color( hex ) );
  20193. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20194. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20195. }
  20196. this.update( camera );
  20197. };
  20198. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20199. THREE.CameraHelper.prototype.update = function () {
  20200. var scope = this;
  20201. var w = 1, h = 1;
  20202. // we need just camera projection matrix
  20203. // world matrix must be identity
  20204. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20205. // center / target
  20206. setPoint( "c", 0, 0, -1 );
  20207. setPoint( "t", 0, 0, 1 );
  20208. // near
  20209. setPoint( "n1", -w, -h, -1 );
  20210. setPoint( "n2", w, -h, -1 );
  20211. setPoint( "n3", -w, h, -1 );
  20212. setPoint( "n4", w, h, -1 );
  20213. // far
  20214. setPoint( "f1", -w, -h, 1 );
  20215. setPoint( "f2", w, -h, 1 );
  20216. setPoint( "f3", -w, h, 1 );
  20217. setPoint( "f4", w, h, 1 );
  20218. // up
  20219. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20220. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20221. setPoint( "u3", 0, h * 2, -1 );
  20222. // cross
  20223. setPoint( "cf1", -w, 0, 1 );
  20224. setPoint( "cf2", w, 0, 1 );
  20225. setPoint( "cf3", 0, -h, 1 );
  20226. setPoint( "cf4", 0, h, 1 );
  20227. setPoint( "cn1", -w, 0, -1 );
  20228. setPoint( "cn2", w, 0, -1 );
  20229. setPoint( "cn3", 0, -h, -1 );
  20230. setPoint( "cn4", 0, h, -1 );
  20231. function setPoint( point, x, y, z ) {
  20232. THREE.CameraHelper.__v.set( x, y, z );
  20233. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20234. var points = scope.pointMap[ point ];
  20235. if ( points !== undefined ) {
  20236. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20237. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20238. }
  20239. }
  20240. }
  20241. this.geometry.verticesNeedUpdate = true;
  20242. };
  20243. THREE.CameraHelper.__projector = new THREE.Projector();
  20244. THREE.CameraHelper.__v = new THREE.Vector3();
  20245. THREE.CameraHelper.__c = new THREE.Camera();
  20246. /**
  20247. * @author alteredq / http://alteredqualia.com/
  20248. *
  20249. * - shows directional light color, intensity, position, orientation and target
  20250. */
  20251. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  20252. THREE.Object3D.call( this );
  20253. this.light = light;
  20254. // position
  20255. this.position = light.position;
  20256. // direction
  20257. this.direction = new THREE.Vector3();
  20258. this.direction.sub( light.target.position, light.position );
  20259. // color
  20260. this.color = light.color.clone();
  20261. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20262. this.color.r *= intensity;
  20263. this.color.g *= intensity;
  20264. this.color.b *= intensity;
  20265. var hexColor = this.color.getHex();
  20266. // light helper
  20267. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20268. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20269. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20270. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20271. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  20272. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20273. this.lightArrow.cone.material.fog = false;
  20274. this.lightArrow.line.material.fog = false;
  20275. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20276. this.add( this.lightArrow );
  20277. this.add( this.lightSphere );
  20278. this.add( this.lightRays );
  20279. this.lightSphere.properties.isGizmo = true;
  20280. this.lightSphere.properties.gizmoSubject = light;
  20281. this.lightSphere.properties.gizmoRoot = this;
  20282. // light target helper
  20283. this.targetSphere = null;
  20284. if ( light.target.properties.targetInverse ) {
  20285. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20286. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20287. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20288. this.targetSphere.position = light.target.position;
  20289. this.targetSphere.properties.isGizmo = true;
  20290. this.targetSphere.properties.gizmoSubject = light.target;
  20291. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20292. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20293. var lineGeometry = new THREE.Geometry();
  20294. lineGeometry.vertices.push( this.position.clone() );
  20295. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20296. lineGeometry.computeLineDistances();
  20297. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20298. this.targetLine.properties.isGizmo = true;
  20299. }
  20300. //
  20301. this.properties.isGizmo = true;
  20302. }
  20303. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20304. THREE.DirectionalLightHelper.prototype.update = function () {
  20305. // update arrow orientation
  20306. // pointing from light to target
  20307. this.direction.sub( this.light.target.position, this.light.position );
  20308. this.lightArrow.setDirection( this.direction );
  20309. // update arrow, spheres, rays and line colors to light color * light intensity
  20310. this.color.copy( this.light.color );
  20311. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20312. this.color.r *= intensity;
  20313. this.color.g *= intensity;
  20314. this.color.b *= intensity;
  20315. this.lightArrow.setColor( this.color.getHex() );
  20316. this.lightSphere.material.color.copy( this.color );
  20317. this.lightRays.material.color.copy( this.color );
  20318. this.targetSphere.material.color.copy( this.color );
  20319. this.targetLine.material.color.copy( this.color );
  20320. // update target line vertices
  20321. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20322. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20323. this.targetLine.geometry.computeLineDistances();
  20324. this.targetLine.geometry.verticesNeedUpdate = true;
  20325. }
  20326. /**
  20327. * @author alteredq / http://alteredqualia.com/
  20328. *
  20329. * - shows hemisphere light intensity, sky and ground colors and directions
  20330. */
  20331. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20332. THREE.Object3D.call( this );
  20333. this.light = light;
  20334. // position
  20335. this.position = light.position;
  20336. //
  20337. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20338. // sky color
  20339. this.color = light.color.clone();
  20340. this.color.r *= intensity;
  20341. this.color.g *= intensity;
  20342. this.color.b *= intensity;
  20343. var hexColor = this.color.getHex();
  20344. // ground color
  20345. this.groundColor = light.groundColor.clone();
  20346. this.groundColor.r *= intensity;
  20347. this.groundColor.g *= intensity;
  20348. this.groundColor.b *= intensity;
  20349. var hexColorGround = this.groundColor.getHex();
  20350. // double colored light bulb
  20351. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20352. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20353. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20354. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20355. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20356. bulbGeometry.faces[ i ].materialIndex = 0;
  20357. }
  20358. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20359. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20360. }
  20361. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20362. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20363. // arrows for sky and ground light directions
  20364. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20365. this.lightArrow.rotation.x = Math.PI;
  20366. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20367. var joint = new THREE.Object3D();
  20368. joint.rotation.x = -Math.PI * 0.5;
  20369. joint.add( this.lightSphere );
  20370. joint.add( this.lightArrow );
  20371. joint.add( this.lightArrowGround );
  20372. this.add( joint );
  20373. //
  20374. this.lightSphere.properties.isGizmo = true;
  20375. this.lightSphere.properties.gizmoSubject = light;
  20376. this.lightSphere.properties.gizmoRoot = this;
  20377. //
  20378. this.properties.isGizmo = true;
  20379. //
  20380. this.target = new THREE.Vector3();
  20381. this.lookAt( this.target );
  20382. }
  20383. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20384. THREE.HemisphereLightHelper.prototype.update = function () {
  20385. // update sphere sky and ground colors to light color * light intensity
  20386. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20387. this.color.copy( this.light.color );
  20388. this.groundColor.copy( this.light.groundColor );
  20389. this.color.r *= intensity;
  20390. this.color.g *= intensity;
  20391. this.color.b *= intensity;
  20392. this.groundColor.r *= intensity;
  20393. this.groundColor.g *= intensity;
  20394. this.groundColor.b *= intensity;
  20395. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20396. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20397. this.lightArrow.setColor( this.color.getHex() );
  20398. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20399. this.lookAt( this.target );
  20400. }
  20401. /**
  20402. * @author alteredq / http://alteredqualia.com/
  20403. *
  20404. * - shows point light color, intensity, position and distance
  20405. */
  20406. THREE.PointLightHelper = function ( light, sphereSize ) {
  20407. THREE.Object3D.call( this );
  20408. this.light = light;
  20409. // position
  20410. this.position = light.position;
  20411. // color
  20412. this.color = light.color.clone();
  20413. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20414. this.color.r *= intensity;
  20415. this.color.g *= intensity;
  20416. this.color.b *= intensity;
  20417. var hexColor = this.color.getHex();
  20418. // light helper
  20419. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20420. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20421. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20422. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20423. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20424. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20425. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20426. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20427. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20428. var d = light.distance;
  20429. if ( d === 0.0 ) {
  20430. this.lightDistance.visible = false;
  20431. } else {
  20432. this.lightDistance.scale.set( d, d, d );
  20433. }
  20434. this.add( this.lightSphere );
  20435. this.add( this.lightRays );
  20436. this.add( this.lightDistance );
  20437. //
  20438. this.lightSphere.properties.isGizmo = true;
  20439. this.lightSphere.properties.gizmoSubject = light;
  20440. this.lightSphere.properties.gizmoRoot = this;
  20441. //
  20442. this.properties.isGizmo = true;
  20443. }
  20444. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20445. THREE.PointLightHelper.prototype.update = function () {
  20446. // update sphere and rays colors to light color * light intensity
  20447. this.color.copy( this.light.color );
  20448. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20449. this.color.r *= intensity;
  20450. this.color.g *= intensity;
  20451. this.color.b *= intensity;
  20452. this.lightSphere.material.color.copy( this.color );
  20453. this.lightRays.material.color.copy( this.color );
  20454. this.lightDistance.material.color.copy( this.color );
  20455. //
  20456. var d = this.light.distance;
  20457. if ( d === 0.0 ) {
  20458. this.lightDistance.visible = false;
  20459. } else {
  20460. this.lightDistance.visible = true;
  20461. this.lightDistance.scale.set( d, d, d );
  20462. }
  20463. }
  20464. /**
  20465. * @author alteredq / http://alteredqualia.com/
  20466. *
  20467. * - shows spot light color, intensity, position, orientation, light cone and target
  20468. */
  20469. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  20470. THREE.Object3D.call( this );
  20471. this.light = light;
  20472. // position
  20473. this.position = light.position;
  20474. // direction
  20475. this.direction = new THREE.Vector3();
  20476. this.direction.sub( light.target.position, light.position );
  20477. // color
  20478. this.color = light.color.clone();
  20479. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20480. this.color.r *= intensity;
  20481. this.color.g *= intensity;
  20482. this.color.b *= intensity;
  20483. var hexColor = this.color.getHex();
  20484. // light helper
  20485. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20486. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20487. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20488. var coneMatrix = new THREE.Matrix4();
  20489. coneMatrix.rotateX( -Math.PI/2 );
  20490. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20491. coneGeometry.applyMatrix( coneMatrix );
  20492. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20493. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20494. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20495. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  20496. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20497. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20498. var coneLength = light.distance ? light.distance : 10000;
  20499. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20500. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20501. this.lightArrow.cone.material.fog = false;
  20502. this.lightArrow.line.material.fog = false;
  20503. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20504. this.gyroscope = new THREE.Gyroscope();
  20505. this.gyroscope.add( this.lightArrow );
  20506. this.gyroscope.add( this.lightSphere );
  20507. this.gyroscope.add( this.lightRays );
  20508. this.add( this.gyroscope );
  20509. this.add( this.lightCone );
  20510. this.lookAt( light.target.position );
  20511. this.lightSphere.properties.isGizmo = true;
  20512. this.lightSphere.properties.gizmoSubject = light;
  20513. this.lightSphere.properties.gizmoRoot = this;
  20514. // light target helper
  20515. this.targetSphere = null;
  20516. if ( light.target.properties.targetInverse ) {
  20517. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20518. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20519. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20520. this.targetSphere.position = light.target.position;
  20521. this.targetSphere.properties.isGizmo = true;
  20522. this.targetSphere.properties.gizmoSubject = light.target;
  20523. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20524. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20525. var lineGeometry = new THREE.Geometry();
  20526. lineGeometry.vertices.push( this.position.clone() );
  20527. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20528. lineGeometry.computeLineDistances();
  20529. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20530. this.targetLine.properties.isGizmo = true;
  20531. }
  20532. //
  20533. this.properties.isGizmo = true;
  20534. }
  20535. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20536. THREE.SpotLightHelper.prototype.update = function () {
  20537. // update arrow orientation
  20538. // pointing from light to target
  20539. this.direction.sub( this.light.target.position, this.light.position );
  20540. this.lightArrow.setDirection( this.direction );
  20541. // update light cone orientation and size
  20542. this.lookAt( this.light.target.position );
  20543. var coneLength = this.light.distance ? this.light.distance : 10000;
  20544. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20545. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20546. // update arrow, spheres, rays and line colors to light color * light intensity
  20547. this.color.copy( this.light.color );
  20548. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20549. this.color.r *= intensity;
  20550. this.color.g *= intensity;
  20551. this.color.b *= intensity;
  20552. this.lightArrow.setColor( this.color.getHex() );
  20553. this.lightSphere.material.color.copy( this.color );
  20554. this.lightRays.material.color.copy( this.color );
  20555. this.lightCone.material.color.copy( this.color );
  20556. this.targetSphere.material.color.copy( this.color );
  20557. this.targetLine.material.color.copy( this.color );
  20558. // update target line vertices
  20559. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20560. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20561. this.targetLine.geometry.computeLineDistances();
  20562. this.targetLine.geometry.verticesNeedUpdate = true;
  20563. }
  20564. /*
  20565. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  20566. *
  20567. * Subdivision Geometry Modifier
  20568. * using Catmull-Clark Subdivision Surfaces
  20569. * for creating smooth geometry meshes
  20570. *
  20571. * Note: a modifier modifies vertices and faces of geometry,
  20572. * so use geometry.clone() if original geometry needs to be retained
  20573. *
  20574. * Readings:
  20575. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  20576. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  20577. * http://xrt.wikidot.com/blog:31
  20578. * "Subdivision Surfaces in Character Animation"
  20579. *
  20580. * (on boundary edges)
  20581. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  20582. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  20583. *
  20584. * Supports:
  20585. * Closed and Open geometries.
  20586. *
  20587. * TODO:
  20588. * crease vertex and "semi-sharp" features
  20589. * selective subdivision
  20590. */
  20591. THREE.SubdivisionModifier = function( subdivisions ) {
  20592. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  20593. // Settings
  20594. this.useOldVertexColors = false;
  20595. this.supportUVs = true;
  20596. this.debug = false;
  20597. };
  20598. // Applies the "modify" pattern
  20599. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  20600. var repeats = this.subdivisions;
  20601. while ( repeats-- > 0 ) {
  20602. this.smooth( geometry );
  20603. }
  20604. };
  20605. /// REFACTORING THIS OUT
  20606. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  20607. return Math.min( a, b ) + "_" + Math.max( a, b );
  20608. };
  20609. // Returns a hashmap - of { edge_key: face_index }
  20610. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  20611. var i, il, v1, v2, j, k,
  20612. face, faceIndices, faceIndex,
  20613. edge,
  20614. hash,
  20615. edgeFaceMap = {};
  20616. var orderedKey = THREE.GeometryUtils.orderedKey;
  20617. function mapEdgeHash( hash, i ) {
  20618. if ( edgeFaceMap[ hash ] === undefined ) {
  20619. edgeFaceMap[ hash ] = [];
  20620. }
  20621. edgeFaceMap[ hash ].push( i );
  20622. }
  20623. // construct vertex -> face map
  20624. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  20625. face = geometry.faces[ i ];
  20626. if ( face instanceof THREE.Face3 ) {
  20627. hash = orderedKey( face.a, face.b );
  20628. mapEdgeHash( hash, i );
  20629. hash = orderedKey( face.b, face.c );
  20630. mapEdgeHash( hash, i );
  20631. hash = orderedKey( face.c, face.a );
  20632. mapEdgeHash( hash, i );
  20633. } else if ( face instanceof THREE.Face4 ) {
  20634. hash = orderedKey( face.a, face.b );
  20635. mapEdgeHash( hash, i );
  20636. hash = orderedKey( face.b, face.c );
  20637. mapEdgeHash( hash, i );
  20638. hash = orderedKey( face.c, face.d );
  20639. mapEdgeHash( hash, i );
  20640. hash = orderedKey( face.d, face.a );
  20641. mapEdgeHash( hash, i );
  20642. }
  20643. }
  20644. // extract faces
  20645. // var edges = [];
  20646. //
  20647. // var numOfEdges = 0;
  20648. // for (i in edgeFaceMap) {
  20649. // numOfEdges++;
  20650. //
  20651. // edge = edgeFaceMap[i];
  20652. // edges.push(edge);
  20653. //
  20654. // }
  20655. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  20656. return edgeFaceMap;
  20657. }
  20658. /////////////////////////////
  20659. // Performs an iteration of Catmull-Clark Subdivision
  20660. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  20661. //debug( 'running smooth' );
  20662. // New set of vertices, faces and uvs
  20663. var newVertices = [], newFaces = [], newUVs = [];
  20664. function v( x, y, z ) {
  20665. newVertices.push( new THREE.Vector3( x, y, z ) );
  20666. }
  20667. var scope = this;
  20668. var orderedKey = THREE.GeometryUtils.orderedKey;
  20669. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  20670. function assert() {
  20671. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  20672. }
  20673. function debug() {
  20674. if (scope.debug) console.log.apply(console, arguments);
  20675. }
  20676. function warn() {
  20677. if (console)
  20678. console.log.apply(console, arguments);
  20679. }
  20680. function f4( a, b, c, d, oldFace, orders, facei ) {
  20681. // TODO move vertex selection over here!
  20682. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  20683. if (scope.useOldVertexColors) {
  20684. newFace.vertexColors = [];
  20685. var color, tmpColor, order;
  20686. for (var i=0;i<4;i++) {
  20687. order = orders[i];
  20688. color = new THREE.Color(),
  20689. color.setRGB(0,0,0);
  20690. for (var j=0, jl=0; j<order.length;j++) {
  20691. tmpColor = oldFace.vertexColors[order[j]-1];
  20692. color.r += tmpColor.r;
  20693. color.g += tmpColor.g;
  20694. color.b += tmpColor.b;
  20695. }
  20696. color.r /= order.length;
  20697. color.g /= order.length;
  20698. color.b /= order.length;
  20699. newFace.vertexColors[i] = color;
  20700. }
  20701. }
  20702. newFaces.push( newFace );
  20703. if (scope.supportUVs) {
  20704. var aUv = [
  20705. getUV(a, ''),
  20706. getUV(b, facei),
  20707. getUV(c, facei),
  20708. getUV(d, facei)
  20709. ];
  20710. if (!aUv[0]) debug('a :( ', a+':'+facei);
  20711. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  20712. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  20713. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  20714. else
  20715. newUVs.push( aUv );
  20716. }
  20717. }
  20718. var originalPoints = oldGeometry.vertices;
  20719. var originalFaces = oldGeometry.faces;
  20720. var originalVerticesLength = originalPoints.length;
  20721. var newPoints = originalPoints.concat(); // New set of vertices to work on
  20722. var facePoints = [], // these are new points on exisiting faces
  20723. edgePoints = {}; // these are new points on exisiting edges
  20724. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  20725. // TODO: handle this correctly.
  20726. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  20727. function debugCoreStuff() {
  20728. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  20729. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  20730. }
  20731. function getUV(vertexNo, oldFaceNo) {
  20732. var j,jl;
  20733. var key = vertexNo+':'+oldFaceNo;
  20734. var theUV = uvForVertices[key];
  20735. if (!theUV) {
  20736. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  20737. debug('face pt');
  20738. } else {
  20739. debug('edge pt');
  20740. }
  20741. warn('warning, UV not found for', key);
  20742. return null;
  20743. }
  20744. return theUV;
  20745. // Original faces -> Vertex Nos.
  20746. // new Facepoint -> Vertex Nos.
  20747. // edge Points
  20748. }
  20749. function addUV(vertexNo, oldFaceNo, value) {
  20750. var key = vertexNo+':'+oldFaceNo;
  20751. if (!(key in uvForVertices)) {
  20752. uvForVertices[key] = value;
  20753. } else {
  20754. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  20755. }
  20756. }
  20757. // Step 1
  20758. // For each face, add a face point
  20759. // Set each face point to be the centroid of all original points for the respective face.
  20760. // debug(oldGeometry);
  20761. var i, il, j, jl, face;
  20762. // For Uvs
  20763. var uvs = oldGeometry.faceVertexUvs[0];
  20764. var abcd = 'abcd', vertice;
  20765. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  20766. if (scope.supportUVs)
  20767. for (i=0, il = uvs.length; i<il; i++ ) {
  20768. for (j=0,jl=uvs[i].length;j<jl;j++) {
  20769. vertice = originalFaces[i][abcd.charAt(j)];
  20770. addUV(vertice, i, uvs[i][j]);
  20771. }
  20772. }
  20773. if (uvs.length == 0) scope.supportUVs = false;
  20774. // Additional UVs check, if we index original
  20775. var uvCount = 0;
  20776. for (var u in uvForVertices) {
  20777. uvCount++;
  20778. }
  20779. if (!uvCount) {
  20780. scope.supportUVs = false;
  20781. debug('no uvs');
  20782. }
  20783. var avgUv ;
  20784. for (i=0, il = originalFaces.length; i<il ;i++) {
  20785. face = originalFaces[ i ];
  20786. facePoints.push( face.centroid );
  20787. newPoints.push( face.centroid );
  20788. if (!scope.supportUVs) continue;
  20789. // Prepare subdivided uv
  20790. avgUv = new THREE.Vector2();
  20791. if ( face instanceof THREE.Face3 ) {
  20792. avgUv.x = getUV( face.a, i ).x + getUV( face.b, i ).x + getUV( face.c, i ).x;
  20793. avgUv.y = getUV( face.a, i ).y + getUV( face.b, i ).y + getUV( face.c, i ).y;
  20794. avgUv.x /= 3;
  20795. avgUv.y /= 3;
  20796. } else if ( face instanceof THREE.Face4 ) {
  20797. avgUv.x = getUV( face.a, i ).x + getUV( face.b, i ).x + getUV( face.c, i ).x + getUV( face.d, i ).x;
  20798. avgUv.y = getUV( face.a, i ).y + getUV( face.b, i ).y + getUV( face.c, i ).y + getUV( face.d, i ).y;
  20799. avgUv.x /= 4;
  20800. avgUv.y /= 4;
  20801. }
  20802. addUV(originalVerticesLength + i, '', avgUv);
  20803. }
  20804. // Step 2
  20805. // For each edge, add an edge point.
  20806. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  20807. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  20808. var edge, faceIndexA, faceIndexB, avg;
  20809. // debug('edgeFaceMap', edgeFaceMap);
  20810. var edgeCount = 0;
  20811. var edgeVertex, edgeVertexA, edgeVertexB;
  20812. ////
  20813. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  20814. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  20815. function addVertexEdgeMap(vertex, edge) {
  20816. if (vertexEdgeMap[vertex]===undefined) {
  20817. vertexEdgeMap[vertex] = [];
  20818. }
  20819. vertexEdgeMap[vertex].push(edge);
  20820. }
  20821. function addVertexFaceMap(vertex, face, edge) {
  20822. if (vertexFaceMap[vertex]===undefined) {
  20823. vertexFaceMap[vertex] = {};
  20824. }
  20825. vertexFaceMap[vertex][face] = edge;
  20826. // vertexFaceMap[vertex][face] = null;
  20827. }
  20828. // Prepares vertexEdgeMap and vertexFaceMap
  20829. for (i in edgeFaceMap) { // This is for every edge
  20830. edge = edgeFaceMap[i];
  20831. edgeVertex = i.split('_');
  20832. edgeVertexA = edgeVertex[0];
  20833. edgeVertexB = edgeVertex[1];
  20834. // Maps an edgeVertex to connecting edges
  20835. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  20836. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  20837. for (j=0,jl=edge.length;j<jl;j++) {
  20838. face = edge[j];
  20839. addVertexFaceMap(edgeVertexA, face, i);
  20840. addVertexFaceMap(edgeVertexB, face, i);
  20841. }
  20842. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  20843. // this thing is fishy right now.
  20844. if (edge.length < 2) {
  20845. // edge is "sharp";
  20846. sharpEdges[i] = true;
  20847. sharpVertices[edgeVertexA] = true;
  20848. sharpVertices[edgeVertexB] = true;
  20849. }
  20850. }
  20851. for (i in edgeFaceMap) {
  20852. edge = edgeFaceMap[i];
  20853. faceIndexA = edge[0]; // face index a
  20854. faceIndexB = edge[1]; // face index b
  20855. edgeVertex = i.split('_');
  20856. edgeVertexA = edgeVertex[0];
  20857. edgeVertexB = edgeVertex[1];
  20858. avg = new THREE.Vector3();
  20859. //debug(i, faceIndexB,facePoints[faceIndexB]);
  20860. assert(edge.length > 0, 'an edge without faces?!');
  20861. if (edge.length==1) {
  20862. avg.addSelf(originalPoints[edgeVertexA]);
  20863. avg.addSelf(originalPoints[edgeVertexB]);
  20864. avg.multiplyScalar(0.5);
  20865. sharpVertices[newPoints.length] = true;
  20866. } else {
  20867. avg.addSelf(facePoints[faceIndexA]);
  20868. avg.addSelf(facePoints[faceIndexB]);
  20869. avg.addSelf(originalPoints[edgeVertexA]);
  20870. avg.addSelf(originalPoints[edgeVertexB]);
  20871. avg.multiplyScalar(0.25);
  20872. }
  20873. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  20874. newPoints.push( avg );
  20875. edgeCount ++;
  20876. if (!scope.supportUVs) {
  20877. continue;
  20878. }
  20879. // Prepare subdivided uv
  20880. avgUv = new THREE.Vector2();
  20881. avgUv.x = getUV(edgeVertexA, faceIndexA).x + getUV(edgeVertexB, faceIndexA).x;
  20882. avgUv.y = getUV(edgeVertexA, faceIndexA).y + getUV(edgeVertexB, faceIndexA).y;
  20883. avgUv.x /= 2;
  20884. avgUv.y /= 2;
  20885. addUV(edgePoints[i], faceIndexA, avgUv);
  20886. if (edge.length>=2) {
  20887. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  20888. avgUv = new THREE.Vector2();
  20889. avgUv.x = getUV(edgeVertexA, faceIndexB).x + getUV(edgeVertexB, faceIndexB).x;
  20890. avgUv.y = getUV(edgeVertexA, faceIndexB).y + getUV(edgeVertexB, faceIndexB).y;
  20891. avgUv.x /= 2;
  20892. avgUv.y /= 2;
  20893. addUV(edgePoints[i], faceIndexB, avgUv);
  20894. }
  20895. }
  20896. debug('-- Step 2 done');
  20897. // Step 3
  20898. // For each face point, add an edge for every edge of the face,
  20899. // connecting the face point to each edge point for the face.
  20900. var facePt, currentVerticeIndex;
  20901. var hashAB, hashBC, hashCD, hashDA, hashCA;
  20902. var abc123 = ['123', '12', '2', '23'];
  20903. var bca123 = ['123', '23', '3', '31'];
  20904. var cab123 = ['123', '31', '1', '12'];
  20905. var abc1234 = ['1234', '12', '2', '23'];
  20906. var bcd1234 = ['1234', '23', '3', '34'];
  20907. var cda1234 = ['1234', '34', '4', '41'];
  20908. var dab1234 = ['1234', '41', '1', '12'];
  20909. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  20910. facePt = facePoints[i];
  20911. face = originalFaces[i];
  20912. currentVerticeIndex = originalVerticesLength+ i;
  20913. if ( face instanceof THREE.Face3 ) {
  20914. // create 3 face4s
  20915. hashAB = orderedKey( face.a, face.b );
  20916. hashBC = orderedKey( face.b, face.c );
  20917. hashCA = orderedKey( face.c, face.a );
  20918. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  20919. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  20920. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  20921. } else if ( face instanceof THREE.Face4 ) {
  20922. // create 4 face4s
  20923. hashAB = orderedKey( face.a, face.b );
  20924. hashBC = orderedKey( face.b, face.c );
  20925. hashCD = orderedKey( face.c, face.d );
  20926. hashDA = orderedKey( face.d, face.a );
  20927. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  20928. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  20929. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  20930. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  20931. } else {
  20932. debug('face should be a face!', face);
  20933. }
  20934. }
  20935. newVertices = newPoints;
  20936. // Step 4
  20937. // For each original point P,
  20938. // take the average F of all n face points for faces touching P,
  20939. // and take the average R of all n edge midpoints for edges touching P,
  20940. // where each edge midpoint is the average of its two endpoint vertices.
  20941. // Move each original point to the point
  20942. var F = new THREE.Vector3();
  20943. var R = new THREE.Vector3();
  20944. var n;
  20945. for (i=0, il = originalPoints.length; i<il; i++) {
  20946. // (F + 2R + (n-3)P) / n
  20947. if (vertexEdgeMap[i]===undefined) continue;
  20948. F.set(0,0,0);
  20949. R.set(0,0,0);
  20950. var newPos = new THREE.Vector3(0,0,0);
  20951. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  20952. for (j in vertexFaceMap[i]) {
  20953. F.addSelf(facePoints[j]);
  20954. f++;
  20955. }
  20956. var sharpEdgeCount = 0;
  20957. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  20958. // Are we on the border?
  20959. var boundary_case = f != n;
  20960. // if (boundary_case) {
  20961. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  20962. // }
  20963. for (j=0;j<n;j++) {
  20964. if (
  20965. sharpEdges[
  20966. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20967. ]) {
  20968. sharpEdgeCount++;
  20969. }
  20970. }
  20971. // if ( sharpEdgeCount==2 ) {
  20972. // continue;
  20973. // // Do not move vertex if there's 2 connecting sharp edges.
  20974. // }
  20975. /*
  20976. if (sharpEdgeCount>2) {
  20977. // TODO
  20978. }
  20979. */
  20980. F.divideScalar(f);
  20981. var boundary_edges = 0;
  20982. if (boundary_case) {
  20983. var bb_edge;
  20984. for (j=0; j<n;j++) {
  20985. edge = vertexEdgeMap[i][j];
  20986. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  20987. if (bb_edge) {
  20988. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20989. R.addSelf(midPt);
  20990. boundary_edges++;
  20991. }
  20992. }
  20993. R.divideScalar(4);
  20994. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  20995. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  20996. } else {
  20997. for (j=0; j<n;j++) {
  20998. edge = vertexEdgeMap[i][j];
  20999. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  21000. R.addSelf(midPt);
  21001. }
  21002. R.divideScalar(n);
  21003. }
  21004. // Sum the formula
  21005. newPos.addSelf(originalPoints[i]);
  21006. if (boundary_case) {
  21007. newPos.divideScalar(2);
  21008. newPos.addSelf(R);
  21009. } else {
  21010. newPos.multiplyScalar(n - 3);
  21011. newPos.addSelf(F);
  21012. newPos.addSelf(R.multiplyScalar(2));
  21013. newPos.divideScalar(n);
  21014. }
  21015. newVertices[i] = newPos;
  21016. }
  21017. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  21018. newGeometry.vertices = newVertices;
  21019. newGeometry.faces = newFaces;
  21020. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  21021. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  21022. newGeometry.computeCentroids();
  21023. newGeometry.computeFaceNormals();
  21024. newGeometry.computeVertexNormals();
  21025. };
  21026. /**
  21027. * @author alteredq / http://alteredqualia.com/
  21028. */
  21029. THREE.ImmediateRenderObject = function ( ) {
  21030. THREE.Object3D.call( this );
  21031. this.render = function ( renderCallback ) { };
  21032. };
  21033. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21034. /**
  21035. * @author mikael emtinger / http://gomo.se/
  21036. * @author alteredq / http://alteredqualia.com/
  21037. */
  21038. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21039. THREE.Object3D.call( this );
  21040. this.lensFlares = [];
  21041. this.positionScreen = new THREE.Vector3();
  21042. this.customUpdateCallback = undefined;
  21043. if( texture !== undefined ) {
  21044. this.add( texture, size, distance, blending, color );
  21045. }
  21046. };
  21047. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21048. /*
  21049. * Add: adds another flare
  21050. */
  21051. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21052. if( size === undefined ) size = -1;
  21053. if( distance === undefined ) distance = 0;
  21054. if( opacity === undefined ) opacity = 1;
  21055. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21056. if( blending === undefined ) blending = THREE.NormalBlending;
  21057. distance = Math.min( distance, Math.max( 0, distance ) );
  21058. this.lensFlares.push( { texture: texture, // THREE.Texture
  21059. size: size, // size in pixels (-1 = use texture.width)
  21060. distance: distance, // distance (0-1) from light source (0=at light source)
  21061. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21062. scale: 1, // scale
  21063. rotation: 1, // rotation
  21064. opacity: opacity, // opacity
  21065. color: color, // color
  21066. blending: blending } ); // blending
  21067. };
  21068. /*
  21069. * Update lens flares update positions on all flares based on the screen position
  21070. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21071. */
  21072. THREE.LensFlare.prototype.updateLensFlares = function () {
  21073. var f, fl = this.lensFlares.length;
  21074. var flare;
  21075. var vecX = -this.positionScreen.x * 2;
  21076. var vecY = -this.positionScreen.y * 2;
  21077. for( f = 0; f < fl; f ++ ) {
  21078. flare = this.lensFlares[ f ];
  21079. flare.x = this.positionScreen.x + vecX * flare.distance;
  21080. flare.y = this.positionScreen.y + vecY * flare.distance;
  21081. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21082. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21083. }
  21084. };
  21085. /**
  21086. * @author alteredq / http://alteredqualia.com/
  21087. */
  21088. THREE.MorphBlendMesh = function( geometry, material ) {
  21089. THREE.Mesh.call( this, geometry, material );
  21090. this.animationsMap = {};
  21091. this.animationsList = [];
  21092. // prepare default animation
  21093. // (all frames played together in 1 second)
  21094. var numFrames = this.geometry.morphTargets.length;
  21095. var name = "__default";
  21096. var startFrame = 0;
  21097. var endFrame = numFrames - 1;
  21098. var fps = numFrames / 1;
  21099. this.createAnimation( name, startFrame, endFrame, fps );
  21100. this.setAnimationWeight( name, 1 );
  21101. };
  21102. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21103. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21104. var animation = {
  21105. startFrame: start,
  21106. endFrame: end,
  21107. length: end - start + 1,
  21108. fps: fps,
  21109. duration: ( end - start ) / fps,
  21110. lastFrame: 0,
  21111. currentFrame: 0,
  21112. active: false,
  21113. time: 0,
  21114. direction: 1,
  21115. weight: 1,
  21116. directionBackwards: false,
  21117. mirroredLoop: false
  21118. };
  21119. this.animationsMap[ name ] = animation;
  21120. this.animationsList.push( animation );
  21121. };
  21122. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21123. var pattern = /([a-z]+)(\d+)/;
  21124. var firstAnimation, frameRanges = {};
  21125. var geometry = this.geometry;
  21126. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21127. var morph = geometry.morphTargets[ i ];
  21128. var chunks = morph.name.match( pattern );
  21129. if ( chunks && chunks.length > 1 ) {
  21130. var name = chunks[ 1 ];
  21131. var num = chunks[ 2 ];
  21132. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21133. var range = frameRanges[ name ];
  21134. if ( i < range.start ) range.start = i;
  21135. if ( i > range.end ) range.end = i;
  21136. if ( ! firstAnimation ) firstAnimation = name;
  21137. }
  21138. }
  21139. for ( var name in frameRanges ) {
  21140. var range = frameRanges[ name ];
  21141. this.createAnimation( name, range.start, range.end, fps );
  21142. }
  21143. this.firstAnimation = firstAnimation;
  21144. };
  21145. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21146. var animation = this.animationsMap[ name ];
  21147. if ( animation ) {
  21148. animation.direction = 1;
  21149. animation.directionBackwards = false;
  21150. }
  21151. };
  21152. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21153. var animation = this.animationsMap[ name ];
  21154. if ( animation ) {
  21155. animation.direction = -1;
  21156. animation.directionBackwards = true;
  21157. }
  21158. };
  21159. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21160. var animation = this.animationsMap[ name ];
  21161. if ( animation ) {
  21162. animation.fps = fps;
  21163. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21164. }
  21165. };
  21166. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21167. var animation = this.animationsMap[ name ];
  21168. if ( animation ) {
  21169. animation.duration = duration;
  21170. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21171. }
  21172. };
  21173. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21174. var animation = this.animationsMap[ name ];
  21175. if ( animation ) {
  21176. animation.weight = weight;
  21177. }
  21178. };
  21179. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21180. var animation = this.animationsMap[ name ];
  21181. if ( animation ) {
  21182. animation.time = time;
  21183. }
  21184. };
  21185. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21186. var time = 0;
  21187. var animation = this.animationsMap[ name ];
  21188. if ( animation ) {
  21189. time = animation.time;
  21190. }
  21191. return time;
  21192. };
  21193. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21194. var duration = -1;
  21195. var animation = this.animationsMap[ name ];
  21196. if ( animation ) {
  21197. duration = animation.duration;
  21198. }
  21199. return duration;
  21200. };
  21201. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21202. var animation = this.animationsMap[ name ];
  21203. if ( animation ) {
  21204. animation.time = 0;
  21205. animation.active = true;
  21206. } else {
  21207. console.warn( "animation[" + name + "] undefined" );
  21208. }
  21209. };
  21210. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21211. var animation = this.animationsMap[ name ];
  21212. if ( animation ) {
  21213. animation.active = false;
  21214. }
  21215. };
  21216. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21217. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21218. var animation = this.animationsList[ i ];
  21219. if ( ! animation.active ) continue;
  21220. var frameTime = animation.duration / animation.length;
  21221. animation.time += animation.direction * delta;
  21222. if ( animation.mirroredLoop ) {
  21223. if ( animation.time > animation.duration || animation.time < 0 ) {
  21224. animation.direction *= -1;
  21225. if ( animation.time > animation.duration ) {
  21226. animation.time = animation.duration;
  21227. animation.directionBackwards = true;
  21228. }
  21229. if ( animation.time < 0 ) {
  21230. animation.time = 0;
  21231. animation.directionBackwards = false;
  21232. }
  21233. }
  21234. } else {
  21235. animation.time = animation.time % animation.duration;
  21236. if ( animation.time < 0 ) animation.time += animation.duration;
  21237. }
  21238. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21239. var weight = animation.weight;
  21240. if ( keyframe !== animation.currentFrame ) {
  21241. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21242. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21243. this.morphTargetInfluences[ keyframe ] = 0;
  21244. animation.lastFrame = animation.currentFrame;
  21245. animation.currentFrame = keyframe;
  21246. }
  21247. var mix = ( animation.time % frameTime ) / frameTime;
  21248. if ( animation.directionBackwards ) mix = 1 - mix;
  21249. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21250. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21251. }
  21252. };
  21253. /**
  21254. * @author mikael emtinger / http://gomo.se/
  21255. * @author alteredq / http://alteredqualia.com/
  21256. */
  21257. THREE.LensFlarePlugin = function ( ) {
  21258. var _gl, _renderer, _lensFlare = {};
  21259. this.init = function ( renderer ) {
  21260. _gl = renderer.context;
  21261. _renderer = renderer;
  21262. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21263. _lensFlare.faces = new Uint16Array( 6 );
  21264. var i = 0;
  21265. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21266. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21267. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21268. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21269. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21270. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21271. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21272. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21273. i = 0;
  21274. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21275. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21276. // buffers
  21277. _lensFlare.vertexBuffer = _gl.createBuffer();
  21278. _lensFlare.elementBuffer = _gl.createBuffer();
  21279. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21280. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21281. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21282. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21283. // textures
  21284. _lensFlare.tempTexture = _gl.createTexture();
  21285. _lensFlare.occlusionTexture = _gl.createTexture();
  21286. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21287. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21288. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21289. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21290. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21291. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21292. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21293. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21294. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21295. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21296. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21297. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21298. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21299. _lensFlare.hasVertexTexture = false;
  21300. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  21301. } else {
  21302. _lensFlare.hasVertexTexture = true;
  21303. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  21304. }
  21305. _lensFlare.attributes = {};
  21306. _lensFlare.uniforms = {};
  21307. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21308. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21309. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21310. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21311. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21312. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21313. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21314. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21315. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21316. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21317. };
  21318. /*
  21319. * Render lens flares
  21320. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21321. * reads these back and calculates occlusion.
  21322. * Then _lensFlare.update_lensFlares() is called to re-position and
  21323. * update transparency of flares. Then they are rendered.
  21324. *
  21325. */
  21326. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21327. var flares = scene.__webglFlares,
  21328. nFlares = flares.length;
  21329. if ( ! nFlares ) return;
  21330. var tempPosition = new THREE.Vector3();
  21331. var invAspect = viewportHeight / viewportWidth,
  21332. halfViewportWidth = viewportWidth * 0.5,
  21333. halfViewportHeight = viewportHeight * 0.5;
  21334. var size = 16 / viewportHeight,
  21335. scale = new THREE.Vector2( size * invAspect, size );
  21336. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21337. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21338. var uniforms = _lensFlare.uniforms,
  21339. attributes = _lensFlare.attributes;
  21340. // set _lensFlare program and reset blending
  21341. _gl.useProgram( _lensFlare.program );
  21342. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21343. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21344. // loop through all lens flares to update their occlusion and positions
  21345. // setup gl and common used attribs/unforms
  21346. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21347. _gl.uniform1i( uniforms.map, 1 );
  21348. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21349. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21350. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21351. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21352. _gl.disable( _gl.CULL_FACE );
  21353. _gl.depthMask( false );
  21354. var i, j, jl, flare, sprite;
  21355. for ( i = 0; i < nFlares; i ++ ) {
  21356. size = 16 / viewportHeight;
  21357. scale.set( size * invAspect, size );
  21358. // calc object screen position
  21359. flare = flares[ i ];
  21360. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21361. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  21362. camera.projectionMatrix.multiplyVector3( tempPosition );
  21363. // setup arrays for gl programs
  21364. screenPosition.copy( tempPosition )
  21365. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21366. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21367. // screen cull
  21368. if ( _lensFlare.hasVertexTexture || (
  21369. screenPositionPixels.x > 0 &&
  21370. screenPositionPixels.x < viewportWidth &&
  21371. screenPositionPixels.y > 0 &&
  21372. screenPositionPixels.y < viewportHeight ) ) {
  21373. // save current RGB to temp texture
  21374. _gl.activeTexture( _gl.TEXTURE1 );
  21375. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21376. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21377. // render pink quad
  21378. _gl.uniform1i( uniforms.renderType, 0 );
  21379. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21380. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21381. _gl.disable( _gl.BLEND );
  21382. _gl.enable( _gl.DEPTH_TEST );
  21383. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21384. // copy result to occlusionMap
  21385. _gl.activeTexture( _gl.TEXTURE0 );
  21386. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21387. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21388. // restore graphics
  21389. _gl.uniform1i( uniforms.renderType, 1 );
  21390. _gl.disable( _gl.DEPTH_TEST );
  21391. _gl.activeTexture( _gl.TEXTURE1 );
  21392. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21393. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21394. // update object positions
  21395. flare.positionScreen.copy( screenPosition )
  21396. if ( flare.customUpdateCallback ) {
  21397. flare.customUpdateCallback( flare );
  21398. } else {
  21399. flare.updateLensFlares();
  21400. }
  21401. // render flares
  21402. _gl.uniform1i( uniforms.renderType, 2 );
  21403. _gl.enable( _gl.BLEND );
  21404. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21405. sprite = flare.lensFlares[ j ];
  21406. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21407. screenPosition.x = sprite.x;
  21408. screenPosition.y = sprite.y;
  21409. screenPosition.z = sprite.z;
  21410. size = sprite.size * sprite.scale / viewportHeight;
  21411. scale.x = size * invAspect;
  21412. scale.y = size;
  21413. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21414. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21415. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21416. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21417. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21418. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21419. _renderer.setTexture( sprite.texture, 1 );
  21420. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21421. }
  21422. }
  21423. }
  21424. }
  21425. // restore gl
  21426. _gl.enable( _gl.CULL_FACE );
  21427. _gl.enable( _gl.DEPTH_TEST );
  21428. _gl.depthMask( true );
  21429. };
  21430. function createProgram ( shader ) {
  21431. var program = _gl.createProgram();
  21432. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21433. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21434. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21435. _gl.shaderSource( vertexShader, shader.vertexShader );
  21436. _gl.compileShader( fragmentShader );
  21437. _gl.compileShader( vertexShader );
  21438. _gl.attachShader( program, fragmentShader );
  21439. _gl.attachShader( program, vertexShader );
  21440. _gl.linkProgram( program );
  21441. return program;
  21442. };
  21443. };/**
  21444. * @author alteredq / http://alteredqualia.com/
  21445. */
  21446. THREE.ShadowMapPlugin = function ( ) {
  21447. var _gl,
  21448. _renderer,
  21449. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21450. _frustum = new THREE.Frustum(),
  21451. _projScreenMatrix = new THREE.Matrix4(),
  21452. _min = new THREE.Vector3(),
  21453. _max = new THREE.Vector3();
  21454. this.init = function ( renderer ) {
  21455. _gl = renderer.context;
  21456. _renderer = renderer;
  21457. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21458. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21459. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21460. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21461. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21462. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21463. _depthMaterial._shadowPass = true;
  21464. _depthMaterialMorph._shadowPass = true;
  21465. _depthMaterialSkin._shadowPass = true;
  21466. _depthMaterialMorphSkin._shadowPass = true;
  21467. };
  21468. this.render = function ( scene, camera ) {
  21469. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21470. this.update( scene, camera );
  21471. };
  21472. this.update = function ( scene, camera ) {
  21473. var i, il, j, jl, n,
  21474. shadowMap, shadowMatrix, shadowCamera,
  21475. program, buffer, material,
  21476. webglObject, object, light,
  21477. renderList,
  21478. lights = [],
  21479. k = 0,
  21480. fog = null;
  21481. // set GL state for depth map
  21482. _gl.clearColor( 1, 1, 1, 1 );
  21483. _gl.disable( _gl.BLEND );
  21484. _gl.enable( _gl.CULL_FACE );
  21485. _gl.frontFace( _gl.CCW );
  21486. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21487. _gl.cullFace( _gl.FRONT );
  21488. } else {
  21489. _gl.cullFace( _gl.BACK );
  21490. }
  21491. _renderer.setDepthTest( true );
  21492. // preprocess lights
  21493. // - skip lights that are not casting shadows
  21494. // - create virtual lights for cascaded shadow maps
  21495. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21496. light = scene.__lights[ i ];
  21497. if ( ! light.castShadow ) continue;
  21498. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21499. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21500. var virtualLight;
  21501. if ( ! light.shadowCascadeArray[ n ] ) {
  21502. virtualLight = createVirtualLight( light, n );
  21503. virtualLight.originalCamera = camera;
  21504. var gyro = new THREE.Gyroscope();
  21505. gyro.position = light.shadowCascadeOffset;
  21506. gyro.add( virtualLight );
  21507. gyro.add( virtualLight.target );
  21508. camera.add( gyro );
  21509. light.shadowCascadeArray[ n ] = virtualLight;
  21510. console.log( "Created virtualLight", virtualLight );
  21511. } else {
  21512. virtualLight = light.shadowCascadeArray[ n ];
  21513. }
  21514. updateVirtualLight( light, n );
  21515. lights[ k ] = virtualLight;
  21516. k ++;
  21517. }
  21518. } else {
  21519. lights[ k ] = light;
  21520. k ++;
  21521. }
  21522. }
  21523. // render depth map
  21524. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21525. light = lights[ i ];
  21526. if ( ! light.shadowMap ) {
  21527. var shadowFilter = THREE.LinearFilter;
  21528. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21529. shadowFilter = THREE.NearestFilter;
  21530. }
  21531. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21532. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21533. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21534. light.shadowMatrix = new THREE.Matrix4();
  21535. }
  21536. if ( ! light.shadowCamera ) {
  21537. if ( light instanceof THREE.SpotLight ) {
  21538. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21539. } else if ( light instanceof THREE.DirectionalLight ) {
  21540. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21541. } else {
  21542. console.error( "Unsupported light type for shadow" );
  21543. continue;
  21544. }
  21545. scene.add( light.shadowCamera );
  21546. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21547. }
  21548. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21549. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21550. light.shadowCamera.add( light.cameraHelper );
  21551. }
  21552. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21553. updateShadowCamera( camera, light );
  21554. }
  21555. shadowMap = light.shadowMap;
  21556. shadowMatrix = light.shadowMatrix;
  21557. shadowCamera = light.shadowCamera;
  21558. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21559. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21560. shadowCamera.updateMatrixWorld();
  21561. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21562. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21563. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21564. // compute shadow matrix
  21565. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21566. 0.0, 0.5, 0.0, 0.5,
  21567. 0.0, 0.0, 0.5, 0.5,
  21568. 0.0, 0.0, 0.0, 1.0 );
  21569. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21570. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21571. // update camera matrices and frustum
  21572. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21573. _frustum.setFromMatrix( _projScreenMatrix );
  21574. // render shadow map
  21575. _renderer.setRenderTarget( shadowMap );
  21576. _renderer.clear();
  21577. // set object matrices & frustum culling
  21578. renderList = scene.__webglObjects;
  21579. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21580. webglObject = renderList[ j ];
  21581. object = webglObject.object;
  21582. webglObject.render = false;
  21583. if ( object.visible && object.castShadow ) {
  21584. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21585. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21586. webglObject.render = true;
  21587. }
  21588. }
  21589. }
  21590. // render regular objects
  21591. var objectMaterial, useMorphing, useSkinning;
  21592. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21593. webglObject = renderList[ j ];
  21594. if ( webglObject.render ) {
  21595. object = webglObject.object;
  21596. buffer = webglObject.buffer;
  21597. // culling is overriden globally for all objects
  21598. // while rendering depth map
  21599. // need to deal with MeshFaceMaterial somehow
  21600. // in that case just use the first of material.materials for now
  21601. // (proper solution would require to break objects by materials
  21602. // similarly to regular rendering and then set corresponding
  21603. // depth materials per each chunk instead of just once per object)
  21604. objectMaterial = getObjectMaterial( object );
  21605. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21606. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21607. if ( object.customDepthMaterial ) {
  21608. material = object.customDepthMaterial;
  21609. } else if ( useSkinning ) {
  21610. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21611. } else if ( useMorphing ) {
  21612. material = _depthMaterialMorph;
  21613. } else {
  21614. material = _depthMaterial;
  21615. }
  21616. if ( buffer instanceof THREE.BufferGeometry ) {
  21617. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21618. } else {
  21619. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21620. }
  21621. }
  21622. }
  21623. // set matrices and render immediate objects
  21624. renderList = scene.__webglObjectsImmediate;
  21625. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21626. webglObject = renderList[ j ];
  21627. object = webglObject.object;
  21628. if ( object.visible && object.castShadow ) {
  21629. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21630. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21631. }
  21632. }
  21633. }
  21634. // restore GL state
  21635. var clearColor = _renderer.getClearColor(),
  21636. clearAlpha = _renderer.getClearAlpha();
  21637. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21638. _gl.enable( _gl.BLEND );
  21639. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21640. _gl.cullFace( _gl.BACK );
  21641. }
  21642. };
  21643. function createVirtualLight( light, cascade ) {
  21644. var virtualLight = new THREE.DirectionalLight();
  21645. virtualLight.isVirtual = true;
  21646. virtualLight.onlyShadow = true;
  21647. virtualLight.castShadow = true;
  21648. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21649. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21650. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21651. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21652. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21653. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21654. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21655. virtualLight.shadowDarkness = light.shadowDarkness;
  21656. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21657. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21658. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21659. virtualLight.pointsWorld = [];
  21660. virtualLight.pointsFrustum = [];
  21661. var pointsWorld = virtualLight.pointsWorld,
  21662. pointsFrustum = virtualLight.pointsFrustum;
  21663. for ( var i = 0; i < 8; i ++ ) {
  21664. pointsWorld[ i ] = new THREE.Vector3();
  21665. pointsFrustum[ i ] = new THREE.Vector3();
  21666. }
  21667. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21668. var farZ = light.shadowCascadeFarZ[ cascade ];
  21669. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21670. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21671. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21672. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21673. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21674. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21675. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21676. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21677. return virtualLight;
  21678. }
  21679. // Synchronize virtual light with the original light
  21680. function updateVirtualLight( light, cascade ) {
  21681. var virtualLight = light.shadowCascadeArray[ cascade ];
  21682. virtualLight.position.copy( light.position );
  21683. virtualLight.target.position.copy( light.target.position );
  21684. virtualLight.lookAt( virtualLight.target );
  21685. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21686. virtualLight.shadowDarkness = light.shadowDarkness;
  21687. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21688. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21689. var farZ = light.shadowCascadeFarZ[ cascade ];
  21690. var pointsFrustum = virtualLight.pointsFrustum;
  21691. pointsFrustum[ 0 ].z = nearZ;
  21692. pointsFrustum[ 1 ].z = nearZ;
  21693. pointsFrustum[ 2 ].z = nearZ;
  21694. pointsFrustum[ 3 ].z = nearZ;
  21695. pointsFrustum[ 4 ].z = farZ;
  21696. pointsFrustum[ 5 ].z = farZ;
  21697. pointsFrustum[ 6 ].z = farZ;
  21698. pointsFrustum[ 7 ].z = farZ;
  21699. }
  21700. // Fit shadow camera's ortho frustum to camera frustum
  21701. function updateShadowCamera( camera, light ) {
  21702. var shadowCamera = light.shadowCamera,
  21703. pointsFrustum = light.pointsFrustum,
  21704. pointsWorld = light.pointsWorld;
  21705. _min.set( Infinity, Infinity, Infinity );
  21706. _max.set( -Infinity, -Infinity, -Infinity );
  21707. for ( var i = 0; i < 8; i ++ ) {
  21708. var p = pointsWorld[ i ];
  21709. p.copy( pointsFrustum[ i ] );
  21710. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21711. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21712. if ( p.x < _min.x ) _min.x = p.x;
  21713. if ( p.x > _max.x ) _max.x = p.x;
  21714. if ( p.y < _min.y ) _min.y = p.y;
  21715. if ( p.y > _max.y ) _max.y = p.y;
  21716. if ( p.z < _min.z ) _min.z = p.z;
  21717. if ( p.z > _max.z ) _max.z = p.z;
  21718. }
  21719. shadowCamera.left = _min.x;
  21720. shadowCamera.right = _max.x;
  21721. shadowCamera.top = _max.y;
  21722. shadowCamera.bottom = _min.y;
  21723. // can't really fit near/far
  21724. //shadowCamera.near = _min.z;
  21725. //shadowCamera.far = _max.z;
  21726. shadowCamera.updateProjectionMatrix();
  21727. }
  21728. // For the moment just ignore objects that have multiple materials with different animation methods
  21729. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21730. function getObjectMaterial( object ) {
  21731. return object.material instanceof THREE.MeshFaceMaterial
  21732. ? object.material.materials[ 0 ]
  21733. : object.material;
  21734. };
  21735. };
  21736. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21737. /**
  21738. * @author mikael emtinger / http://gomo.se/
  21739. * @author alteredq / http://alteredqualia.com/
  21740. */
  21741. THREE.SpritePlugin = function ( ) {
  21742. var _gl, _renderer, _sprite = {};
  21743. this.init = function ( renderer ) {
  21744. _gl = renderer.context;
  21745. _renderer = renderer;
  21746. _sprite.vertices = new Float32Array( 8 + 8 );
  21747. _sprite.faces = new Uint16Array( 6 );
  21748. var i = 0;
  21749. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21750. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21751. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21752. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21753. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21754. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21755. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21756. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21757. i = 0;
  21758. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21759. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21760. _sprite.vertexBuffer = _gl.createBuffer();
  21761. _sprite.elementBuffer = _gl.createBuffer();
  21762. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21763. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21764. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21765. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21766. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21767. _sprite.attributes = {};
  21768. _sprite.uniforms = {};
  21769. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21770. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21771. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21772. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21773. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21774. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21775. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21776. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21777. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21778. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21779. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21780. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21781. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21782. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21783. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21784. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21785. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21786. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21787. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21788. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21789. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21790. };
  21791. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21792. var sprites = scene.__webglSprites,
  21793. nSprites = sprites.length;
  21794. if ( ! nSprites ) return;
  21795. var attributes = _sprite.attributes,
  21796. uniforms = _sprite.uniforms;
  21797. var invAspect = viewportHeight / viewportWidth;
  21798. var halfViewportWidth = viewportWidth * 0.5,
  21799. halfViewportHeight = viewportHeight * 0.5;
  21800. // setup gl
  21801. _gl.useProgram( _sprite.program );
  21802. _gl.enableVertexAttribArray( attributes.position );
  21803. _gl.enableVertexAttribArray( attributes.uv );
  21804. _gl.disable( _gl.CULL_FACE );
  21805. _gl.enable( _gl.BLEND );
  21806. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21807. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21808. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21809. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21810. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21811. _gl.activeTexture( _gl.TEXTURE0 );
  21812. _gl.uniform1i( uniforms.map, 0 );
  21813. var oldFogType = 0;
  21814. var sceneFogType = 0;
  21815. var fog = scene.fog;
  21816. if ( fog ) {
  21817. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21818. if ( fog instanceof THREE.Fog ) {
  21819. _gl.uniform1f( uniforms.fogNear, fog.near );
  21820. _gl.uniform1f( uniforms.fogFar, fog.far );
  21821. _gl.uniform1i( uniforms.fogType, 1 );
  21822. oldFogType = 1;
  21823. sceneFogType = 1;
  21824. } else if ( fog instanceof THREE.FogExp2 ) {
  21825. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21826. _gl.uniform1i( uniforms.fogType, 2 );
  21827. oldFogType = 2;
  21828. sceneFogType = 2;
  21829. }
  21830. } else {
  21831. _gl.uniform1i( uniforms.fogType, 0 );
  21832. oldFogType = 0;
  21833. sceneFogType = 0;
  21834. }
  21835. // update positions and sort
  21836. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21837. for( i = 0; i < nSprites; i ++ ) {
  21838. sprite = sprites[ i ];
  21839. material = sprite.material;
  21840. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21841. if ( ! material.useScreenCoordinates ) {
  21842. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21843. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21844. } else {
  21845. sprite.z = - sprite.position.z;
  21846. }
  21847. }
  21848. sprites.sort( painterSortStable );
  21849. // render all sprites
  21850. for( i = 0; i < nSprites; i ++ ) {
  21851. sprite = sprites[ i ];
  21852. material = sprite.material;
  21853. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21854. if ( material.map && material.map.image && material.map.image.width ) {
  21855. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21856. if ( material.useScreenCoordinates ) {
  21857. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21858. _gl.uniform3f(
  21859. uniforms.screenPosition,
  21860. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21861. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21862. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21863. );
  21864. } else {
  21865. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21866. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21867. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21868. }
  21869. if ( scene.fog && material.fog ) {
  21870. fogType = sceneFogType;
  21871. } else {
  21872. fogType = 0;
  21873. }
  21874. if ( oldFogType !== fogType ) {
  21875. _gl.uniform1i( uniforms.fogType, fogType );
  21876. oldFogType = fogType;
  21877. }
  21878. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21879. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21880. scale[ 1 ] = size * sprite.scale.y;
  21881. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21882. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21883. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21884. _gl.uniform1f( uniforms.opacity, material.opacity );
  21885. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21886. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21887. _gl.uniform2fv( uniforms.scale, scale );
  21888. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21889. _renderer.setDepthTest( material.depthTest );
  21890. _renderer.setDepthWrite( material.depthWrite );
  21891. _renderer.setTexture( material.map, 0 );
  21892. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21893. }
  21894. }
  21895. // restore gl
  21896. _gl.enable( _gl.CULL_FACE );
  21897. };
  21898. function createProgram ( shader ) {
  21899. var program = _gl.createProgram();
  21900. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21901. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21902. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21903. _gl.shaderSource( vertexShader, shader.vertexShader );
  21904. _gl.compileShader( fragmentShader );
  21905. _gl.compileShader( vertexShader );
  21906. _gl.attachShader( program, fragmentShader );
  21907. _gl.attachShader( program, vertexShader );
  21908. _gl.linkProgram( program );
  21909. return program;
  21910. };
  21911. function painterSortStable ( a, b ) {
  21912. if ( a.z !== b.z ) {
  21913. return b.z - a.z;
  21914. } else {
  21915. return b.id - a.id;
  21916. }
  21917. };
  21918. };/**
  21919. * @author alteredq / http://alteredqualia.com/
  21920. */
  21921. THREE.DepthPassPlugin = function ( ) {
  21922. this.enabled = false;
  21923. this.renderTarget = null;
  21924. var _gl,
  21925. _renderer,
  21926. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21927. _frustum = new THREE.Frustum(),
  21928. _projScreenMatrix = new THREE.Matrix4();
  21929. this.init = function ( renderer ) {
  21930. _gl = renderer.context;
  21931. _renderer = renderer;
  21932. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21933. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21934. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21935. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21936. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21937. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21938. _depthMaterial._shadowPass = true;
  21939. _depthMaterialMorph._shadowPass = true;
  21940. _depthMaterialSkin._shadowPass = true;
  21941. _depthMaterialMorphSkin._shadowPass = true;
  21942. };
  21943. this.render = function ( scene, camera ) {
  21944. if ( ! this.enabled ) return;
  21945. this.update( scene, camera );
  21946. };
  21947. this.update = function ( scene, camera ) {
  21948. var i, il, j, jl, n,
  21949. program, buffer, material,
  21950. webglObject, object, light,
  21951. renderList,
  21952. fog = null;
  21953. // set GL state for depth map
  21954. _gl.clearColor( 1, 1, 1, 1 );
  21955. _gl.disable( _gl.BLEND );
  21956. _renderer.setDepthTest( true );
  21957. // update scene
  21958. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21959. // update camera matrices and frustum
  21960. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21961. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21962. _frustum.setFromMatrix( _projScreenMatrix );
  21963. // render depth map
  21964. _renderer.setRenderTarget( this.renderTarget );
  21965. _renderer.clear();
  21966. // set object matrices & frustum culling
  21967. renderList = scene.__webglObjects;
  21968. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21969. webglObject = renderList[ j ];
  21970. object = webglObject.object;
  21971. webglObject.render = false;
  21972. if ( object.visible ) {
  21973. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21974. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21975. webglObject.render = true;
  21976. }
  21977. }
  21978. }
  21979. // render regular objects
  21980. var objectMaterial, useMorphing, useSkinning;
  21981. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21982. webglObject = renderList[ j ];
  21983. if ( webglObject.render ) {
  21984. object = webglObject.object;
  21985. buffer = webglObject.buffer;
  21986. // todo: create proper depth material for particles
  21987. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21988. objectMaterial = getObjectMaterial( object );
  21989. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21990. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21991. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21992. if ( object.customDepthMaterial ) {
  21993. material = object.customDepthMaterial;
  21994. } else if ( useSkinning ) {
  21995. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21996. } else if ( useMorphing ) {
  21997. material = _depthMaterialMorph;
  21998. } else {
  21999. material = _depthMaterial;
  22000. }
  22001. if ( buffer instanceof THREE.BufferGeometry ) {
  22002. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22003. } else {
  22004. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22005. }
  22006. }
  22007. }
  22008. // set matrices and render immediate objects
  22009. renderList = scene.__webglObjectsImmediate;
  22010. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22011. webglObject = renderList[ j ];
  22012. object = webglObject.object;
  22013. if ( object.visible ) {
  22014. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  22015. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22016. }
  22017. }
  22018. // restore GL state
  22019. var clearColor = _renderer.getClearColor(),
  22020. clearAlpha = _renderer.getClearAlpha();
  22021. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22022. _gl.enable( _gl.BLEND );
  22023. };
  22024. // For the moment just ignore objects that have multiple materials with different animation methods
  22025. // Only the first material will be taken into account for deciding which depth material to use
  22026. function getObjectMaterial( object ) {
  22027. return object.material instanceof THREE.MeshFaceMaterial
  22028. ? object.material.materials[ 0 ]
  22029. : object.material;
  22030. };
  22031. };
  22032. /**
  22033. * @author mikael emtinger / http://gomo.se/
  22034. *
  22035. */
  22036. THREE.ShaderFlares = {
  22037. 'lensFlareVertexTexture': {
  22038. vertexShader: [
  22039. "uniform vec3 screenPosition;",
  22040. "uniform vec2 scale;",
  22041. "uniform float rotation;",
  22042. "uniform int renderType;",
  22043. "uniform sampler2D occlusionMap;",
  22044. "attribute vec2 position;",
  22045. "attribute vec2 uv;",
  22046. "varying vec2 vUV;",
  22047. "varying float vVisibility;",
  22048. "void main() {",
  22049. "vUV = uv;",
  22050. "vec2 pos = position;",
  22051. "if( renderType == 2 ) {",
  22052. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  22053. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  22054. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  22055. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  22056. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  22057. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  22058. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  22059. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  22060. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22061. "vVisibility = ( visibility.r / 9.0 ) *",
  22062. "( 1.0 - visibility.g / 9.0 ) *",
  22063. "( visibility.b / 9.0 ) *",
  22064. "( 1.0 - visibility.a / 9.0 );",
  22065. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22066. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22067. "}",
  22068. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22069. "}"
  22070. ].join( "\n" ),
  22071. fragmentShader: [
  22072. "precision mediump float;",
  22073. "uniform sampler2D map;",
  22074. "uniform float opacity;",
  22075. "uniform int renderType;",
  22076. "uniform vec3 color;",
  22077. "varying vec2 vUV;",
  22078. "varying float vVisibility;",
  22079. "void main() {",
  22080. // pink square
  22081. "if( renderType == 0 ) {",
  22082. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22083. // restore
  22084. "} else if( renderType == 1 ) {",
  22085. "gl_FragColor = texture2D( map, vUV );",
  22086. // flare
  22087. "} else {",
  22088. "vec4 texture = texture2D( map, vUV );",
  22089. "texture.a *= opacity * vVisibility;",
  22090. "gl_FragColor = texture;",
  22091. "gl_FragColor.rgb *= color;",
  22092. "}",
  22093. "}"
  22094. ].join( "\n" )
  22095. },
  22096. 'lensFlare': {
  22097. vertexShader: [
  22098. "uniform vec3 screenPosition;",
  22099. "uniform vec2 scale;",
  22100. "uniform float rotation;",
  22101. "uniform int renderType;",
  22102. "attribute vec2 position;",
  22103. "attribute vec2 uv;",
  22104. "varying vec2 vUV;",
  22105. "void main() {",
  22106. "vUV = uv;",
  22107. "vec2 pos = position;",
  22108. "if( renderType == 2 ) {",
  22109. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22110. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22111. "}",
  22112. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22113. "}"
  22114. ].join( "\n" ),
  22115. fragmentShader: [
  22116. "precision mediump float;",
  22117. "uniform sampler2D map;",
  22118. "uniform sampler2D occlusionMap;",
  22119. "uniform float opacity;",
  22120. "uniform int renderType;",
  22121. "uniform vec3 color;",
  22122. "varying vec2 vUV;",
  22123. "void main() {",
  22124. // pink square
  22125. "if( renderType == 0 ) {",
  22126. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22127. // restore
  22128. "} else if( renderType == 1 ) {",
  22129. "gl_FragColor = texture2D( map, vUV );",
  22130. // flare
  22131. "} else {",
  22132. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  22133. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  22134. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  22135. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22136. "visibility = ( 1.0 - visibility / 4.0 );",
  22137. "vec4 texture = texture2D( map, vUV );",
  22138. "texture.a *= opacity * visibility;",
  22139. "gl_FragColor = texture;",
  22140. "gl_FragColor.rgb *= color;",
  22141. "}",
  22142. "}"
  22143. ].join( "\n" )
  22144. }
  22145. };
  22146. /**
  22147. * @author mikael emtinger / http://gomo.se/
  22148. * @author alteredq / http://alteredqualia.com/
  22149. *
  22150. */
  22151. THREE.ShaderSprite = {
  22152. 'sprite': {
  22153. vertexShader: [
  22154. "uniform int useScreenCoordinates;",
  22155. "uniform int sizeAttenuation;",
  22156. "uniform vec3 screenPosition;",
  22157. "uniform mat4 modelViewMatrix;",
  22158. "uniform mat4 projectionMatrix;",
  22159. "uniform float rotation;",
  22160. "uniform vec2 scale;",
  22161. "uniform vec2 alignment;",
  22162. "uniform vec2 uvOffset;",
  22163. "uniform vec2 uvScale;",
  22164. "attribute vec2 position;",
  22165. "attribute vec2 uv;",
  22166. "varying vec2 vUV;",
  22167. "void main() {",
  22168. "vUV = uvOffset + uv * uvScale;",
  22169. "vec2 alignedPosition = position + alignment;",
  22170. "vec2 rotatedPosition;",
  22171. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22172. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22173. "vec4 finalPosition;",
  22174. "if( useScreenCoordinates != 0 ) {",
  22175. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22176. "} else {",
  22177. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22178. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  22179. "}",
  22180. "gl_Position = finalPosition;",
  22181. "}"
  22182. ].join( "\n" ),
  22183. fragmentShader: [
  22184. "precision mediump float;",
  22185. "uniform vec3 color;",
  22186. "uniform sampler2D map;",
  22187. "uniform float opacity;",
  22188. "uniform int fogType;",
  22189. "uniform vec3 fogColor;",
  22190. "uniform float fogDensity;",
  22191. "uniform float fogNear;",
  22192. "uniform float fogFar;",
  22193. "uniform float alphaTest;",
  22194. "varying vec2 vUV;",
  22195. "void main() {",
  22196. "vec4 texture = texture2D( map, vUV );",
  22197. "if ( texture.a < alphaTest ) discard;",
  22198. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22199. "if ( fogType > 0 ) {",
  22200. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22201. "float fogFactor = 0.0;",
  22202. "if ( fogType == 1 ) {",
  22203. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22204. "} else {",
  22205. "const float LOG2 = 1.442695;",
  22206. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22207. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22208. "}",
  22209. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22210. "}",
  22211. "}"
  22212. ].join( "\n" )
  22213. }
  22214. };