three.js 820 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = THREE || { REVISION: '59dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. self.Int32Array = self.Int32Array || Array;
  15. self.Float32Array = self.Float32Array || Array;
  16. String.prototype.trim = String.prototype.trim || function () {
  17. return this.replace( /^\s+|\s+$/g, '' );
  18. };
  19. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  20. THREE.extend = function ( obj, source ) {
  21. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  22. if ( Object.keys ) {
  23. var keys = Object.keys( source );
  24. for (var i = 0, il = keys.length; i < il; i++) {
  25. var prop = keys[i];
  26. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  27. }
  28. } else {
  29. var safeHasOwnProperty = {}.hasOwnProperty;
  30. for ( var prop in source ) {
  31. if ( safeHasOwnProperty.call( source, prop ) ) {
  32. obj[prop] = source[prop];
  33. }
  34. }
  35. }
  36. return obj;
  37. };
  38. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  39. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  40. // requestAnimationFrame polyfill by Erik Möller
  41. // fixes from Paul Irish and Tino Zijdel
  42. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  43. ( function () {
  44. var lastTime = 0;
  45. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  46. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  47. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  48. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  49. }
  50. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  51. self.requestAnimationFrame = function ( callback ) {
  52. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  53. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  54. lastTime = currTime + timeToCall;
  55. return id;
  56. };
  57. }
  58. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  59. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  60. }
  61. }() );
  62. // GL STATE CONSTANTS
  63. THREE.CullFaceNone = 0;
  64. THREE.CullFaceBack = 1;
  65. THREE.CullFaceFront = 2;
  66. THREE.CullFaceFrontBack = 3;
  67. THREE.FrontFaceDirectionCW = 0;
  68. THREE.FrontFaceDirectionCCW = 1;
  69. // SHADOWING TYPES
  70. THREE.BasicShadowMap = 0;
  71. THREE.PCFShadowMap = 1;
  72. THREE.PCFSoftShadowMap = 2;
  73. // MATERIAL CONSTANTS
  74. // side
  75. THREE.FrontSide = 0;
  76. THREE.BackSide = 1;
  77. THREE.DoubleSide = 2;
  78. // shading
  79. THREE.NoShading = 0;
  80. THREE.FlatShading = 1;
  81. THREE.SmoothShading = 2;
  82. // colors
  83. THREE.NoColors = 0;
  84. THREE.FaceColors = 1;
  85. THREE.VertexColors = 2;
  86. // blending modes
  87. THREE.NoBlending = 0;
  88. THREE.NormalBlending = 1;
  89. THREE.AdditiveBlending = 2;
  90. THREE.SubtractiveBlending = 3;
  91. THREE.MultiplyBlending = 4;
  92. THREE.CustomBlending = 5;
  93. // custom blending equations
  94. // (numbers start from 100 not to clash with other
  95. // mappings to OpenGL constants defined in Texture.js)
  96. THREE.AddEquation = 100;
  97. THREE.SubtractEquation = 101;
  98. THREE.ReverseSubtractEquation = 102;
  99. // custom blending destination factors
  100. THREE.ZeroFactor = 200;
  101. THREE.OneFactor = 201;
  102. THREE.SrcColorFactor = 202;
  103. THREE.OneMinusSrcColorFactor = 203;
  104. THREE.SrcAlphaFactor = 204;
  105. THREE.OneMinusSrcAlphaFactor = 205;
  106. THREE.DstAlphaFactor = 206;
  107. THREE.OneMinusDstAlphaFactor = 207;
  108. // custom blending source factors
  109. //THREE.ZeroFactor = 200;
  110. //THREE.OneFactor = 201;
  111. //THREE.SrcAlphaFactor = 204;
  112. //THREE.OneMinusSrcAlphaFactor = 205;
  113. //THREE.DstAlphaFactor = 206;
  114. //THREE.OneMinusDstAlphaFactor = 207;
  115. THREE.DstColorFactor = 208;
  116. THREE.OneMinusDstColorFactor = 209;
  117. THREE.SrcAlphaSaturateFactor = 210;
  118. // TEXTURE CONSTANTS
  119. THREE.MultiplyOperation = 0;
  120. THREE.MixOperation = 1;
  121. THREE.AddOperation = 2;
  122. // Mapping modes
  123. THREE.UVMapping = function () {};
  124. THREE.CubeReflectionMapping = function () {};
  125. THREE.CubeRefractionMapping = function () {};
  126. THREE.SphericalReflectionMapping = function () {};
  127. THREE.SphericalRefractionMapping = function () {};
  128. // Wrapping modes
  129. THREE.RepeatWrapping = 1000;
  130. THREE.ClampToEdgeWrapping = 1001;
  131. THREE.MirroredRepeatWrapping = 1002;
  132. // Filters
  133. THREE.NearestFilter = 1003;
  134. THREE.NearestMipMapNearestFilter = 1004;
  135. THREE.NearestMipMapLinearFilter = 1005;
  136. THREE.LinearFilter = 1006;
  137. THREE.LinearMipMapNearestFilter = 1007;
  138. THREE.LinearMipMapLinearFilter = 1008;
  139. // Data types
  140. THREE.UnsignedByteType = 1009;
  141. THREE.ByteType = 1010;
  142. THREE.ShortType = 1011;
  143. THREE.UnsignedShortType = 1012;
  144. THREE.IntType = 1013;
  145. THREE.UnsignedIntType = 1014;
  146. THREE.FloatType = 1015;
  147. // Pixel types
  148. //THREE.UnsignedByteType = 1009;
  149. THREE.UnsignedShort4444Type = 1016;
  150. THREE.UnsignedShort5551Type = 1017;
  151. THREE.UnsignedShort565Type = 1018;
  152. // Pixel formats
  153. THREE.AlphaFormat = 1019;
  154. THREE.RGBFormat = 1020;
  155. THREE.RGBAFormat = 1021;
  156. THREE.LuminanceFormat = 1022;
  157. THREE.LuminanceAlphaFormat = 1023;
  158. // Compressed texture formats
  159. THREE.RGB_S3TC_DXT1_Format = 2001;
  160. THREE.RGBA_S3TC_DXT1_Format = 2002;
  161. THREE.RGBA_S3TC_DXT3_Format = 2003;
  162. THREE.RGBA_S3TC_DXT5_Format = 2004;
  163. /*
  164. // Potential future PVRTC compressed texture formats
  165. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  166. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  167. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  168. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  169. */
  170. /**
  171. * @author mrdoob / http://mrdoob.com/
  172. */
  173. THREE.Color = function ( value ) {
  174. if ( value !== undefined ) this.set( value );
  175. return this;
  176. };
  177. THREE.Color.prototype = {
  178. constructor: THREE.Color,
  179. r: 1, g: 1, b: 1,
  180. set: function ( value ) {
  181. if ( value instanceof THREE.Color ) {
  182. this.copy( value );
  183. } else if ( typeof value === 'number' ) {
  184. this.setHex( value );
  185. } else if ( typeof value === 'string' ) {
  186. this.setStyle( value );
  187. }
  188. return this;
  189. },
  190. setHex: function ( hex ) {
  191. hex = Math.floor( hex );
  192. this.r = ( hex >> 16 & 255 ) / 255;
  193. this.g = ( hex >> 8 & 255 ) / 255;
  194. this.b = ( hex & 255 ) / 255;
  195. return this;
  196. },
  197. setRGB: function ( r, g, b ) {
  198. this.r = r;
  199. this.g = g;
  200. this.b = b;
  201. return this;
  202. },
  203. setHSL: function ( h, s, l ) {
  204. // h,s,l ranges are in 0.0 - 1.0
  205. if ( s === 0 ) {
  206. this.r = this.g = this.b = l;
  207. } else {
  208. var hue2rgb = function ( p, q, t ) {
  209. if ( t < 0 ) t += 1;
  210. if ( t > 1 ) t -= 1;
  211. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  212. if ( t < 1 / 2 ) return q;
  213. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  214. return p;
  215. };
  216. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  217. var q = ( 2 * l ) - p;
  218. this.r = hue2rgb( q, p, h + 1 / 3 );
  219. this.g = hue2rgb( q, p, h );
  220. this.b = hue2rgb( q, p, h - 1 / 3 );
  221. }
  222. return this;
  223. },
  224. setStyle: function ( style ) {
  225. // rgb(255,0,0)
  226. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  227. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  228. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  229. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  230. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  231. return this;
  232. }
  233. // rgb(100%,0%,0%)
  234. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  235. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  236. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  237. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  238. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  239. return this;
  240. }
  241. // #ff0000
  242. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  243. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  244. this.setHex( parseInt( color[ 1 ], 16 ) );
  245. return this;
  246. }
  247. // #f00
  248. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  249. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  250. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  251. return this;
  252. }
  253. // red
  254. if ( /^(\w+)$/i.test( style ) ) {
  255. this.setHex( THREE.ColorKeywords[ style ] );
  256. return this;
  257. }
  258. },
  259. copy: function ( color ) {
  260. this.r = color.r;
  261. this.g = color.g;
  262. this.b = color.b;
  263. return this;
  264. },
  265. copyGammaToLinear: function ( color ) {
  266. this.r = color.r * color.r;
  267. this.g = color.g * color.g;
  268. this.b = color.b * color.b;
  269. return this;
  270. },
  271. copyLinearToGamma: function ( color ) {
  272. this.r = Math.sqrt( color.r );
  273. this.g = Math.sqrt( color.g );
  274. this.b = Math.sqrt( color.b );
  275. return this;
  276. },
  277. convertGammaToLinear: function () {
  278. var r = this.r, g = this.g, b = this.b;
  279. this.r = r * r;
  280. this.g = g * g;
  281. this.b = b * b;
  282. return this;
  283. },
  284. convertLinearToGamma: function () {
  285. this.r = Math.sqrt( this.r );
  286. this.g = Math.sqrt( this.g );
  287. this.b = Math.sqrt( this.b );
  288. return this;
  289. },
  290. getHex: function () {
  291. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  292. },
  293. getHexString: function () {
  294. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  295. },
  296. getHSL: function () {
  297. var hsl = { h: 0, s: 0, l: 0 };
  298. return function () {
  299. // h,s,l ranges are in 0.0 - 1.0
  300. var r = this.r, g = this.g, b = this.b;
  301. var max = Math.max( r, g, b );
  302. var min = Math.min( r, g, b );
  303. var hue, saturation;
  304. var lightness = ( min + max ) / 2.0;
  305. if ( min === max ) {
  306. hue = 0;
  307. saturation = 0;
  308. } else {
  309. var delta = max - min;
  310. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  311. switch ( max ) {
  312. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  313. case g: hue = ( b - r ) / delta + 2; break;
  314. case b: hue = ( r - g ) / delta + 4; break;
  315. }
  316. hue /= 6;
  317. }
  318. hsl.h = hue;
  319. hsl.s = saturation;
  320. hsl.l = lightness;
  321. return hsl;
  322. };
  323. }(),
  324. getStyle: function () {
  325. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  326. },
  327. offsetHSL: function ( h, s, l ) {
  328. var hsl = this.getHSL();
  329. hsl.h += h; hsl.s += s; hsl.l += l;
  330. this.setHSL( hsl.h, hsl.s, hsl.l );
  331. return this;
  332. },
  333. add: function ( color ) {
  334. this.r += color.r;
  335. this.g += color.g;
  336. this.b += color.b;
  337. return this;
  338. },
  339. addColors: function ( color1, color2 ) {
  340. this.r = color1.r + color2.r;
  341. this.g = color1.g + color2.g;
  342. this.b = color1.b + color2.b;
  343. return this;
  344. },
  345. addScalar: function ( s ) {
  346. this.r += s;
  347. this.g += s;
  348. this.b += s;
  349. return this;
  350. },
  351. multiply: function ( color ) {
  352. this.r *= color.r;
  353. this.g *= color.g;
  354. this.b *= color.b;
  355. return this;
  356. },
  357. multiplyScalar: function ( s ) {
  358. this.r *= s;
  359. this.g *= s;
  360. this.b *= s;
  361. return this;
  362. },
  363. lerp: function ( color, alpha ) {
  364. this.r += ( color.r - this.r ) * alpha;
  365. this.g += ( color.g - this.g ) * alpha;
  366. this.b += ( color.b - this.b ) * alpha;
  367. return this;
  368. },
  369. equals: function ( c ) {
  370. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  371. },
  372. clone: function () {
  373. return new THREE.Color().setRGB( this.r, this.g, this.b );
  374. }
  375. };
  376. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  377. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  378. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  379. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  380. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  381. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  382. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  383. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  384. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  385. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  386. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  387. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  388. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  389. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  390. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  391. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  392. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  393. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  394. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  395. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  396. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  397. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  398. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  399. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  400. /**
  401. * @author mikael emtinger / http://gomo.se/
  402. * @author alteredq / http://alteredqualia.com/
  403. * @author WestLangley / http://github.com/WestLangley
  404. * @author bhouston / http://exocortex.com
  405. */
  406. THREE.Quaternion = function ( x, y, z, w ) {
  407. this._x = x || 0;
  408. this._y = y || 0;
  409. this._z = z || 0;
  410. this._w = ( w !== undefined ) ? w : 1;
  411. };
  412. THREE.Quaternion.prototype = {
  413. constructor: THREE.Quaternion,
  414. _x: 0,_y: 0, _z: 0, _w: 0,
  415. _euler: undefined,
  416. _updateEuler: function ( callback ) {
  417. if ( this._euler !== undefined ) {
  418. this._euler.setFromQuaternion( this, undefined, false );
  419. }
  420. },
  421. get x () {
  422. return this._x;
  423. },
  424. set x ( value ) {
  425. this._x = value;
  426. this._updateEuler();
  427. },
  428. get y () {
  429. return this._y;
  430. },
  431. set y ( value ) {
  432. this._y = value;
  433. this._updateEuler();
  434. },
  435. get z () {
  436. return this._z;
  437. },
  438. set z ( value ) {
  439. this._z = value;
  440. this._updateEuler();
  441. },
  442. get w () {
  443. return this._w;
  444. },
  445. set w ( value ) {
  446. this._w = value;
  447. this._updateEuler();
  448. },
  449. set: function ( x, y, z, w ) {
  450. this._x = x;
  451. this._y = y;
  452. this._z = z;
  453. this._w = w;
  454. this._updateEuler();
  455. return this;
  456. },
  457. copy: function ( quaternion ) {
  458. this._x = quaternion._x;
  459. this._y = quaternion._y;
  460. this._z = quaternion._z;
  461. this._w = quaternion._w;
  462. this._updateEuler();
  463. return this;
  464. },
  465. setFromEuler: function ( euler, update ) {
  466. if ( typeof euler['order'] === undefined ) {
  467. console.error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  468. }
  469. // http://www.mathworks.com/matlabcentral/fileexchange/
  470. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  471. // content/SpinCalc.m
  472. var c1 = Math.cos( euler._x / 2 );
  473. var c2 = Math.cos( euler._y / 2 );
  474. var c3 = Math.cos( euler._z / 2 );
  475. var s1 = Math.sin( euler._x / 2 );
  476. var s2 = Math.sin( euler._y / 2 );
  477. var s3 = Math.sin( euler._z / 2 );
  478. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  479. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  480. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  481. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  482. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  483. } else if ( euler.order === 'YXZ' ) {
  484. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  485. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  486. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  487. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  488. } else if ( euler.order === 'ZXY' ) {
  489. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  490. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  491. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  492. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  493. } else if ( euler.order === 'ZYX' ) {
  494. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  495. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  496. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  497. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  498. } else if ( euler.order === 'YZX' ) {
  499. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  500. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  501. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  502. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  503. } else if ( euler.order === 'XZY' ) {
  504. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  505. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  506. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  507. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  508. }
  509. if ( update !== false ) this._updateEuler();
  510. return this;
  511. },
  512. setFromAxisAngle: function ( axis, angle ) {
  513. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  514. // axis have to be normalized
  515. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  516. this._x = axis.x * s;
  517. this._y = axis.y * s;
  518. this._z = axis.z * s;
  519. this._w = Math.cos( halfAngle );
  520. this._updateEuler();
  521. return this;
  522. },
  523. setFromRotationMatrix: function ( m ) {
  524. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  525. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  526. var te = m.elements,
  527. m11 = te[0], m12 = te[4], m13 = te[8],
  528. m21 = te[1], m22 = te[5], m23 = te[9],
  529. m31 = te[2], m32 = te[6], m33 = te[10],
  530. trace = m11 + m22 + m33,
  531. s;
  532. if ( trace > 0 ) {
  533. s = 0.5 / Math.sqrt( trace + 1.0 );
  534. this._w = 0.25 / s;
  535. this._x = ( m32 - m23 ) * s;
  536. this._y = ( m13 - m31 ) * s;
  537. this._z = ( m21 - m12 ) * s;
  538. } else if ( m11 > m22 && m11 > m33 ) {
  539. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  540. this._w = (m32 - m23 ) / s;
  541. this._x = 0.25 * s;
  542. this._y = (m12 + m21 ) / s;
  543. this._z = (m13 + m31 ) / s;
  544. } else if ( m22 > m33 ) {
  545. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  546. this._w = (m13 - m31 ) / s;
  547. this._x = (m12 + m21 ) / s;
  548. this._y = 0.25 * s;
  549. this._z = (m23 + m32 ) / s;
  550. } else {
  551. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  552. this._w = ( m21 - m12 ) / s;
  553. this._x = ( m13 + m31 ) / s;
  554. this._y = ( m23 + m32 ) / s;
  555. this._z = 0.25 * s;
  556. }
  557. this._updateEuler();
  558. return this;
  559. },
  560. inverse: function () {
  561. this.conjugate().normalize();
  562. return this;
  563. },
  564. conjugate: function () {
  565. this._x *= -1;
  566. this._y *= -1;
  567. this._z *= -1;
  568. this._updateEuler();
  569. return this;
  570. },
  571. lengthSq: function () {
  572. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  573. },
  574. length: function () {
  575. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  576. },
  577. normalize: function () {
  578. var l = this.length();
  579. if ( l === 0 ) {
  580. this._x = 0;
  581. this._y = 0;
  582. this._z = 0;
  583. this._w = 1;
  584. } else {
  585. l = 1 / l;
  586. this._x = this._x * l;
  587. this._y = this._y * l;
  588. this._z = this._z * l;
  589. this._w = this._w * l;
  590. }
  591. return this;
  592. },
  593. multiply: function ( q, p ) {
  594. if ( p !== undefined ) {
  595. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  596. return this.multiplyQuaternions( q, p );
  597. }
  598. return this.multiplyQuaternions( this, q );
  599. },
  600. multiplyQuaternions: function ( a, b ) {
  601. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  602. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  603. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  604. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  605. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  606. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  607. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  608. this._updateEuler();
  609. return this;
  610. },
  611. multiplyVector3: function ( vector ) {
  612. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  613. return vector.applyQuaternion( this );
  614. },
  615. slerp: function ( qb, t ) {
  616. var x = this._x, y = this._y, z = this._z, w = this._w;
  617. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  618. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  619. if ( cosHalfTheta < 0 ) {
  620. this._w = -qb._w;
  621. this._x = -qb._x;
  622. this._y = -qb._y;
  623. this._z = -qb._z;
  624. cosHalfTheta = -cosHalfTheta;
  625. } else {
  626. this.copy( qb );
  627. }
  628. if ( cosHalfTheta >= 1.0 ) {
  629. this._w = w;
  630. this._x = x;
  631. this._y = y;
  632. this._z = z;
  633. return this;
  634. }
  635. var halfTheta = Math.acos( cosHalfTheta );
  636. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  637. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  638. this._w = 0.5 * ( w + this._w );
  639. this._x = 0.5 * ( x + this._x );
  640. this._y = 0.5 * ( y + this._y );
  641. this._z = 0.5 * ( z + this._z );
  642. return this;
  643. }
  644. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  645. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  646. this._w = ( w * ratioA + this._w * ratioB );
  647. this._x = ( x * ratioA + this._x * ratioB );
  648. this._y = ( y * ratioA + this._y * ratioB );
  649. this._z = ( z * ratioA + this._z * ratioB );
  650. this._updateEuler();
  651. return this;
  652. },
  653. equals: function ( quaternion ) {
  654. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  655. },
  656. fromArray: function ( array ) {
  657. this._x = array[ 0 ];
  658. this._y = array[ 1 ];
  659. this._z = array[ 2 ];
  660. this._w = array[ 3 ];
  661. this._updateEuler();
  662. return this;
  663. },
  664. toArray: function () {
  665. return [ this._x, this._y, this._z, this._w ];
  666. },
  667. clone: function () {
  668. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  669. }
  670. };
  671. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  672. return qm.copy( qa ).slerp( qb, t );
  673. }
  674. /**
  675. * @author mrdoob / http://mrdoob.com/
  676. * @author philogb / http://blog.thejit.org/
  677. * @author egraether / http://egraether.com/
  678. * @author zz85 / http://www.lab4games.net/zz85/blog
  679. */
  680. THREE.Vector2 = function ( x, y ) {
  681. this.x = x || 0;
  682. this.y = y || 0;
  683. };
  684. THREE.Vector2.prototype = {
  685. constructor: THREE.Vector2,
  686. set: function ( x, y ) {
  687. this.x = x;
  688. this.y = y;
  689. return this;
  690. },
  691. setX: function ( x ) {
  692. this.x = x;
  693. return this;
  694. },
  695. setY: function ( y ) {
  696. this.y = y;
  697. return this;
  698. },
  699. setComponent: function ( index, value ) {
  700. switch ( index ) {
  701. case 0: this.x = value; break;
  702. case 1: this.y = value; break;
  703. default: throw new Error( "index is out of range: " + index );
  704. }
  705. },
  706. getComponent: function ( index ) {
  707. switch ( index ) {
  708. case 0: return this.x;
  709. case 1: return this.y;
  710. default: throw new Error( "index is out of range: " + index );
  711. }
  712. },
  713. copy: function ( v ) {
  714. this.x = v.x;
  715. this.y = v.y;
  716. return this;
  717. },
  718. add: function ( v, w ) {
  719. if ( w !== undefined ) {
  720. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  721. return this.addVectors( v, w );
  722. }
  723. this.x += v.x;
  724. this.y += v.y;
  725. return this;
  726. },
  727. addVectors: function ( a, b ) {
  728. this.x = a.x + b.x;
  729. this.y = a.y + b.y;
  730. return this;
  731. },
  732. addScalar: function ( s ) {
  733. this.x += s;
  734. this.y += s;
  735. return this;
  736. },
  737. sub: function ( v, w ) {
  738. if ( w !== undefined ) {
  739. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  740. return this.subVectors( v, w );
  741. }
  742. this.x -= v.x;
  743. this.y -= v.y;
  744. return this;
  745. },
  746. subVectors: function ( a, b ) {
  747. this.x = a.x - b.x;
  748. this.y = a.y - b.y;
  749. return this;
  750. },
  751. multiplyScalar: function ( s ) {
  752. this.x *= s;
  753. this.y *= s;
  754. return this;
  755. },
  756. divideScalar: function ( s ) {
  757. if ( s !== 0 ) {
  758. this.x /= s;
  759. this.y /= s;
  760. } else {
  761. this.set( 0, 0 );
  762. }
  763. return this;
  764. },
  765. min: function ( v ) {
  766. if ( this.x > v.x ) {
  767. this.x = v.x;
  768. }
  769. if ( this.y > v.y ) {
  770. this.y = v.y;
  771. }
  772. return this;
  773. },
  774. max: function ( v ) {
  775. if ( this.x < v.x ) {
  776. this.x = v.x;
  777. }
  778. if ( this.y < v.y ) {
  779. this.y = v.y;
  780. }
  781. return this;
  782. },
  783. clamp: function ( min, max ) {
  784. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  785. if ( this.x < min.x ) {
  786. this.x = min.x;
  787. } else if ( this.x > max.x ) {
  788. this.x = max.x;
  789. }
  790. if ( this.y < min.y ) {
  791. this.y = min.y;
  792. } else if ( this.y > max.y ) {
  793. this.y = max.y;
  794. }
  795. return this;
  796. },
  797. negate: function() {
  798. return this.multiplyScalar( - 1 );
  799. },
  800. dot: function ( v ) {
  801. return this.x * v.x + this.y * v.y;
  802. },
  803. lengthSq: function () {
  804. return this.x * this.x + this.y * this.y;
  805. },
  806. length: function () {
  807. return Math.sqrt( this.x * this.x + this.y * this.y );
  808. },
  809. normalize: function () {
  810. return this.divideScalar( this.length() );
  811. },
  812. distanceTo: function ( v ) {
  813. return Math.sqrt( this.distanceToSquared( v ) );
  814. },
  815. distanceToSquared: function ( v ) {
  816. var dx = this.x - v.x, dy = this.y - v.y;
  817. return dx * dx + dy * dy;
  818. },
  819. setLength: function ( l ) {
  820. var oldLength = this.length();
  821. if ( oldLength !== 0 && l !== oldLength ) {
  822. this.multiplyScalar( l / oldLength );
  823. }
  824. return this;
  825. },
  826. lerp: function ( v, alpha ) {
  827. this.x += ( v.x - this.x ) * alpha;
  828. this.y += ( v.y - this.y ) * alpha;
  829. return this;
  830. },
  831. equals: function( v ) {
  832. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  833. },
  834. fromArray: function ( array ) {
  835. this.x = array[ 0 ];
  836. this.y = array[ 1 ];
  837. return this;
  838. },
  839. toArray: function () {
  840. return [ this.x, this.y ];
  841. },
  842. clone: function () {
  843. return new THREE.Vector2( this.x, this.y );
  844. }
  845. };
  846. /**
  847. * @author mrdoob / http://mrdoob.com/
  848. * @author *kile / http://kile.stravaganza.org/
  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.Vector3 = function ( x, y, z ) {
  855. this.x = x || 0;
  856. this.y = y || 0;
  857. this.z = z || 0;
  858. };
  859. THREE.Vector3.prototype = {
  860. constructor: THREE.Vector3,
  861. set: function ( x, y, z ) {
  862. this.x = x;
  863. this.y = y;
  864. this.z = z;
  865. return this;
  866. },
  867. setX: function ( x ) {
  868. this.x = x;
  869. return this;
  870. },
  871. setY: function ( y ) {
  872. this.y = y;
  873. return this;
  874. },
  875. setZ: function ( z ) {
  876. this.z = z;
  877. return this;
  878. },
  879. setComponent: function ( index, value ) {
  880. switch ( index ) {
  881. case 0: this.x = value; break;
  882. case 1: this.y = value; break;
  883. case 2: this.z = value; break;
  884. default: throw new Error( "index is out of range: " + index );
  885. }
  886. },
  887. getComponent: function ( index ) {
  888. switch ( index ) {
  889. case 0: return this.x;
  890. case 1: return this.y;
  891. case 2: return this.z;
  892. default: throw new Error( "index is out of range: " + index );
  893. }
  894. },
  895. copy: function ( v ) {
  896. this.x = v.x;
  897. this.y = v.y;
  898. this.z = v.z;
  899. return this;
  900. },
  901. add: function ( v, w ) {
  902. if ( w !== undefined ) {
  903. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  904. return this.addVectors( v, w );
  905. }
  906. this.x += v.x;
  907. this.y += v.y;
  908. this.z += v.z;
  909. return this;
  910. },
  911. addScalar: function ( s ) {
  912. this.x += s;
  913. this.y += s;
  914. this.z += s;
  915. return this;
  916. },
  917. addVectors: function ( a, b ) {
  918. this.x = a.x + b.x;
  919. this.y = a.y + b.y;
  920. this.z = a.z + b.z;
  921. return this;
  922. },
  923. sub: function ( v, w ) {
  924. if ( w !== undefined ) {
  925. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  926. return this.subVectors( v, w );
  927. }
  928. this.x -= v.x;
  929. this.y -= v.y;
  930. this.z -= v.z;
  931. return this;
  932. },
  933. subVectors: function ( a, b ) {
  934. this.x = a.x - b.x;
  935. this.y = a.y - b.y;
  936. this.z = a.z - b.z;
  937. return this;
  938. },
  939. multiply: function ( v, w ) {
  940. if ( w !== undefined ) {
  941. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  942. return this.multiplyVectors( v, w );
  943. }
  944. this.x *= v.x;
  945. this.y *= v.y;
  946. this.z *= v.z;
  947. return this;
  948. },
  949. multiplyScalar: function ( s ) {
  950. this.x *= s;
  951. this.y *= s;
  952. this.z *= s;
  953. return this;
  954. },
  955. multiplyVectors: function ( a, b ) {
  956. this.x = a.x * b.x;
  957. this.y = a.y * b.y;
  958. this.z = a.z * b.z;
  959. return this;
  960. },
  961. applyMatrix3: function ( m ) {
  962. var x = this.x;
  963. var y = this.y;
  964. var z = this.z;
  965. var e = m.elements;
  966. this.x = e[0] * x + e[3] * y + e[6] * z;
  967. this.y = e[1] * x + e[4] * y + e[7] * z;
  968. this.z = e[2] * x + e[5] * y + e[8] * z;
  969. return this;
  970. },
  971. applyMatrix4: function ( m ) {
  972. // input: THREE.Matrix4 affine matrix
  973. var x = this.x, y = this.y, z = this.z;
  974. var e = m.elements;
  975. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  976. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  977. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  978. return this;
  979. },
  980. applyProjection: function ( m ) {
  981. // input: THREE.Matrix4 projection matrix
  982. var x = this.x, y = this.y, z = this.z;
  983. var e = m.elements;
  984. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  985. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  986. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  987. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  988. return this;
  989. },
  990. applyQuaternion: function ( q ) {
  991. var x = this.x;
  992. var y = this.y;
  993. var z = this.z;
  994. var qx = q.x;
  995. var qy = q.y;
  996. var qz = q.z;
  997. var qw = q.w;
  998. // calculate quat * vector
  999. var ix = qw * x + qy * z - qz * y;
  1000. var iy = qw * y + qz * x - qx * z;
  1001. var iz = qw * z + qx * y - qy * x;
  1002. var iw = -qx * x - qy * y - qz * z;
  1003. // calculate result * inverse quat
  1004. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1005. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1006. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1007. return this;
  1008. },
  1009. transformDirection: function ( m ) {
  1010. // input: THREE.Matrix4 affine matrix
  1011. // vector interpreted as a direction
  1012. var x = this.x, y = this.y, z = this.z;
  1013. var e = m.elements;
  1014. this.x = e[0] * x + e[4] * y + e[8] * z;
  1015. this.y = e[1] * x + e[5] * y + e[9] * z;
  1016. this.z = e[2] * x + e[6] * y + e[10] * z;
  1017. this.normalize();
  1018. return this;
  1019. },
  1020. divide: function ( v ) {
  1021. this.x /= v.x;
  1022. this.y /= v.y;
  1023. this.z /= v.z;
  1024. return this;
  1025. },
  1026. divideScalar: function ( s ) {
  1027. if ( s !== 0 ) {
  1028. this.x /= s;
  1029. this.y /= s;
  1030. this.z /= s;
  1031. } else {
  1032. this.x = 0;
  1033. this.y = 0;
  1034. this.z = 0;
  1035. }
  1036. return this;
  1037. },
  1038. min: function ( v ) {
  1039. if ( this.x > v.x ) {
  1040. this.x = v.x;
  1041. }
  1042. if ( this.y > v.y ) {
  1043. this.y = v.y;
  1044. }
  1045. if ( this.z > v.z ) {
  1046. this.z = v.z;
  1047. }
  1048. return this;
  1049. },
  1050. max: function ( v ) {
  1051. if ( this.x < v.x ) {
  1052. this.x = v.x;
  1053. }
  1054. if ( this.y < v.y ) {
  1055. this.y = v.y;
  1056. }
  1057. if ( this.z < v.z ) {
  1058. this.z = v.z;
  1059. }
  1060. return this;
  1061. },
  1062. clamp: function ( min, max ) {
  1063. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1064. if ( this.x < min.x ) {
  1065. this.x = min.x;
  1066. } else if ( this.x > max.x ) {
  1067. this.x = max.x;
  1068. }
  1069. if ( this.y < min.y ) {
  1070. this.y = min.y;
  1071. } else if ( this.y > max.y ) {
  1072. this.y = max.y;
  1073. }
  1074. if ( this.z < min.z ) {
  1075. this.z = min.z;
  1076. } else if ( this.z > max.z ) {
  1077. this.z = max.z;
  1078. }
  1079. return this;
  1080. },
  1081. negate: function () {
  1082. return this.multiplyScalar( - 1 );
  1083. },
  1084. dot: function ( v ) {
  1085. return this.x * v.x + this.y * v.y + this.z * v.z;
  1086. },
  1087. lengthSq: function () {
  1088. return this.x * this.x + this.y * this.y + this.z * this.z;
  1089. },
  1090. length: function () {
  1091. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1092. },
  1093. lengthManhattan: function () {
  1094. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1095. },
  1096. normalize: function () {
  1097. return this.divideScalar( this.length() );
  1098. },
  1099. setLength: function ( l ) {
  1100. var oldLength = this.length();
  1101. if ( oldLength !== 0 && l !== oldLength ) {
  1102. this.multiplyScalar( l / oldLength );
  1103. }
  1104. return this;
  1105. },
  1106. lerp: function ( v, alpha ) {
  1107. this.x += ( v.x - this.x ) * alpha;
  1108. this.y += ( v.y - this.y ) * alpha;
  1109. this.z += ( v.z - this.z ) * alpha;
  1110. return this;
  1111. },
  1112. cross: function ( v, w ) {
  1113. if ( w !== undefined ) {
  1114. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1115. return this.crossVectors( v, w );
  1116. }
  1117. var x = this.x, y = this.y, z = this.z;
  1118. this.x = y * v.z - z * v.y;
  1119. this.y = z * v.x - x * v.z;
  1120. this.z = x * v.y - y * v.x;
  1121. return this;
  1122. },
  1123. crossVectors: function ( a, b ) {
  1124. this.x = a.y * b.z - a.z * b.y;
  1125. this.y = a.z * b.x - a.x * b.z;
  1126. this.z = a.x * b.y - a.y * b.x;
  1127. return this;
  1128. },
  1129. angleTo: function ( v ) {
  1130. var theta = this.dot( v ) / ( this.length() * v.length() );
  1131. // clamp, to handle numerical problems
  1132. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1133. },
  1134. distanceTo: function ( v ) {
  1135. return Math.sqrt( this.distanceToSquared( v ) );
  1136. },
  1137. distanceToSquared: function ( v ) {
  1138. var dx = this.x - v.x;
  1139. var dy = this.y - v.y;
  1140. var dz = this.z - v.z;
  1141. return dx * dx + dy * dy + dz * dz;
  1142. },
  1143. setEulerFromRotationMatrix: function ( m, order ) {
  1144. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1145. },
  1146. setEulerFromQuaternion: function ( q, order ) {
  1147. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1148. },
  1149. getPositionFromMatrix: function ( m ) {
  1150. this.x = m.elements[12];
  1151. this.y = m.elements[13];
  1152. this.z = m.elements[14];
  1153. return this;
  1154. },
  1155. getScaleFromMatrix: function ( m ) {
  1156. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1157. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1158. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1159. this.x = sx;
  1160. this.y = sy;
  1161. this.z = sz;
  1162. return this;
  1163. },
  1164. getColumnFromMatrix: function ( index, matrix ) {
  1165. var offset = index * 4;
  1166. var me = matrix.elements;
  1167. this.x = me[ offset ];
  1168. this.y = me[ offset + 1 ];
  1169. this.z = me[ offset + 2 ];
  1170. return this;
  1171. },
  1172. equals: function ( v ) {
  1173. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1174. },
  1175. fromArray: function ( array ) {
  1176. this.x = array[ 0 ];
  1177. this.y = array[ 1 ];
  1178. this.z = array[ 2 ];
  1179. return this;
  1180. },
  1181. toArray: function () {
  1182. return [ this.x, this.y, this.z ];
  1183. },
  1184. clone: function () {
  1185. return new THREE.Vector3( this.x, this.y, this.z );
  1186. }
  1187. };
  1188. THREE.extend( THREE.Vector3.prototype, {
  1189. applyEuler: function () {
  1190. var q1 = new THREE.Quaternion();
  1191. return function ( rotation ) {
  1192. if( typeof rotation['order'] === undefined ) {
  1193. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1194. }
  1195. var quaternion = q1.setFromEuler( rotation );
  1196. this.applyQuaternion( quaternion );
  1197. return this;
  1198. };
  1199. }(),
  1200. applyAxisAngle: function () {
  1201. var q1 = new THREE.Quaternion();
  1202. return function ( axis, angle ) {
  1203. var quaternion = q1.setFromAxisAngle( axis, angle );
  1204. this.applyQuaternion( quaternion );
  1205. return this;
  1206. };
  1207. }(),
  1208. projectOnVector: function () {
  1209. var v1 = new THREE.Vector3();
  1210. return function ( vector ) {
  1211. v1.copy( vector ).normalize();
  1212. var d = this.dot( v1 );
  1213. return this.copy( v1 ).multiplyScalar( d );
  1214. };
  1215. }(),
  1216. projectOnPlane: function () {
  1217. var v1 = new THREE.Vector3();
  1218. return function ( planeNormal ) {
  1219. v1.copy( this ).projectOnVector( planeNormal );
  1220. return this.sub( v1 );
  1221. }
  1222. }(),
  1223. reflect: function () {
  1224. var v1 = new THREE.Vector3();
  1225. return function ( vector ) {
  1226. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1227. return this.subVectors( v1, this );
  1228. }
  1229. }()
  1230. } );
  1231. /**
  1232. * @author supereggbert / http://www.paulbrunt.co.uk/
  1233. * @author philogb / http://blog.thejit.org/
  1234. * @author mikael emtinger / http://gomo.se/
  1235. * @author egraether / http://egraether.com/
  1236. * @author WestLangley / http://github.com/WestLangley
  1237. */
  1238. THREE.Vector4 = function ( x, y, z, w ) {
  1239. this.x = x || 0;
  1240. this.y = y || 0;
  1241. this.z = z || 0;
  1242. this.w = ( w !== undefined ) ? w : 1;
  1243. };
  1244. THREE.Vector4.prototype = {
  1245. constructor: THREE.Vector4,
  1246. set: function ( x, y, z, w ) {
  1247. this.x = x;
  1248. this.y = y;
  1249. this.z = z;
  1250. this.w = w;
  1251. return this;
  1252. },
  1253. setX: function ( x ) {
  1254. this.x = x;
  1255. return this;
  1256. },
  1257. setY: function ( y ) {
  1258. this.y = y;
  1259. return this;
  1260. },
  1261. setZ: function ( z ) {
  1262. this.z = z;
  1263. return this;
  1264. },
  1265. setW: function ( w ) {
  1266. this.w = w;
  1267. return this;
  1268. },
  1269. setComponent: function ( index, value ) {
  1270. switch ( index ) {
  1271. case 0: this.x = value; break;
  1272. case 1: this.y = value; break;
  1273. case 2: this.z = value; break;
  1274. case 3: this.w = value; break;
  1275. default: throw new Error( "index is out of range: " + index );
  1276. }
  1277. },
  1278. getComponent: function ( index ) {
  1279. switch ( index ) {
  1280. case 0: return this.x;
  1281. case 1: return this.y;
  1282. case 2: return this.z;
  1283. case 3: return this.w;
  1284. default: throw new Error( "index is out of range: " + index );
  1285. }
  1286. },
  1287. copy: function ( v ) {
  1288. this.x = v.x;
  1289. this.y = v.y;
  1290. this.z = v.z;
  1291. this.w = ( v.w !== undefined ) ? v.w : 1;
  1292. return this;
  1293. },
  1294. add: function ( v, w ) {
  1295. if ( w !== undefined ) {
  1296. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1297. return this.addVectors( v, w );
  1298. }
  1299. this.x += v.x;
  1300. this.y += v.y;
  1301. this.z += v.z;
  1302. this.w += v.w;
  1303. return this;
  1304. },
  1305. addScalar: function ( s ) {
  1306. this.x += s;
  1307. this.y += s;
  1308. this.z += s;
  1309. this.w += s;
  1310. return this;
  1311. },
  1312. addVectors: function ( a, b ) {
  1313. this.x = a.x + b.x;
  1314. this.y = a.y + b.y;
  1315. this.z = a.z + b.z;
  1316. this.w = a.w + b.w;
  1317. return this;
  1318. },
  1319. sub: function ( v, w ) {
  1320. if ( w !== undefined ) {
  1321. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1322. return this.subVectors( v, w );
  1323. }
  1324. this.x -= v.x;
  1325. this.y -= v.y;
  1326. this.z -= v.z;
  1327. this.w -= v.w;
  1328. return this;
  1329. },
  1330. subVectors: function ( a, b ) {
  1331. this.x = a.x - b.x;
  1332. this.y = a.y - b.y;
  1333. this.z = a.z - b.z;
  1334. this.w = a.w - b.w;
  1335. return this;
  1336. },
  1337. multiplyScalar: function ( s ) {
  1338. this.x *= s;
  1339. this.y *= s;
  1340. this.z *= s;
  1341. this.w *= s;
  1342. return this;
  1343. },
  1344. applyMatrix4: function ( m ) {
  1345. var x = this.x;
  1346. var y = this.y;
  1347. var z = this.z;
  1348. var w = this.w;
  1349. var e = m.elements;
  1350. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1351. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1352. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1353. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1354. return this;
  1355. },
  1356. divideScalar: function ( s ) {
  1357. if ( s !== 0 ) {
  1358. this.x /= s;
  1359. this.y /= s;
  1360. this.z /= s;
  1361. this.w /= s;
  1362. } else {
  1363. this.x = 0;
  1364. this.y = 0;
  1365. this.z = 0;
  1366. this.w = 1;
  1367. }
  1368. return this;
  1369. },
  1370. setAxisAngleFromQuaternion: function ( q ) {
  1371. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1372. // q is assumed to be normalized
  1373. this.w = 2 * Math.acos( q.w );
  1374. var s = Math.sqrt( 1 - q.w * q.w );
  1375. if ( s < 0.0001 ) {
  1376. this.x = 1;
  1377. this.y = 0;
  1378. this.z = 0;
  1379. } else {
  1380. this.x = q.x / s;
  1381. this.y = q.y / s;
  1382. this.z = q.z / s;
  1383. }
  1384. return this;
  1385. },
  1386. setAxisAngleFromRotationMatrix: function ( m ) {
  1387. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1388. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1389. var angle, x, y, z, // variables for result
  1390. epsilon = 0.01, // margin to allow for rounding errors
  1391. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1392. te = m.elements,
  1393. m11 = te[0], m12 = te[4], m13 = te[8],
  1394. m21 = te[1], m22 = te[5], m23 = te[9],
  1395. m31 = te[2], m32 = te[6], m33 = te[10];
  1396. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1397. && ( Math.abs( m13 - m31 ) < epsilon )
  1398. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1399. // singularity found
  1400. // first check for identity matrix which must have +1 for all terms
  1401. // in leading diagonal and zero in other terms
  1402. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1403. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1404. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1405. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1406. // this singularity is identity matrix so angle = 0
  1407. this.set( 1, 0, 0, 0 );
  1408. return this; // zero angle, arbitrary axis
  1409. }
  1410. // otherwise this singularity is angle = 180
  1411. angle = Math.PI;
  1412. var xx = ( m11 + 1 ) / 2;
  1413. var yy = ( m22 + 1 ) / 2;
  1414. var zz = ( m33 + 1 ) / 2;
  1415. var xy = ( m12 + m21 ) / 4;
  1416. var xz = ( m13 + m31 ) / 4;
  1417. var yz = ( m23 + m32 ) / 4;
  1418. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1419. if ( xx < epsilon ) {
  1420. x = 0;
  1421. y = 0.707106781;
  1422. z = 0.707106781;
  1423. } else {
  1424. x = Math.sqrt( xx );
  1425. y = xy / x;
  1426. z = xz / x;
  1427. }
  1428. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1429. if ( yy < epsilon ) {
  1430. x = 0.707106781;
  1431. y = 0;
  1432. z = 0.707106781;
  1433. } else {
  1434. y = Math.sqrt( yy );
  1435. x = xy / y;
  1436. z = yz / y;
  1437. }
  1438. } else { // m33 is the largest diagonal term so base result on this
  1439. if ( zz < epsilon ) {
  1440. x = 0.707106781;
  1441. y = 0.707106781;
  1442. z = 0;
  1443. } else {
  1444. z = Math.sqrt( zz );
  1445. x = xz / z;
  1446. y = yz / z;
  1447. }
  1448. }
  1449. this.set( x, y, z, angle );
  1450. return this; // return 180 deg rotation
  1451. }
  1452. // as we have reached here there are no singularities so we can handle normally
  1453. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1454. + ( m13 - m31 ) * ( m13 - m31 )
  1455. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1456. if ( Math.abs( s ) < 0.001 ) s = 1;
  1457. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1458. // caught by singularity test above, but I've left it in just in case
  1459. this.x = ( m32 - m23 ) / s;
  1460. this.y = ( m13 - m31 ) / s;
  1461. this.z = ( m21 - m12 ) / s;
  1462. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1463. return this;
  1464. },
  1465. min: function ( v ) {
  1466. if ( this.x > v.x ) {
  1467. this.x = v.x;
  1468. }
  1469. if ( this.y > v.y ) {
  1470. this.y = v.y;
  1471. }
  1472. if ( this.z > v.z ) {
  1473. this.z = v.z;
  1474. }
  1475. if ( this.w > v.w ) {
  1476. this.w = v.w;
  1477. }
  1478. return this;
  1479. },
  1480. max: function ( v ) {
  1481. if ( this.x < v.x ) {
  1482. this.x = v.x;
  1483. }
  1484. if ( this.y < v.y ) {
  1485. this.y = v.y;
  1486. }
  1487. if ( this.z < v.z ) {
  1488. this.z = v.z;
  1489. }
  1490. if ( this.w < v.w ) {
  1491. this.w = v.w;
  1492. }
  1493. return this;
  1494. },
  1495. clamp: function ( min, max ) {
  1496. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1497. if ( this.x < min.x ) {
  1498. this.x = min.x;
  1499. } else if ( this.x > max.x ) {
  1500. this.x = max.x;
  1501. }
  1502. if ( this.y < min.y ) {
  1503. this.y = min.y;
  1504. } else if ( this.y > max.y ) {
  1505. this.y = max.y;
  1506. }
  1507. if ( this.z < min.z ) {
  1508. this.z = min.z;
  1509. } else if ( this.z > max.z ) {
  1510. this.z = max.z;
  1511. }
  1512. if ( this.w < min.w ) {
  1513. this.w = min.w;
  1514. } else if ( this.w > max.w ) {
  1515. this.w = max.w;
  1516. }
  1517. return this;
  1518. },
  1519. negate: function() {
  1520. return this.multiplyScalar( -1 );
  1521. },
  1522. dot: function ( v ) {
  1523. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1524. },
  1525. lengthSq: function () {
  1526. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1527. },
  1528. length: function () {
  1529. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1530. },
  1531. lengthManhattan: function () {
  1532. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1533. },
  1534. normalize: function () {
  1535. return this.divideScalar( this.length() );
  1536. },
  1537. setLength: function ( l ) {
  1538. var oldLength = this.length();
  1539. if ( oldLength !== 0 && l !== oldLength ) {
  1540. this.multiplyScalar( l / oldLength );
  1541. }
  1542. return this;
  1543. },
  1544. lerp: function ( v, alpha ) {
  1545. this.x += ( v.x - this.x ) * alpha;
  1546. this.y += ( v.y - this.y ) * alpha;
  1547. this.z += ( v.z - this.z ) * alpha;
  1548. this.w += ( v.w - this.w ) * alpha;
  1549. return this;
  1550. },
  1551. equals: function ( v ) {
  1552. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1553. },
  1554. fromArray: function ( array ) {
  1555. this.x = array[ 0 ];
  1556. this.y = array[ 1 ];
  1557. this.z = array[ 2 ];
  1558. this.w = array[ 3 ];
  1559. return this;
  1560. },
  1561. toArray: function () {
  1562. return [ this.x, this.y, this.z, this.w ];
  1563. },
  1564. clone: function () {
  1565. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1566. }
  1567. };
  1568. /**
  1569. * @author mrdoob / http://mrdoob.com/
  1570. * @author WestLangley / http://github.com/WestLangley
  1571. * @author bhouston / http://exocortex.com
  1572. */
  1573. THREE.Euler = function ( x, y, z, order ) {
  1574. this._x = x || 0;
  1575. this._y = y || 0;
  1576. this._z = z || 0;
  1577. this._order = order || THREE.Euler.DefaultOrder;
  1578. };
  1579. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1580. THREE.Euler.DefaultOrder = 'XYZ';
  1581. THREE.Euler.prototype = {
  1582. constructor: THREE.Euler,
  1583. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1584. _quaternion: undefined,
  1585. _updateQuaternion: function () {
  1586. if ( this._quaternion !== undefined ) {
  1587. this._quaternion.setFromEuler( this, false );
  1588. }
  1589. },
  1590. get x () {
  1591. return this._x;
  1592. },
  1593. set x ( value ) {
  1594. this._x = value;
  1595. this._updateQuaternion();
  1596. },
  1597. get y () {
  1598. return this._y;
  1599. },
  1600. set y ( value ) {
  1601. this._y = value;
  1602. this._updateQuaternion();
  1603. },
  1604. get z () {
  1605. return this._z;
  1606. },
  1607. set z ( value ) {
  1608. this._z = value;
  1609. this._updateQuaternion();
  1610. },
  1611. get order () {
  1612. return this._order;
  1613. },
  1614. set order ( value ) {
  1615. this._order = value;
  1616. this._updateQuaternion();
  1617. },
  1618. set: function ( x, y, z, order ) {
  1619. this._x = x;
  1620. this._y = y;
  1621. this._z = z;
  1622. this._order = order || this._order;
  1623. this._updateQuaternion();
  1624. return this;
  1625. },
  1626. copy: function ( euler ) {
  1627. this._x = euler._x;
  1628. this._y = euler._y;
  1629. this._z = euler._z;
  1630. this._order = euler._order;
  1631. this._updateQuaternion();
  1632. return this;
  1633. },
  1634. setFromRotationMatrix: function ( m, order ) {
  1635. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1636. // clamp, to handle numerical problems
  1637. function clamp( x ) {
  1638. return Math.min( Math.max( x, -1 ), 1 );
  1639. }
  1640. var te = m.elements;
  1641. var m11 = te[0], m12 = te[4], m13 = te[8];
  1642. var m21 = te[1], m22 = te[5], m23 = te[9];
  1643. var m31 = te[2], m32 = te[6], m33 = te[10];
  1644. order = order || this._order;
  1645. if ( order === 'XYZ' ) {
  1646. this._y = Math.asin( clamp( m13 ) );
  1647. if ( Math.abs( m13 ) < 0.99999 ) {
  1648. this._x = Math.atan2( - m23, m33 );
  1649. this._z = Math.atan2( - m12, m11 );
  1650. } else {
  1651. this._x = Math.atan2( m32, m22 );
  1652. this._z = 0;
  1653. }
  1654. } else if ( order === 'YXZ' ) {
  1655. this._x = Math.asin( - clamp( m23 ) );
  1656. if ( Math.abs( m23 ) < 0.99999 ) {
  1657. this._y = Math.atan2( m13, m33 );
  1658. this._z = Math.atan2( m21, m22 );
  1659. } else {
  1660. this._y = Math.atan2( - m31, m11 );
  1661. this._z = 0;
  1662. }
  1663. } else if ( order === 'ZXY' ) {
  1664. this._x = Math.asin( clamp( m32 ) );
  1665. if ( Math.abs( m32 ) < 0.99999 ) {
  1666. this._y = Math.atan2( - m31, m33 );
  1667. this._z = Math.atan2( - m12, m22 );
  1668. } else {
  1669. this._y = 0;
  1670. this._z = Math.atan2( m21, m11 );
  1671. }
  1672. } else if ( order === 'ZYX' ) {
  1673. this._y = Math.asin( - clamp( m31 ) );
  1674. if ( Math.abs( m31 ) < 0.99999 ) {
  1675. this._x = Math.atan2( m32, m33 );
  1676. this._z = Math.atan2( m21, m11 );
  1677. } else {
  1678. this._x = 0;
  1679. this._z = Math.atan2( - m12, m22 );
  1680. }
  1681. } else if ( order === 'YZX' ) {
  1682. this._z = Math.asin( clamp( m21 ) );
  1683. if ( Math.abs( m21 ) < 0.99999 ) {
  1684. this._x = Math.atan2( - m23, m22 );
  1685. this._y = Math.atan2( - m31, m11 );
  1686. } else {
  1687. this._x = 0;
  1688. this._y = Math.atan2( m13, m33 );
  1689. }
  1690. } else if ( order === 'XZY' ) {
  1691. this._z = Math.asin( - clamp( m12 ) );
  1692. if ( Math.abs( m12 ) < 0.99999 ) {
  1693. this._x = Math.atan2( m32, m22 );
  1694. this._y = Math.atan2( m13, m11 );
  1695. } else {
  1696. this._x = Math.atan2( - m23, m33 );
  1697. this._y = 0;
  1698. }
  1699. } else {
  1700. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1701. }
  1702. this._order = order;
  1703. this._updateQuaternion();
  1704. return this;
  1705. },
  1706. setFromQuaternion: function ( q, order, update ) {
  1707. // q is assumed to be normalized
  1708. // clamp, to handle numerical problems
  1709. function clamp( x ) {
  1710. return Math.min( Math.max( x, -1 ), 1 );
  1711. }
  1712. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1713. var sqx = q.x * q.x;
  1714. var sqy = q.y * q.y;
  1715. var sqz = q.z * q.z;
  1716. var sqw = q.w * q.w;
  1717. order = order || this._order;
  1718. if ( order === 'XYZ' ) {
  1719. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1720. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1721. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1722. } else if ( order === 'YXZ' ) {
  1723. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1724. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1725. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1726. } else if ( order === 'ZXY' ) {
  1727. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1728. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1729. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1730. } else if ( order === 'ZYX' ) {
  1731. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1732. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1733. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1734. } else if ( order === 'YZX' ) {
  1735. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1736. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1737. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1738. } else if ( order === 'XZY' ) {
  1739. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1740. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1741. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1742. } else {
  1743. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1744. }
  1745. this._order = order;
  1746. if ( update !== false ) this._updateQuaternion();
  1747. return this;
  1748. },
  1749. reorder: function () {
  1750. // WARNING: this discards revolution information -bhouston
  1751. var q = new THREE.Quaternion();
  1752. return function ( newOrder ) {
  1753. q.setFromEuler( this );
  1754. this.setFromQuaternion( q, newOrder );
  1755. };
  1756. }(),
  1757. fromArray: function ( array ) {
  1758. this._x = array[ 0 ];
  1759. this._y = array[ 1 ];
  1760. this._z = array[ 2 ];
  1761. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1762. this._updateQuaternion();
  1763. return this;
  1764. },
  1765. toArray: function () {
  1766. return [ this._x, this._y, this._z, this._order ];
  1767. },
  1768. equals: function ( euler ) {
  1769. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1770. },
  1771. clone: function () {
  1772. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1773. }
  1774. };
  1775. /**
  1776. * @author bhouston / http://exocortex.com
  1777. */
  1778. THREE.Line3 = function ( start, end ) {
  1779. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1780. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1781. };
  1782. THREE.Line3.prototype = {
  1783. constructor: THREE.Line3,
  1784. set: function ( start, end ) {
  1785. this.start.copy( start );
  1786. this.end.copy( end );
  1787. return this;
  1788. },
  1789. copy: function ( line ) {
  1790. this.start.copy( line.start );
  1791. this.end.copy( line.end );
  1792. return this;
  1793. },
  1794. center: function ( optionalTarget ) {
  1795. var result = optionalTarget || new THREE.Vector3();
  1796. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1797. },
  1798. delta: function ( optionalTarget ) {
  1799. var result = optionalTarget || new THREE.Vector3();
  1800. return result.subVectors( this.end, this.start );
  1801. },
  1802. distanceSq: function () {
  1803. return this.start.distanceToSquared( this.end );
  1804. },
  1805. distance: function () {
  1806. return this.start.distanceTo( this.end );
  1807. },
  1808. at: function ( t, optionalTarget ) {
  1809. var result = optionalTarget || new THREE.Vector3();
  1810. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1811. },
  1812. closestPointToPointParameter: function() {
  1813. var startP = new THREE.Vector3();
  1814. var startEnd = new THREE.Vector3();
  1815. return function ( point, clampToLine ) {
  1816. startP.subVectors( point, this.start );
  1817. startEnd.subVectors( this.end, this.start );
  1818. var startEnd2 = startEnd.dot( startEnd );
  1819. var startEnd_startP = startEnd.dot( startP );
  1820. var t = startEnd_startP / startEnd2;
  1821. if ( clampToLine ) {
  1822. t = THREE.Math.clamp( t, 0, 1 );
  1823. }
  1824. return t;
  1825. };
  1826. }(),
  1827. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1828. var t = this.closestPointToPointParameter( point, clampToLine );
  1829. var result = optionalTarget || new THREE.Vector3();
  1830. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1831. },
  1832. applyMatrix4: function ( matrix ) {
  1833. this.start.applyMatrix4( matrix );
  1834. this.end.applyMatrix4( matrix );
  1835. return this;
  1836. },
  1837. equals: function ( line ) {
  1838. return line.start.equals( this.start ) && line.end.equals( this.end );
  1839. },
  1840. clone: function () {
  1841. return new THREE.Line3().copy( this );
  1842. }
  1843. };
  1844. /**
  1845. * @author bhouston / http://exocortex.com
  1846. */
  1847. THREE.Box2 = function ( min, max ) {
  1848. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1849. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1850. };
  1851. THREE.Box2.prototype = {
  1852. constructor: THREE.Box2,
  1853. set: function ( min, max ) {
  1854. this.min.copy( min );
  1855. this.max.copy( max );
  1856. return this;
  1857. },
  1858. setFromPoints: function ( points ) {
  1859. if ( points.length > 0 ) {
  1860. var point = points[ 0 ];
  1861. this.min.copy( point );
  1862. this.max.copy( point );
  1863. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1864. point = points[ i ];
  1865. if ( point.x < this.min.x ) {
  1866. this.min.x = point.x;
  1867. } else if ( point.x > this.max.x ) {
  1868. this.max.x = point.x;
  1869. }
  1870. if ( point.y < this.min.y ) {
  1871. this.min.y = point.y;
  1872. } else if ( point.y > this.max.y ) {
  1873. this.max.y = point.y;
  1874. }
  1875. }
  1876. } else {
  1877. this.makeEmpty();
  1878. }
  1879. return this;
  1880. },
  1881. setFromCenterAndSize: function () {
  1882. var v1 = new THREE.Vector2();
  1883. return function ( center, size ) {
  1884. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1885. this.min.copy( center ).sub( halfSize );
  1886. this.max.copy( center ).add( halfSize );
  1887. return this;
  1888. };
  1889. }(),
  1890. copy: function ( box ) {
  1891. this.min.copy( box.min );
  1892. this.max.copy( box.max );
  1893. return this;
  1894. },
  1895. makeEmpty: function () {
  1896. this.min.x = this.min.y = Infinity;
  1897. this.max.x = this.max.y = -Infinity;
  1898. return this;
  1899. },
  1900. empty: function () {
  1901. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1902. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1903. },
  1904. center: function ( optionalTarget ) {
  1905. var result = optionalTarget || new THREE.Vector2();
  1906. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1907. },
  1908. size: function ( optionalTarget ) {
  1909. var result = optionalTarget || new THREE.Vector2();
  1910. return result.subVectors( this.max, this.min );
  1911. },
  1912. expandByPoint: function ( point ) {
  1913. this.min.min( point );
  1914. this.max.max( point );
  1915. return this;
  1916. },
  1917. expandByVector: function ( vector ) {
  1918. this.min.sub( vector );
  1919. this.max.add( vector );
  1920. return this;
  1921. },
  1922. expandByScalar: function ( scalar ) {
  1923. this.min.addScalar( -scalar );
  1924. this.max.addScalar( scalar );
  1925. return this;
  1926. },
  1927. containsPoint: function ( point ) {
  1928. if ( point.x < this.min.x || point.x > this.max.x ||
  1929. point.y < this.min.y || point.y > this.max.y ) {
  1930. return false;
  1931. }
  1932. return true;
  1933. },
  1934. containsBox: function ( box ) {
  1935. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1936. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1937. return true;
  1938. }
  1939. return false;
  1940. },
  1941. getParameter: function ( point ) {
  1942. // This can potentially have a divide by zero if the box
  1943. // has a size dimension of 0.
  1944. return new THREE.Vector2(
  1945. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1946. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1947. );
  1948. },
  1949. isIntersectionBox: function ( box ) {
  1950. // using 6 splitting planes to rule out intersections.
  1951. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1952. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1953. return false;
  1954. }
  1955. return true;
  1956. },
  1957. clampPoint: function ( point, optionalTarget ) {
  1958. var result = optionalTarget || new THREE.Vector2();
  1959. return result.copy( point ).clamp( this.min, this.max );
  1960. },
  1961. distanceToPoint: function () {
  1962. var v1 = new THREE.Vector2();
  1963. return function ( point ) {
  1964. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1965. return clampedPoint.sub( point ).length();
  1966. };
  1967. }(),
  1968. intersect: function ( box ) {
  1969. this.min.max( box.min );
  1970. this.max.min( box.max );
  1971. return this;
  1972. },
  1973. union: function ( box ) {
  1974. this.min.min( box.min );
  1975. this.max.max( box.max );
  1976. return this;
  1977. },
  1978. translate: function ( offset ) {
  1979. this.min.add( offset );
  1980. this.max.add( offset );
  1981. return this;
  1982. },
  1983. equals: function ( box ) {
  1984. return box.min.equals( this.min ) && box.max.equals( this.max );
  1985. },
  1986. clone: function () {
  1987. return new THREE.Box2().copy( this );
  1988. }
  1989. };
  1990. /**
  1991. * @author bhouston / http://exocortex.com
  1992. * @author WestLangley / http://github.com/WestLangley
  1993. */
  1994. THREE.Box3 = function ( min, max ) {
  1995. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1996. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1997. };
  1998. THREE.Box3.prototype = {
  1999. constructor: THREE.Box3,
  2000. set: function ( min, max ) {
  2001. this.min.copy( min );
  2002. this.max.copy( max );
  2003. return this;
  2004. },
  2005. setFromPoints: function ( points ) {
  2006. if ( points.length > 0 ) {
  2007. var point = points[ 0 ];
  2008. this.min.copy( point );
  2009. this.max.copy( point );
  2010. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2011. point = points[ i ];
  2012. if ( point.x < this.min.x ) {
  2013. this.min.x = point.x;
  2014. } else if ( point.x > this.max.x ) {
  2015. this.max.x = point.x;
  2016. }
  2017. if ( point.y < this.min.y ) {
  2018. this.min.y = point.y;
  2019. } else if ( point.y > this.max.y ) {
  2020. this.max.y = point.y;
  2021. }
  2022. if ( point.z < this.min.z ) {
  2023. this.min.z = point.z;
  2024. } else if ( point.z > this.max.z ) {
  2025. this.max.z = point.z;
  2026. }
  2027. }
  2028. } else {
  2029. this.makeEmpty();
  2030. }
  2031. return this;
  2032. },
  2033. setFromCenterAndSize: function() {
  2034. var v1 = new THREE.Vector3();
  2035. return function ( center, size ) {
  2036. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2037. this.min.copy( center ).sub( halfSize );
  2038. this.max.copy( center ).add( halfSize );
  2039. return this;
  2040. };
  2041. }(),
  2042. setFromObject: function() {
  2043. // Computes the world-axis-aligned bounding box of an object (including its children),
  2044. // accounting for both the object's, and childrens', world transforms
  2045. var v1 = new THREE.Vector3();
  2046. return function( object ) {
  2047. var scope = this;
  2048. object.updateMatrixWorld( true );
  2049. this.makeEmpty();
  2050. object.traverse( function ( node ) {
  2051. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2052. var vertices = node.geometry.vertices;
  2053. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2054. v1.copy( vertices[ i ] );
  2055. v1.applyMatrix4( node.matrixWorld );
  2056. scope.expandByPoint( v1 );
  2057. }
  2058. }
  2059. } );
  2060. return this;
  2061. };
  2062. }(),
  2063. copy: function ( box ) {
  2064. this.min.copy( box.min );
  2065. this.max.copy( box.max );
  2066. return this;
  2067. },
  2068. makeEmpty: function () {
  2069. this.min.x = this.min.y = this.min.z = Infinity;
  2070. this.max.x = this.max.y = this.max.z = -Infinity;
  2071. return this;
  2072. },
  2073. empty: function () {
  2074. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2075. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2076. },
  2077. center: function ( optionalTarget ) {
  2078. var result = optionalTarget || new THREE.Vector3();
  2079. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2080. },
  2081. size: function ( optionalTarget ) {
  2082. var result = optionalTarget || new THREE.Vector3();
  2083. return result.subVectors( this.max, this.min );
  2084. },
  2085. expandByPoint: function ( point ) {
  2086. this.min.min( point );
  2087. this.max.max( point );
  2088. return this;
  2089. },
  2090. expandByVector: function ( vector ) {
  2091. this.min.sub( vector );
  2092. this.max.add( vector );
  2093. return this;
  2094. },
  2095. expandByScalar: function ( scalar ) {
  2096. this.min.addScalar( -scalar );
  2097. this.max.addScalar( scalar );
  2098. return this;
  2099. },
  2100. containsPoint: function ( point ) {
  2101. if ( point.x < this.min.x || point.x > this.max.x ||
  2102. point.y < this.min.y || point.y > this.max.y ||
  2103. point.z < this.min.z || point.z > this.max.z ) {
  2104. return false;
  2105. }
  2106. return true;
  2107. },
  2108. containsBox: function ( box ) {
  2109. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2110. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2111. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2112. return true;
  2113. }
  2114. return false;
  2115. },
  2116. getParameter: function ( point ) {
  2117. // This can potentially have a divide by zero if the box
  2118. // has a size dimension of 0.
  2119. return new THREE.Vector3(
  2120. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2121. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2122. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2123. );
  2124. },
  2125. isIntersectionBox: function ( box ) {
  2126. // using 6 splitting planes to rule out intersections.
  2127. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2128. box.max.y < this.min.y || box.min.y > this.max.y ||
  2129. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2130. return false;
  2131. }
  2132. return true;
  2133. },
  2134. clampPoint: function ( point, optionalTarget ) {
  2135. var result = optionalTarget || new THREE.Vector3();
  2136. return result.copy( point ).clamp( this.min, this.max );
  2137. },
  2138. distanceToPoint: function() {
  2139. var v1 = new THREE.Vector3();
  2140. return function ( point ) {
  2141. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2142. return clampedPoint.sub( point ).length();
  2143. };
  2144. }(),
  2145. getBoundingSphere: function() {
  2146. var v1 = new THREE.Vector3();
  2147. return function ( optionalTarget ) {
  2148. var result = optionalTarget || new THREE.Sphere();
  2149. result.center = this.center();
  2150. result.radius = this.size( v1 ).length() * 0.5;
  2151. return result;
  2152. };
  2153. }(),
  2154. intersect: function ( box ) {
  2155. this.min.max( box.min );
  2156. this.max.min( box.max );
  2157. return this;
  2158. },
  2159. union: function ( box ) {
  2160. this.min.min( box.min );
  2161. this.max.max( box.max );
  2162. return this;
  2163. },
  2164. applyMatrix4: function() {
  2165. var points = [
  2166. new THREE.Vector3(),
  2167. new THREE.Vector3(),
  2168. new THREE.Vector3(),
  2169. new THREE.Vector3(),
  2170. new THREE.Vector3(),
  2171. new THREE.Vector3(),
  2172. new THREE.Vector3(),
  2173. new THREE.Vector3()
  2174. ];
  2175. return function ( matrix ) {
  2176. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2177. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2178. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2179. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2180. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2181. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2182. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2183. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2184. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2185. this.makeEmpty();
  2186. this.setFromPoints( points );
  2187. return this;
  2188. };
  2189. }(),
  2190. translate: function ( offset ) {
  2191. this.min.add( offset );
  2192. this.max.add( offset );
  2193. return this;
  2194. },
  2195. equals: function ( box ) {
  2196. return box.min.equals( this.min ) && box.max.equals( this.max );
  2197. },
  2198. clone: function () {
  2199. return new THREE.Box3().copy( this );
  2200. }
  2201. };
  2202. /**
  2203. * @author alteredq / http://alteredqualia.com/
  2204. * @author WestLangley / http://github.com/WestLangley
  2205. * @author bhouston / http://exocortex.com
  2206. */
  2207. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2208. this.elements = new Float32Array(9);
  2209. this.set(
  2210. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2211. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2212. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2213. );
  2214. };
  2215. THREE.Matrix3.prototype = {
  2216. constructor: THREE.Matrix3,
  2217. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2218. var te = this.elements;
  2219. te[0] = n11; te[3] = n12; te[6] = n13;
  2220. te[1] = n21; te[4] = n22; te[7] = n23;
  2221. te[2] = n31; te[5] = n32; te[8] = n33;
  2222. return this;
  2223. },
  2224. identity: function () {
  2225. this.set(
  2226. 1, 0, 0,
  2227. 0, 1, 0,
  2228. 0, 0, 1
  2229. );
  2230. return this;
  2231. },
  2232. copy: function ( m ) {
  2233. var me = m.elements;
  2234. this.set(
  2235. me[0], me[3], me[6],
  2236. me[1], me[4], me[7],
  2237. me[2], me[5], me[8]
  2238. );
  2239. return this;
  2240. },
  2241. multiplyVector3: function ( vector ) {
  2242. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2243. return vector.applyMatrix3( this );
  2244. },
  2245. multiplyVector3Array: function() {
  2246. var v1 = new THREE.Vector3();
  2247. return function ( a ) {
  2248. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2249. v1.x = a[ i ];
  2250. v1.y = a[ i + 1 ];
  2251. v1.z = a[ i + 2 ];
  2252. v1.applyMatrix3(this);
  2253. a[ i ] = v1.x;
  2254. a[ i + 1 ] = v1.y;
  2255. a[ i + 2 ] = v1.z;
  2256. }
  2257. return a;
  2258. };
  2259. }(),
  2260. multiplyScalar: function ( s ) {
  2261. var te = this.elements;
  2262. te[0] *= s; te[3] *= s; te[6] *= s;
  2263. te[1] *= s; te[4] *= s; te[7] *= s;
  2264. te[2] *= s; te[5] *= s; te[8] *= s;
  2265. return this;
  2266. },
  2267. determinant: function () {
  2268. var te = this.elements;
  2269. var a = te[0], b = te[1], c = te[2],
  2270. d = te[3], e = te[4], f = te[5],
  2271. g = te[6], h = te[7], i = te[8];
  2272. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2273. },
  2274. getInverse: function ( matrix, throwOnInvertible ) {
  2275. // input: THREE.Matrix4
  2276. // ( based on http://code.google.com/p/webgl-mjs/ )
  2277. var me = matrix.elements;
  2278. var te = this.elements;
  2279. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2280. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2281. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2282. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2283. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2284. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2285. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2286. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2287. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2288. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2289. // no inverse
  2290. if ( det === 0 ) {
  2291. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2292. if ( throwOnInvertible || false ) {
  2293. throw new Error( msg );
  2294. } else {
  2295. console.warn( msg );
  2296. }
  2297. this.identity();
  2298. return this;
  2299. }
  2300. this.multiplyScalar( 1.0 / det );
  2301. return this;
  2302. },
  2303. transpose: function () {
  2304. var tmp, m = this.elements;
  2305. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2306. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2307. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2308. return this;
  2309. },
  2310. getNormalMatrix: function ( m ) {
  2311. // input: THREE.Matrix4
  2312. this.getInverse( m ).transpose();
  2313. return this;
  2314. },
  2315. transposeIntoArray: function ( r ) {
  2316. var m = this.elements;
  2317. r[ 0 ] = m[ 0 ];
  2318. r[ 1 ] = m[ 3 ];
  2319. r[ 2 ] = m[ 6 ];
  2320. r[ 3 ] = m[ 1 ];
  2321. r[ 4 ] = m[ 4 ];
  2322. r[ 5 ] = m[ 7 ];
  2323. r[ 6 ] = m[ 2 ];
  2324. r[ 7 ] = m[ 5 ];
  2325. r[ 8 ] = m[ 8 ];
  2326. return this;
  2327. },
  2328. clone: function () {
  2329. var te = this.elements;
  2330. return new THREE.Matrix3(
  2331. te[0], te[3], te[6],
  2332. te[1], te[4], te[7],
  2333. te[2], te[5], te[8]
  2334. );
  2335. }
  2336. };
  2337. /**
  2338. * @author mrdoob / http://mrdoob.com/
  2339. * @author supereggbert / http://www.paulbrunt.co.uk/
  2340. * @author philogb / http://blog.thejit.org/
  2341. * @author jordi_ros / http://plattsoft.com
  2342. * @author D1plo1d / http://github.com/D1plo1d
  2343. * @author alteredq / http://alteredqualia.com/
  2344. * @author mikael emtinger / http://gomo.se/
  2345. * @author timknip / http://www.floorplanner.com/
  2346. * @author bhouston / http://exocortex.com
  2347. * @author WestLangley / http://github.com/WestLangley
  2348. */
  2349. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2350. this.elements = new Float32Array( 16 );
  2351. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2352. // we should not support semi specification of Matrix4, it is just weird.
  2353. var te = this.elements;
  2354. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2355. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2356. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2357. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2358. };
  2359. THREE.Matrix4.prototype = {
  2360. constructor: THREE.Matrix4,
  2361. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2362. var te = this.elements;
  2363. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2364. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2365. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2366. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2367. return this;
  2368. },
  2369. identity: function () {
  2370. this.set(
  2371. 1, 0, 0, 0,
  2372. 0, 1, 0, 0,
  2373. 0, 0, 1, 0,
  2374. 0, 0, 0, 1
  2375. );
  2376. return this;
  2377. },
  2378. copy: function ( m ) {
  2379. this.elements.set( m.elements );
  2380. return this;
  2381. },
  2382. extractPosition: function ( m ) {
  2383. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2384. return this.copyPosition( m );
  2385. },
  2386. copyPosition: function ( m ) {
  2387. var te = this.elements;
  2388. var me = m.elements;
  2389. te[12] = me[12];
  2390. te[13] = me[13];
  2391. te[14] = me[14];
  2392. return this;
  2393. },
  2394. extractRotation: function () {
  2395. var v1 = new THREE.Vector3();
  2396. return function ( m ) {
  2397. var te = this.elements;
  2398. var me = m.elements;
  2399. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2400. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2401. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2402. te[0] = me[0] * scaleX;
  2403. te[1] = me[1] * scaleX;
  2404. te[2] = me[2] * scaleX;
  2405. te[4] = me[4] * scaleY;
  2406. te[5] = me[5] * scaleY;
  2407. te[6] = me[6] * scaleY;
  2408. te[8] = me[8] * scaleZ;
  2409. te[9] = me[9] * scaleZ;
  2410. te[10] = me[10] * scaleZ;
  2411. return this;
  2412. };
  2413. }(),
  2414. makeRotationFromEuler: function ( euler ) {
  2415. if ( typeof euler['order'] === undefined ) {
  2416. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2417. }
  2418. var te = this.elements;
  2419. var x = euler.x, y = euler.y, z = euler.z;
  2420. var a = Math.cos( x ), b = Math.sin( x );
  2421. var c = Math.cos( y ), d = Math.sin( y );
  2422. var e = Math.cos( z ), f = Math.sin( z );
  2423. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  2424. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2425. te[0] = c * e;
  2426. te[4] = - c * f;
  2427. te[8] = d;
  2428. te[1] = af + be * d;
  2429. te[5] = ae - bf * d;
  2430. te[9] = - b * c;
  2431. te[2] = bf - ae * d;
  2432. te[6] = be + af * d;
  2433. te[10] = a * c;
  2434. } else if ( euler.order === 'YXZ' ) {
  2435. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2436. te[0] = ce + df * b;
  2437. te[4] = de * b - cf;
  2438. te[8] = a * d;
  2439. te[1] = a * f;
  2440. te[5] = a * e;
  2441. te[9] = - b;
  2442. te[2] = cf * b - de;
  2443. te[6] = df + ce * b;
  2444. te[10] = a * c;
  2445. } else if ( euler.order === 'ZXY' ) {
  2446. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2447. te[0] = ce - df * b;
  2448. te[4] = - a * f;
  2449. te[8] = de + cf * b;
  2450. te[1] = cf + de * b;
  2451. te[5] = a * e;
  2452. te[9] = df - ce * b;
  2453. te[2] = - a * d;
  2454. te[6] = b;
  2455. te[10] = a * c;
  2456. } else if ( euler.order === 'ZYX' ) {
  2457. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2458. te[0] = c * e;
  2459. te[4] = be * d - af;
  2460. te[8] = ae * d + bf;
  2461. te[1] = c * f;
  2462. te[5] = bf * d + ae;
  2463. te[9] = af * d - be;
  2464. te[2] = - d;
  2465. te[6] = b * c;
  2466. te[10] = a * c;
  2467. } else if ( euler.order === 'YZX' ) {
  2468. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2469. te[0] = c * e;
  2470. te[4] = bd - ac * f;
  2471. te[8] = bc * f + ad;
  2472. te[1] = f;
  2473. te[5] = a * e;
  2474. te[9] = - b * e;
  2475. te[2] = - d * e;
  2476. te[6] = ad * f + bc;
  2477. te[10] = ac - bd * f;
  2478. } else if ( euler.order === 'XZY' ) {
  2479. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2480. te[0] = c * e;
  2481. te[4] = - f;
  2482. te[8] = d * e;
  2483. te[1] = ac * f + bd;
  2484. te[5] = a * e;
  2485. te[9] = ad * f - bc;
  2486. te[2] = bc * f - ad;
  2487. te[6] = b * e;
  2488. te[10] = bd * f + ac;
  2489. }
  2490. // last column
  2491. te[3] = 0;
  2492. te[7] = 0;
  2493. te[11] = 0;
  2494. // bottom row
  2495. te[12] = 0;
  2496. te[13] = 0;
  2497. te[14] = 0;
  2498. te[15] = 1;
  2499. return this;
  2500. },
  2501. setRotationFromQuaternion: function ( q ) {
  2502. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2503. return this.makeRotationFromQuaternion( q );
  2504. },
  2505. makeRotationFromQuaternion: function ( q ) {
  2506. var te = this.elements;
  2507. var x = q.x, y = q.y, z = q.z, w = q.w;
  2508. var x2 = x + x, y2 = y + y, z2 = z + z;
  2509. var xx = x * x2, xy = x * y2, xz = x * z2;
  2510. var yy = y * y2, yz = y * z2, zz = z * z2;
  2511. var wx = w * x2, wy = w * y2, wz = w * z2;
  2512. te[0] = 1 - ( yy + zz );
  2513. te[4] = xy - wz;
  2514. te[8] = xz + wy;
  2515. te[1] = xy + wz;
  2516. te[5] = 1 - ( xx + zz );
  2517. te[9] = yz - wx;
  2518. te[2] = xz - wy;
  2519. te[6] = yz + wx;
  2520. te[10] = 1 - ( xx + yy );
  2521. // last column
  2522. te[3] = 0;
  2523. te[7] = 0;
  2524. te[11] = 0;
  2525. // bottom row
  2526. te[12] = 0;
  2527. te[13] = 0;
  2528. te[14] = 0;
  2529. te[15] = 1;
  2530. return this;
  2531. },
  2532. lookAt: function() {
  2533. var x = new THREE.Vector3();
  2534. var y = new THREE.Vector3();
  2535. var z = new THREE.Vector3();
  2536. return function ( eye, target, up ) {
  2537. var te = this.elements;
  2538. z.subVectors( eye, target ).normalize();
  2539. if ( z.length() === 0 ) {
  2540. z.z = 1;
  2541. }
  2542. x.crossVectors( up, z ).normalize();
  2543. if ( x.length() === 0 ) {
  2544. z.x += 0.0001;
  2545. x.crossVectors( up, z ).normalize();
  2546. }
  2547. y.crossVectors( z, x );
  2548. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2549. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2550. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2551. return this;
  2552. };
  2553. }(),
  2554. multiply: function ( m, n ) {
  2555. if ( n !== undefined ) {
  2556. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2557. return this.multiplyMatrices( m, n );
  2558. }
  2559. return this.multiplyMatrices( this, m );
  2560. },
  2561. multiplyMatrices: function ( a, b ) {
  2562. var ae = a.elements;
  2563. var be = b.elements;
  2564. var te = this.elements;
  2565. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2566. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2567. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2568. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2569. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2570. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2571. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2572. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2573. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2574. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2575. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2576. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2577. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2578. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2579. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2580. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2581. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2582. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2583. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2584. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2585. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2586. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2587. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2588. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2589. return this;
  2590. },
  2591. multiplyToArray: function ( a, b, r ) {
  2592. var te = this.elements;
  2593. this.multiplyMatrices( a, b );
  2594. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2595. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2596. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2597. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2598. return this;
  2599. },
  2600. multiplyScalar: function ( s ) {
  2601. var te = this.elements;
  2602. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2603. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2604. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2605. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2606. return this;
  2607. },
  2608. multiplyVector3: function ( vector ) {
  2609. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2610. return vector.applyProjection( this );
  2611. },
  2612. multiplyVector4: function ( vector ) {
  2613. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2614. return vector.applyMatrix4( this );
  2615. },
  2616. multiplyVector3Array: function() {
  2617. var v1 = new THREE.Vector3();
  2618. return function ( a ) {
  2619. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2620. v1.x = a[ i ];
  2621. v1.y = a[ i + 1 ];
  2622. v1.z = a[ i + 2 ];
  2623. v1.applyProjection( this );
  2624. a[ i ] = v1.x;
  2625. a[ i + 1 ] = v1.y;
  2626. a[ i + 2 ] = v1.z;
  2627. }
  2628. return a;
  2629. };
  2630. }(),
  2631. rotateAxis: function ( v ) {
  2632. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2633. v.transformDirection( this );
  2634. },
  2635. crossVector: function ( vector ) {
  2636. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2637. return vector.applyMatrix4( this );
  2638. },
  2639. determinant: function () {
  2640. var te = this.elements;
  2641. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2642. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2643. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2644. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2645. //TODO: make this more efficient
  2646. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2647. return (
  2648. n41 * (
  2649. +n14 * n23 * n32
  2650. -n13 * n24 * n32
  2651. -n14 * n22 * n33
  2652. +n12 * n24 * n33
  2653. +n13 * n22 * n34
  2654. -n12 * n23 * n34
  2655. ) +
  2656. n42 * (
  2657. +n11 * n23 * n34
  2658. -n11 * n24 * n33
  2659. +n14 * n21 * n33
  2660. -n13 * n21 * n34
  2661. +n13 * n24 * n31
  2662. -n14 * n23 * n31
  2663. ) +
  2664. n43 * (
  2665. +n11 * n24 * n32
  2666. -n11 * n22 * n34
  2667. -n14 * n21 * n32
  2668. +n12 * n21 * n34
  2669. +n14 * n22 * n31
  2670. -n12 * n24 * n31
  2671. ) +
  2672. n44 * (
  2673. -n13 * n22 * n31
  2674. -n11 * n23 * n32
  2675. +n11 * n22 * n33
  2676. +n13 * n21 * n32
  2677. -n12 * n21 * n33
  2678. +n12 * n23 * n31
  2679. )
  2680. );
  2681. },
  2682. transpose: function () {
  2683. var te = this.elements;
  2684. var tmp;
  2685. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2686. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2687. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2688. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2689. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2690. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2691. return this;
  2692. },
  2693. flattenToArray: function ( flat ) {
  2694. var te = this.elements;
  2695. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2696. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2697. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2698. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2699. return flat;
  2700. },
  2701. flattenToArrayOffset: function( flat, offset ) {
  2702. var te = this.elements;
  2703. flat[ offset ] = te[0];
  2704. flat[ offset + 1 ] = te[1];
  2705. flat[ offset + 2 ] = te[2];
  2706. flat[ offset + 3 ] = te[3];
  2707. flat[ offset + 4 ] = te[4];
  2708. flat[ offset + 5 ] = te[5];
  2709. flat[ offset + 6 ] = te[6];
  2710. flat[ offset + 7 ] = te[7];
  2711. flat[ offset + 8 ] = te[8];
  2712. flat[ offset + 9 ] = te[9];
  2713. flat[ offset + 10 ] = te[10];
  2714. flat[ offset + 11 ] = te[11];
  2715. flat[ offset + 12 ] = te[12];
  2716. flat[ offset + 13 ] = te[13];
  2717. flat[ offset + 14 ] = te[14];
  2718. flat[ offset + 15 ] = te[15];
  2719. return flat;
  2720. },
  2721. getPosition: function() {
  2722. var v1 = new THREE.Vector3();
  2723. return function () {
  2724. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2725. var te = this.elements;
  2726. return v1.set( te[12], te[13], te[14] );
  2727. };
  2728. }(),
  2729. setPosition: function ( v ) {
  2730. var te = this.elements;
  2731. te[12] = v.x;
  2732. te[13] = v.y;
  2733. te[14] = v.z;
  2734. return this;
  2735. },
  2736. getInverse: function ( m, throwOnInvertible ) {
  2737. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2738. var te = this.elements;
  2739. var me = m.elements;
  2740. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2741. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2742. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2743. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2744. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2745. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2746. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2747. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2748. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2749. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2750. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2751. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2752. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2753. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2754. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2755. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2756. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2757. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2758. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2759. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2760. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2761. if ( det == 0 ) {
  2762. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2763. if ( throwOnInvertible || false ) {
  2764. throw new Error( msg );
  2765. } else {
  2766. console.warn( msg );
  2767. }
  2768. this.identity();
  2769. return this;
  2770. }
  2771. this.multiplyScalar( 1 / det );
  2772. return this;
  2773. },
  2774. translate: function ( v ) {
  2775. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2776. },
  2777. rotateX: function ( angle ) {
  2778. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2779. },
  2780. rotateY: function ( angle ) {
  2781. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2782. },
  2783. rotateZ: function ( angle ) {
  2784. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2785. },
  2786. rotateByAxis: function ( axis, angle ) {
  2787. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2788. },
  2789. scale: function ( v ) {
  2790. var te = this.elements;
  2791. var x = v.x, y = v.y, z = v.z;
  2792. te[0] *= x; te[4] *= y; te[8] *= z;
  2793. te[1] *= x; te[5] *= y; te[9] *= z;
  2794. te[2] *= x; te[6] *= y; te[10] *= z;
  2795. te[3] *= x; te[7] *= y; te[11] *= z;
  2796. return this;
  2797. },
  2798. getMaxScaleOnAxis: function () {
  2799. var te = this.elements;
  2800. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2801. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2802. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2803. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2804. },
  2805. makeTranslation: function ( x, y, z ) {
  2806. this.set(
  2807. 1, 0, 0, x,
  2808. 0, 1, 0, y,
  2809. 0, 0, 1, z,
  2810. 0, 0, 0, 1
  2811. );
  2812. return this;
  2813. },
  2814. makeRotationX: function ( theta ) {
  2815. var c = Math.cos( theta ), s = Math.sin( theta );
  2816. this.set(
  2817. 1, 0, 0, 0,
  2818. 0, c, -s, 0,
  2819. 0, s, c, 0,
  2820. 0, 0, 0, 1
  2821. );
  2822. return this;
  2823. },
  2824. makeRotationY: function ( theta ) {
  2825. var c = Math.cos( theta ), s = Math.sin( theta );
  2826. this.set(
  2827. c, 0, s, 0,
  2828. 0, 1, 0, 0,
  2829. -s, 0, c, 0,
  2830. 0, 0, 0, 1
  2831. );
  2832. return this;
  2833. },
  2834. makeRotationZ: function ( theta ) {
  2835. var c = Math.cos( theta ), s = Math.sin( theta );
  2836. this.set(
  2837. c, -s, 0, 0,
  2838. s, c, 0, 0,
  2839. 0, 0, 1, 0,
  2840. 0, 0, 0, 1
  2841. );
  2842. return this;
  2843. },
  2844. makeRotationAxis: function ( axis, angle ) {
  2845. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2846. var c = Math.cos( angle );
  2847. var s = Math.sin( angle );
  2848. var t = 1 - c;
  2849. var x = axis.x, y = axis.y, z = axis.z;
  2850. var tx = t * x, ty = t * y;
  2851. this.set(
  2852. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2853. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2854. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2855. 0, 0, 0, 1
  2856. );
  2857. return this;
  2858. },
  2859. makeScale: function ( x, y, z ) {
  2860. this.set(
  2861. x, 0, 0, 0,
  2862. 0, y, 0, 0,
  2863. 0, 0, z, 0,
  2864. 0, 0, 0, 1
  2865. );
  2866. return this;
  2867. },
  2868. compose: function ( position, quaternion, scale ) {
  2869. this.makeRotationFromQuaternion( quaternion );
  2870. this.scale( scale );
  2871. this.setPosition( position );
  2872. return this;
  2873. },
  2874. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2875. var te = this.elements;
  2876. var x = 2 * near / ( right - left );
  2877. var y = 2 * near / ( top - bottom );
  2878. var a = ( right + left ) / ( right - left );
  2879. var b = ( top + bottom ) / ( top - bottom );
  2880. var c = - ( far + near ) / ( far - near );
  2881. var d = - 2 * far * near / ( far - near );
  2882. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2883. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2884. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2885. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2886. return this;
  2887. },
  2888. makePerspective: function ( fov, aspect, near, far ) {
  2889. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2890. var ymin = - ymax;
  2891. var xmin = ymin * aspect;
  2892. var xmax = ymax * aspect;
  2893. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2894. },
  2895. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2896. var te = this.elements;
  2897. var w = right - left;
  2898. var h = top - bottom;
  2899. var p = far - near;
  2900. var x = ( right + left ) / w;
  2901. var y = ( top + bottom ) / h;
  2902. var z = ( far + near ) / p;
  2903. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2904. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2905. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2906. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2907. return this;
  2908. },
  2909. fromArray: function ( array ) {
  2910. this.elements.set( array );
  2911. return this;
  2912. },
  2913. toArray: function () {
  2914. var te = this.elements;
  2915. return [
  2916. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2917. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2918. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2919. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2920. ];
  2921. },
  2922. clone: function () {
  2923. var te = this.elements;
  2924. return new THREE.Matrix4(
  2925. te[0], te[4], te[8], te[12],
  2926. te[1], te[5], te[9], te[13],
  2927. te[2], te[6], te[10], te[14],
  2928. te[3], te[7], te[11], te[15]
  2929. );
  2930. }
  2931. };
  2932. THREE.extend( THREE.Matrix4.prototype, {
  2933. decompose: function () {
  2934. var x = new THREE.Vector3();
  2935. var y = new THREE.Vector3();
  2936. var z = new THREE.Vector3();
  2937. var matrix = new THREE.Matrix4();
  2938. return function ( position, quaternion, scale ) {
  2939. var te = this.elements;
  2940. // grab the axis vectors
  2941. x.set( te[0], te[1], te[2] );
  2942. y.set( te[4], te[5], te[6] );
  2943. z.set( te[8], te[9], te[10] );
  2944. position = ( position instanceof THREE.Vector3 ) ? position : new THREE.Vector3();
  2945. quaternion = ( quaternion instanceof THREE.Quaternion ) ? quaternion : new THREE.Quaternion();
  2946. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2947. scale.x = x.length();
  2948. scale.y = y.length();
  2949. scale.z = z.length();
  2950. position.x = te[12];
  2951. position.y = te[13];
  2952. position.z = te[14];
  2953. // scale the rotation part
  2954. matrix.copy( this );
  2955. matrix.elements[0] /= scale.x;
  2956. matrix.elements[1] /= scale.x;
  2957. matrix.elements[2] /= scale.x;
  2958. matrix.elements[4] /= scale.y;
  2959. matrix.elements[5] /= scale.y;
  2960. matrix.elements[6] /= scale.y;
  2961. matrix.elements[8] /= scale.z;
  2962. matrix.elements[9] /= scale.z;
  2963. matrix.elements[10] /= scale.z;
  2964. quaternion.setFromRotationMatrix( matrix );
  2965. return [ position, quaternion, scale ];
  2966. };
  2967. }()
  2968. } );
  2969. /**
  2970. * @author bhouston / http://exocortex.com
  2971. */
  2972. THREE.Ray = function ( origin, direction ) {
  2973. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2974. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2975. };
  2976. THREE.Ray.prototype = {
  2977. constructor: THREE.Ray,
  2978. set: function ( origin, direction ) {
  2979. this.origin.copy( origin );
  2980. this.direction.copy( direction );
  2981. return this;
  2982. },
  2983. copy: function ( ray ) {
  2984. this.origin.copy( ray.origin );
  2985. this.direction.copy( ray.direction );
  2986. return this;
  2987. },
  2988. at: function( t, optionalTarget ) {
  2989. var result = optionalTarget || new THREE.Vector3();
  2990. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2991. },
  2992. recast: function() {
  2993. var v1 = new THREE.Vector3();
  2994. return function ( t ) {
  2995. this.origin.copy( this.at( t, v1 ) );
  2996. return this;
  2997. };
  2998. }(),
  2999. closestPointToPoint: function ( point, optionalTarget ) {
  3000. var result = optionalTarget || new THREE.Vector3();
  3001. result.subVectors( point, this.origin );
  3002. var directionDistance = result.dot( this.direction );
  3003. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3004. },
  3005. distanceToPoint: function() {
  3006. var v1 = new THREE.Vector3();
  3007. return function ( point ) {
  3008. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3009. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3010. return v1.distanceTo( point );
  3011. };
  3012. }(),
  3013. isIntersectionSphere: function( sphere ) {
  3014. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  3015. },
  3016. isIntersectionPlane: function ( plane ) {
  3017. // check if the line and plane are non-perpendicular, if they
  3018. // eventually they will intersect.
  3019. var denominator = plane.normal.dot( this.direction );
  3020. if ( denominator != 0 ) {
  3021. return true;
  3022. }
  3023. // line is coplanar, return origin
  3024. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3025. return true;
  3026. }
  3027. return false;
  3028. },
  3029. distanceToPlane: function ( plane ) {
  3030. var denominator = plane.normal.dot( this.direction );
  3031. if ( denominator == 0 ) {
  3032. // line is coplanar, return origin
  3033. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3034. return 0;
  3035. }
  3036. // Unsure if this is the correct method to handle this case.
  3037. return undefined;
  3038. }
  3039. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3040. return t;
  3041. },
  3042. intersectPlane: function ( plane, optionalTarget ) {
  3043. var t = this.distanceToPlane( plane );
  3044. if ( t === undefined ) {
  3045. return undefined;
  3046. }
  3047. return this.at( t, optionalTarget );
  3048. },
  3049. applyMatrix4: function ( matrix4 ) {
  3050. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3051. this.origin.applyMatrix4( matrix4 );
  3052. this.direction.sub( this.origin );
  3053. return this;
  3054. },
  3055. equals: function ( ray ) {
  3056. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3057. },
  3058. clone: function () {
  3059. return new THREE.Ray().copy( this );
  3060. }
  3061. };
  3062. /**
  3063. * @author bhouston / http://exocortex.com
  3064. * @author mrdoob / http://mrdoob.com/
  3065. */
  3066. THREE.Sphere = function ( center, radius ) {
  3067. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3068. this.radius = ( radius !== undefined ) ? radius : 0;
  3069. };
  3070. THREE.Sphere.prototype = {
  3071. constructor: THREE.Sphere,
  3072. set: function ( center, radius ) {
  3073. this.center.copy( center );
  3074. this.radius = radius;
  3075. return this;
  3076. },
  3077. setFromPoints: function ( points ) {
  3078. var radiusSq, maxRadiusSq = 0;
  3079. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3080. radiusSq = points[ i ].lengthSq();
  3081. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  3082. }
  3083. this.center.set( 0, 0, 0 );
  3084. this.radius = Math.sqrt( maxRadiusSq );
  3085. return this;
  3086. },
  3087. copy: function ( sphere ) {
  3088. this.center.copy( sphere.center );
  3089. this.radius = sphere.radius;
  3090. return this;
  3091. },
  3092. empty: function () {
  3093. return ( this.radius <= 0 );
  3094. },
  3095. containsPoint: function ( point ) {
  3096. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3097. },
  3098. distanceToPoint: function ( point ) {
  3099. return ( point.distanceTo( this.center ) - this.radius );
  3100. },
  3101. intersectsSphere: function ( sphere ) {
  3102. var radiusSum = this.radius + sphere.radius;
  3103. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3104. },
  3105. clampPoint: function ( point, optionalTarget ) {
  3106. var deltaLengthSq = this.center.distanceToSquared( point );
  3107. var result = optionalTarget || new THREE.Vector3();
  3108. result.copy( point );
  3109. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3110. result.sub( this.center ).normalize();
  3111. result.multiplyScalar( this.radius ).add( this.center );
  3112. }
  3113. return result;
  3114. },
  3115. getBoundingBox: function ( optionalTarget ) {
  3116. var box = optionalTarget || new THREE.Box3();
  3117. box.set( this.center, this.center );
  3118. box.expandByScalar( this.radius );
  3119. return box;
  3120. },
  3121. applyMatrix4: function ( matrix ) {
  3122. this.center.applyMatrix4( matrix );
  3123. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3124. return this;
  3125. },
  3126. translate: function ( offset ) {
  3127. this.center.add( offset );
  3128. return this;
  3129. },
  3130. equals: function ( sphere ) {
  3131. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3132. },
  3133. clone: function () {
  3134. return new THREE.Sphere().copy( this );
  3135. }
  3136. };
  3137. /**
  3138. * @author mrdoob / http://mrdoob.com/
  3139. * @author alteredq / http://alteredqualia.com/
  3140. * @author bhouston / http://exocortex.com
  3141. */
  3142. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3143. this.planes = [
  3144. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3145. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3146. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3147. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3148. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3149. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3150. ];
  3151. };
  3152. THREE.Frustum.prototype = {
  3153. constructor: THREE.Frustum,
  3154. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3155. var planes = this.planes;
  3156. planes[0].copy( p0 );
  3157. planes[1].copy( p1 );
  3158. planes[2].copy( p2 );
  3159. planes[3].copy( p3 );
  3160. planes[4].copy( p4 );
  3161. planes[5].copy( p5 );
  3162. return this;
  3163. },
  3164. copy: function ( frustum ) {
  3165. var planes = this.planes;
  3166. for( var i = 0; i < 6; i ++ ) {
  3167. planes[i].copy( frustum.planes[i] );
  3168. }
  3169. return this;
  3170. },
  3171. setFromMatrix: function ( m ) {
  3172. var planes = this.planes;
  3173. var me = m.elements;
  3174. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3175. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3176. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3177. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3178. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3179. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3180. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3181. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3182. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3183. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3184. return this;
  3185. },
  3186. intersectsObject: function () {
  3187. var center = new THREE.Vector3();
  3188. return function ( object ) {
  3189. // this method is expanded inlined for performance reasons.
  3190. var matrix = object.matrixWorld;
  3191. var planes = this.planes;
  3192. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3193. center.getPositionFromMatrix( matrix );
  3194. for ( var i = 0; i < 6; i ++ ) {
  3195. var distance = planes[ i ].distanceToPoint( center );
  3196. if ( distance < negRadius ) {
  3197. return false;
  3198. }
  3199. }
  3200. return true;
  3201. };
  3202. }(),
  3203. intersectsSphere: function ( sphere ) {
  3204. var planes = this.planes;
  3205. var center = sphere.center;
  3206. var negRadius = -sphere.radius;
  3207. for ( var i = 0; i < 6; i ++ ) {
  3208. var distance = planes[ i ].distanceToPoint( center );
  3209. if ( distance < negRadius ) {
  3210. return false;
  3211. }
  3212. }
  3213. return true;
  3214. },
  3215. containsPoint: function ( point ) {
  3216. var planes = this.planes;
  3217. for ( var i = 0; i < 6; i ++ ) {
  3218. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3219. return false;
  3220. }
  3221. }
  3222. return true;
  3223. },
  3224. clone: function () {
  3225. return new THREE.Frustum().copy( this );
  3226. }
  3227. };
  3228. /**
  3229. * @author bhouston / http://exocortex.com
  3230. */
  3231. THREE.Plane = function ( normal, constant ) {
  3232. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3233. this.constant = ( constant !== undefined ) ? constant : 0;
  3234. };
  3235. THREE.Plane.prototype = {
  3236. constructor: THREE.Plane,
  3237. set: function ( normal, constant ) {
  3238. this.normal.copy( normal );
  3239. this.constant = constant;
  3240. return this;
  3241. },
  3242. setComponents: function ( x, y, z, w ) {
  3243. this.normal.set( x, y, z );
  3244. this.constant = w;
  3245. return this;
  3246. },
  3247. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3248. this.normal.copy( normal );
  3249. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3250. return this;
  3251. },
  3252. setFromCoplanarPoints: function() {
  3253. var v1 = new THREE.Vector3();
  3254. var v2 = new THREE.Vector3();
  3255. return function ( a, b, c ) {
  3256. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3257. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3258. this.setFromNormalAndCoplanarPoint( normal, a );
  3259. return this;
  3260. };
  3261. }(),
  3262. copy: function ( plane ) {
  3263. this.normal.copy( plane.normal );
  3264. this.constant = plane.constant;
  3265. return this;
  3266. },
  3267. normalize: function () {
  3268. // Note: will lead to a divide by zero if the plane is invalid.
  3269. var inverseNormalLength = 1.0 / this.normal.length();
  3270. this.normal.multiplyScalar( inverseNormalLength );
  3271. this.constant *= inverseNormalLength;
  3272. return this;
  3273. },
  3274. negate: function () {
  3275. this.constant *= -1;
  3276. this.normal.negate();
  3277. return this;
  3278. },
  3279. distanceToPoint: function ( point ) {
  3280. return this.normal.dot( point ) + this.constant;
  3281. },
  3282. distanceToSphere: function ( sphere ) {
  3283. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3284. },
  3285. projectPoint: function ( point, optionalTarget ) {
  3286. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3287. },
  3288. orthoPoint: function ( point, optionalTarget ) {
  3289. var perpendicularMagnitude = this.distanceToPoint( point );
  3290. var result = optionalTarget || new THREE.Vector3();
  3291. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3292. },
  3293. isIntersectionLine: function ( line ) {
  3294. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3295. var startSign = this.distanceToPoint( line.start );
  3296. var endSign = this.distanceToPoint( line.end );
  3297. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3298. },
  3299. intersectLine: function() {
  3300. var v1 = new THREE.Vector3();
  3301. return function ( line, optionalTarget ) {
  3302. var result = optionalTarget || new THREE.Vector3();
  3303. var direction = line.delta( v1 );
  3304. var denominator = this.normal.dot( direction );
  3305. if ( denominator == 0 ) {
  3306. // line is coplanar, return origin
  3307. if( this.distanceToPoint( line.start ) == 0 ) {
  3308. return result.copy( line.start );
  3309. }
  3310. // Unsure if this is the correct method to handle this case.
  3311. return undefined;
  3312. }
  3313. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3314. if( t < 0 || t > 1 ) {
  3315. return undefined;
  3316. }
  3317. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3318. };
  3319. }(),
  3320. coplanarPoint: function ( optionalTarget ) {
  3321. var result = optionalTarget || new THREE.Vector3();
  3322. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3323. },
  3324. applyMatrix4: function() {
  3325. var v1 = new THREE.Vector3();
  3326. var v2 = new THREE.Vector3();
  3327. return function ( matrix, optionalNormalMatrix ) {
  3328. // compute new normal based on theory here:
  3329. // http://www.songho.ca/opengl/gl_normaltransform.html
  3330. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3331. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3332. var newCoplanarPoint = this.coplanarPoint( v2 );
  3333. newCoplanarPoint.applyMatrix4( matrix );
  3334. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3335. return this;
  3336. };
  3337. }(),
  3338. translate: function ( offset ) {
  3339. this.constant = this.constant - offset.dot( this.normal );
  3340. return this;
  3341. },
  3342. equals: function ( plane ) {
  3343. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3344. },
  3345. clone: function () {
  3346. return new THREE.Plane().copy( this );
  3347. }
  3348. };
  3349. /**
  3350. * @author alteredq / http://alteredqualia.com/
  3351. * @author mrdoob / http://mrdoob.com/
  3352. */
  3353. THREE.Math = {
  3354. PI2: Math.PI * 2,
  3355. generateUUID: function () {
  3356. // http://www.broofa.com/Tools/Math.uuid.htm
  3357. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3358. var uuid = new Array(36);
  3359. var rnd = 0, r;
  3360. return function () {
  3361. for ( var i = 0; i < 36; i ++ ) {
  3362. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3363. uuid[ i ] = '-';
  3364. } else if ( i == 14 ) {
  3365. uuid[ i ] = '4';
  3366. } else {
  3367. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3368. r = rnd & 0xf;
  3369. rnd = rnd >> 4;
  3370. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3371. }
  3372. }
  3373. return uuid.join('');
  3374. };
  3375. }(),
  3376. // Clamp value to range <a, b>
  3377. clamp: function ( x, a, b ) {
  3378. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3379. },
  3380. // Clamp value to range <a, inf)
  3381. clampBottom: function ( x, a ) {
  3382. return x < a ? a : x;
  3383. },
  3384. // Linear mapping from range <a1, a2> to range <b1, b2>
  3385. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3386. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3387. },
  3388. // http://en.wikipedia.org/wiki/Smoothstep
  3389. smoothstep: function ( x, min, max ) {
  3390. if ( x <= min ) return 0;
  3391. if ( x >= max ) return 1;
  3392. x = ( x - min )/( max - min );
  3393. return x*x*(3 - 2*x);
  3394. },
  3395. smootherstep: function ( x, min, max ) {
  3396. if ( x <= min ) return 0;
  3397. if ( x >= max ) return 1;
  3398. x = ( x - min )/( max - min );
  3399. return x*x*x*(x*(x*6 - 15) + 10);
  3400. },
  3401. // Random float from <0, 1> with 16 bits of randomness
  3402. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3403. random16: function () {
  3404. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3405. },
  3406. // Random integer from <low, high> interval
  3407. randInt: function ( low, high ) {
  3408. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3409. },
  3410. // Random float from <low, high> interval
  3411. randFloat: function ( low, high ) {
  3412. return low + Math.random() * ( high - low );
  3413. },
  3414. // Random float from <-range/2, range/2> interval
  3415. randFloatSpread: function ( range ) {
  3416. return range * ( 0.5 - Math.random() );
  3417. },
  3418. sign: function ( x ) {
  3419. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3420. },
  3421. degToRad: function() {
  3422. var degreeToRadiansFactor = Math.PI / 180;
  3423. return function ( degrees ) {
  3424. return degrees * degreeToRadiansFactor;
  3425. };
  3426. }(),
  3427. radToDeg: function() {
  3428. var radianToDegreesFactor = 180 / Math.PI;
  3429. return function ( radians ) {
  3430. return radians * radianToDegreesFactor;
  3431. };
  3432. }()
  3433. };
  3434. /**
  3435. * Spline from Tween.js, slightly optimized (and trashed)
  3436. * http://sole.github.com/tween.js/examples/05_spline.html
  3437. *
  3438. * @author mrdoob / http://mrdoob.com/
  3439. * @author alteredq / http://alteredqualia.com/
  3440. */
  3441. THREE.Spline = function ( points ) {
  3442. this.points = points;
  3443. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3444. point, intPoint, weight, w2, w3,
  3445. pa, pb, pc, pd;
  3446. this.initFromArray = function( a ) {
  3447. this.points = [];
  3448. for ( var i = 0; i < a.length; i++ ) {
  3449. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3450. }
  3451. };
  3452. this.getPoint = function ( k ) {
  3453. point = ( this.points.length - 1 ) * k;
  3454. intPoint = Math.floor( point );
  3455. weight = point - intPoint;
  3456. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3457. c[ 1 ] = intPoint;
  3458. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3459. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3460. pa = this.points[ c[ 0 ] ];
  3461. pb = this.points[ c[ 1 ] ];
  3462. pc = this.points[ c[ 2 ] ];
  3463. pd = this.points[ c[ 3 ] ];
  3464. w2 = weight * weight;
  3465. w3 = weight * w2;
  3466. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3467. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3468. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3469. return v3;
  3470. };
  3471. this.getControlPointsArray = function () {
  3472. var i, p, l = this.points.length,
  3473. coords = [];
  3474. for ( i = 0; i < l; i ++ ) {
  3475. p = this.points[ i ];
  3476. coords[ i ] = [ p.x, p.y, p.z ];
  3477. }
  3478. return coords;
  3479. };
  3480. // approximate length by summing linear segments
  3481. this.getLength = function ( nSubDivisions ) {
  3482. var i, index, nSamples, position,
  3483. point = 0, intPoint = 0, oldIntPoint = 0,
  3484. oldPosition = new THREE.Vector3(),
  3485. tmpVec = new THREE.Vector3(),
  3486. chunkLengths = [],
  3487. totalLength = 0;
  3488. // first point has 0 length
  3489. chunkLengths[ 0 ] = 0;
  3490. if ( !nSubDivisions ) nSubDivisions = 100;
  3491. nSamples = this.points.length * nSubDivisions;
  3492. oldPosition.copy( this.points[ 0 ] );
  3493. for ( i = 1; i < nSamples; i ++ ) {
  3494. index = i / nSamples;
  3495. position = this.getPoint( index );
  3496. tmpVec.copy( position );
  3497. totalLength += tmpVec.distanceTo( oldPosition );
  3498. oldPosition.copy( position );
  3499. point = ( this.points.length - 1 ) * index;
  3500. intPoint = Math.floor( point );
  3501. if ( intPoint != oldIntPoint ) {
  3502. chunkLengths[ intPoint ] = totalLength;
  3503. oldIntPoint = intPoint;
  3504. }
  3505. }
  3506. // last point ends with total length
  3507. chunkLengths[ chunkLengths.length ] = totalLength;
  3508. return { chunks: chunkLengths, total: totalLength };
  3509. };
  3510. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3511. var i, j,
  3512. index, indexCurrent, indexNext,
  3513. linearDistance, realDistance,
  3514. sampling, position,
  3515. newpoints = [],
  3516. tmpVec = new THREE.Vector3(),
  3517. sl = this.getLength();
  3518. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3519. for ( i = 1; i < this.points.length; i++ ) {
  3520. //tmpVec.copy( this.points[ i - 1 ] );
  3521. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3522. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3523. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3524. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3525. indexNext = i / ( this.points.length - 1 );
  3526. for ( j = 1; j < sampling - 1; j++ ) {
  3527. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3528. position = this.getPoint( index );
  3529. newpoints.push( tmpVec.copy( position ).clone() );
  3530. }
  3531. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3532. }
  3533. this.points = newpoints;
  3534. };
  3535. // Catmull-Rom
  3536. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3537. var v0 = ( p2 - p0 ) * 0.5,
  3538. v1 = ( p3 - p1 ) * 0.5;
  3539. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3540. };
  3541. };
  3542. /**
  3543. * @author bhouston / http://exocortex.com
  3544. * @author mrdoob / http://mrdoob.com/
  3545. */
  3546. THREE.Triangle = function ( a, b, c ) {
  3547. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3548. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3549. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3550. };
  3551. THREE.Triangle.normal = function() {
  3552. var v0 = new THREE.Vector3();
  3553. return function ( a, b, c, optionalTarget ) {
  3554. var result = optionalTarget || new THREE.Vector3();
  3555. result.subVectors( c, b );
  3556. v0.subVectors( a, b );
  3557. result.cross( v0 );
  3558. var resultLengthSq = result.lengthSq();
  3559. if( resultLengthSq > 0 ) {
  3560. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3561. }
  3562. return result.set( 0, 0, 0 );
  3563. };
  3564. }();
  3565. // static/instance method to calculate barycoordinates
  3566. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3567. THREE.Triangle.barycoordFromPoint = function() {
  3568. var v0 = new THREE.Vector3();
  3569. var v1 = new THREE.Vector3();
  3570. var v2 = new THREE.Vector3();
  3571. return function ( point, a, b, c, optionalTarget ) {
  3572. v0.subVectors( c, a );
  3573. v1.subVectors( b, a );
  3574. v2.subVectors( point, a );
  3575. var dot00 = v0.dot( v0 );
  3576. var dot01 = v0.dot( v1 );
  3577. var dot02 = v0.dot( v2 );
  3578. var dot11 = v1.dot( v1 );
  3579. var dot12 = v1.dot( v2 );
  3580. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3581. var result = optionalTarget || new THREE.Vector3();
  3582. // colinear or singular triangle
  3583. if( denom == 0 ) {
  3584. // arbitrary location outside of triangle?
  3585. // not sure if this is the best idea, maybe should be returning undefined
  3586. return result.set( -2, -1, -1 );
  3587. }
  3588. var invDenom = 1 / denom;
  3589. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3590. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3591. // barycoordinates must always sum to 1
  3592. return result.set( 1 - u - v, v, u );
  3593. };
  3594. }();
  3595. THREE.Triangle.containsPoint = function() {
  3596. var v1 = new THREE.Vector3();
  3597. return function ( point, a, b, c ) {
  3598. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3599. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3600. };
  3601. }();
  3602. THREE.Triangle.prototype = {
  3603. constructor: THREE.Triangle,
  3604. set: function ( a, b, c ) {
  3605. this.a.copy( a );
  3606. this.b.copy( b );
  3607. this.c.copy( c );
  3608. return this;
  3609. },
  3610. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3611. this.a.copy( points[i0] );
  3612. this.b.copy( points[i1] );
  3613. this.c.copy( points[i2] );
  3614. return this;
  3615. },
  3616. copy: function ( triangle ) {
  3617. this.a.copy( triangle.a );
  3618. this.b.copy( triangle.b );
  3619. this.c.copy( triangle.c );
  3620. return this;
  3621. },
  3622. area: function() {
  3623. var v0 = new THREE.Vector3();
  3624. var v1 = new THREE.Vector3();
  3625. return function () {
  3626. v0.subVectors( this.c, this.b );
  3627. v1.subVectors( this.a, this.b );
  3628. return v0.cross( v1 ).length() * 0.5;
  3629. };
  3630. }(),
  3631. midpoint: function ( optionalTarget ) {
  3632. var result = optionalTarget || new THREE.Vector3();
  3633. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3634. },
  3635. normal: function ( optionalTarget ) {
  3636. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3637. },
  3638. plane: function ( optionalTarget ) {
  3639. var result = optionalTarget || new THREE.Plane();
  3640. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3641. },
  3642. barycoordFromPoint: function ( point, optionalTarget ) {
  3643. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3644. },
  3645. containsPoint: function ( point ) {
  3646. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3647. },
  3648. equals: function ( triangle ) {
  3649. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3650. },
  3651. clone: function () {
  3652. return new THREE.Triangle().copy( this );
  3653. }
  3654. };
  3655. /**
  3656. * @author mrdoob / http://mrdoob.com/
  3657. */
  3658. THREE.Vertex = function ( v ) {
  3659. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3660. return v;
  3661. };
  3662. /**
  3663. * @author mrdoob / http://mrdoob.com/
  3664. */
  3665. THREE.UV = function ( u, v ) {
  3666. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3667. return new THREE.Vector2( u, v );
  3668. };
  3669. /**
  3670. * @author alteredq / http://alteredqualia.com/
  3671. */
  3672. THREE.Clock = function ( autoStart ) {
  3673. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3674. this.startTime = 0;
  3675. this.oldTime = 0;
  3676. this.elapsedTime = 0;
  3677. this.running = false;
  3678. };
  3679. THREE.Clock.prototype = {
  3680. constructor: THREE.Clock,
  3681. start: function () {
  3682. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3683. ? self.performance.now()
  3684. : Date.now();
  3685. this.oldTime = this.startTime;
  3686. this.running = true;
  3687. },
  3688. stop: function () {
  3689. this.getElapsedTime();
  3690. this.running = false;
  3691. },
  3692. getElapsedTime: function () {
  3693. this.getDelta();
  3694. return this.elapsedTime;
  3695. },
  3696. getDelta: function () {
  3697. var diff = 0;
  3698. if ( this.autoStart && ! this.running ) {
  3699. this.start();
  3700. }
  3701. if ( this.running ) {
  3702. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3703. ? self.performance.now()
  3704. : Date.now();
  3705. diff = 0.001 * ( newTime - this.oldTime );
  3706. this.oldTime = newTime;
  3707. this.elapsedTime += diff;
  3708. }
  3709. return diff;
  3710. }
  3711. };
  3712. /**
  3713. * https://github.com/mrdoob/eventdispatcher.js/
  3714. */
  3715. THREE.EventDispatcher = function () {}
  3716. THREE.EventDispatcher.prototype = {
  3717. constructor: THREE.EventDispatcher,
  3718. addEventListener: function ( type, listener ) {
  3719. if ( this._listeners === undefined ) this._listeners = {};
  3720. var listeners = this._listeners;
  3721. if ( listeners[ type ] === undefined ) {
  3722. listeners[ type ] = [];
  3723. }
  3724. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3725. listeners[ type ].push( listener );
  3726. }
  3727. },
  3728. hasEventListener: function ( type, listener ) {
  3729. if ( this._listeners === undefined ) return false;
  3730. var listeners = this._listeners;
  3731. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3732. return true;
  3733. }
  3734. return false;
  3735. },
  3736. removeEventListener: function ( type, listener ) {
  3737. if ( this._listeners === undefined ) return;
  3738. var listeners = this._listeners;
  3739. var index = listeners[ type ].indexOf( listener );
  3740. if ( index !== - 1 ) {
  3741. listeners[ type ].splice( index, 1 );
  3742. }
  3743. },
  3744. dispatchEvent: function ( event ) {
  3745. if ( this._listeners === undefined ) return;
  3746. var listeners = this._listeners;
  3747. var listenerArray = listeners[ event.type ];
  3748. if ( listenerArray !== undefined ) {
  3749. event.target = this;
  3750. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3751. listenerArray[ i ].call( this, event );
  3752. }
  3753. }
  3754. }
  3755. };
  3756. /**
  3757. * @author mrdoob / http://mrdoob.com/
  3758. * @author bhouston / http://exocortex.com/
  3759. */
  3760. ( function ( THREE ) {
  3761. THREE.Raycaster = function ( origin, direction, near, far ) {
  3762. this.ray = new THREE.Ray( origin, direction );
  3763. // normalized ray.direction required for accurate distance calculations
  3764. if ( this.ray.direction.lengthSq() > 0 ) {
  3765. this.ray.direction.normalize();
  3766. }
  3767. this.near = near || 0;
  3768. this.far = far || Infinity;
  3769. };
  3770. var sphere = new THREE.Sphere();
  3771. var localRay = new THREE.Ray();
  3772. var facePlane = new THREE.Plane();
  3773. var intersectPoint = new THREE.Vector3();
  3774. var matrixPosition = new THREE.Vector3();
  3775. var inverseMatrix = new THREE.Matrix4();
  3776. var descSort = function ( a, b ) {
  3777. return a.distance - b.distance;
  3778. };
  3779. var intersectObject = function ( object, raycaster, intersects ) {
  3780. if ( object instanceof THREE.Particle ) {
  3781. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3782. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3783. if ( distance > object.scale.x ) {
  3784. return intersects;
  3785. }
  3786. intersects.push( {
  3787. distance: distance,
  3788. point: object.position,
  3789. face: null,
  3790. object: object
  3791. } );
  3792. } else if ( object instanceof THREE.LOD ) {
  3793. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3794. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3795. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3796. } else if (object instanceof THREE.Mesh ) {
  3797. // Checking boundingSphere distance to ray
  3798. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3799. sphere.set( matrixPosition, object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3800. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  3801. return intersects;
  3802. }
  3803. var geometry = object.geometry;
  3804. var vertices = geometry.vertices;
  3805. if ( geometry instanceof THREE.BufferGeometry ) {
  3806. var material = object.material;
  3807. if ( material === undefined ) return intersects;
  3808. if ( ! geometry.dynamic ) return intersects;
  3809. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3810. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3811. var side = object.material.side;
  3812. var a, b, c;
  3813. var precision = raycaster.precision;
  3814. inverseMatrix.getInverse( object.matrixWorld );
  3815. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3816. var fl;
  3817. var indexed = false;
  3818. if ( geometry.attributes.index ) {
  3819. indexed = true;
  3820. fl = geometry.attributes.index.numItems / 3;
  3821. } else {
  3822. fl = geometry.attributes.position.numItems / 9;
  3823. }
  3824. var vA = new THREE.Vector3();
  3825. var vB = new THREE.Vector3();
  3826. var vC = new THREE.Vector3();
  3827. var vCB = new THREE.Vector3();
  3828. var vAB = new THREE.Vector3();
  3829. for ( var oi = 0; oi < geometry.offsets.length; ++oi ) {
  3830. var start = geometry.offsets[ oi ].start;
  3831. var count = geometry.offsets[ oi ].count;
  3832. var index = geometry.offsets[ oi ].index;
  3833. for ( var i = start, il = start + count; i < il; i += 3 ) {
  3834. if ( indexed ) {
  3835. a = index + geometry.attributes.index.array[ i ];
  3836. b = index + geometry.attributes.index.array[ i + 1 ];
  3837. c = index + geometry.attributes.index.array[ i + 2 ];
  3838. } else {
  3839. a = index;
  3840. b = index + 1;
  3841. c = index + 2;
  3842. }
  3843. vA.set( geometry.attributes.position.array[ a * 3 ],
  3844. geometry.attributes.position.array[ a * 3 + 1 ],
  3845. geometry.attributes.position.array[ a * 3 + 2] );
  3846. vB.set( geometry.attributes.position.array[ b * 3 ],
  3847. geometry.attributes.position.array[ b * 3 + 1 ],
  3848. geometry.attributes.position.array[ b * 3 + 2] );
  3849. vC.set( geometry.attributes.position.array[ c * 3 ],
  3850. geometry.attributes.position.array[ c * 3 + 1 ],
  3851. geometry.attributes.position.array[ c * 3 + 2 ] );
  3852. facePlane.setFromCoplanarPoints( vA, vB, vC );
  3853. var planeDistance = localRay.distanceToPlane( facePlane );
  3854. // bail if raycaster and plane are parallel
  3855. if ( Math.abs( planeDistance ) < precision ) continue;
  3856. // if negative distance, then plane is behind raycaster
  3857. if ( planeDistance < 0 ) continue;
  3858. // check if we hit the wrong side of a single sided face
  3859. side = material.side;
  3860. if ( side !== THREE.DoubleSide ) {
  3861. var planeSign = localRay.direction.dot( facePlane.normal );
  3862. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3863. }
  3864. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3865. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3866. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3867. if ( ! THREE.Triangle.containsPoint( intersectPoint, vA, vB, vC ) ) continue;
  3868. intersects.push( {
  3869. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3870. point: raycaster.ray.at(planeDistance),
  3871. face: null,
  3872. faceIndex: null,
  3873. object: object
  3874. } );
  3875. }
  3876. }
  3877. } else if ( geometry instanceof THREE.Geometry ) {
  3878. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3879. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3880. var side = object.material.side;
  3881. var a, b, c, d;
  3882. var precision = raycaster.precision;
  3883. inverseMatrix.getInverse( object.matrixWorld );
  3884. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3885. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3886. var face = geometry.faces[ f ];
  3887. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3888. if ( material === undefined ) continue;
  3889. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3890. var planeDistance = localRay.distanceToPlane( facePlane );
  3891. // bail if raycaster and plane are parallel
  3892. if ( Math.abs( planeDistance ) < precision ) continue;
  3893. // if negative distance, then plane is behind raycaster
  3894. if ( planeDistance < 0 ) continue;
  3895. // check if we hit the wrong side of a single sided face
  3896. side = material.side;
  3897. if ( side !== THREE.DoubleSide ) {
  3898. var planeSign = localRay.direction.dot( facePlane.normal );
  3899. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3900. }
  3901. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3902. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3903. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3904. if ( face instanceof THREE.Face3 ) {
  3905. a = vertices[ face.a ];
  3906. b = vertices[ face.b ];
  3907. c = vertices[ face.c ];
  3908. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3909. } else if ( face instanceof THREE.Face4 ) {
  3910. a = vertices[ face.a ];
  3911. b = vertices[ face.b ];
  3912. c = vertices[ face.c ];
  3913. d = vertices[ face.d ];
  3914. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3915. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3916. } else {
  3917. // This is added because if we call out of this if/else group when none of the cases
  3918. // match it will add a point to the intersection list erroneously.
  3919. throw Error( "face type not supported" );
  3920. }
  3921. intersects.push( {
  3922. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3923. point: raycaster.ray.at( planeDistance ),
  3924. face: face,
  3925. faceIndex: f,
  3926. object: object
  3927. } );
  3928. }
  3929. }
  3930. }
  3931. };
  3932. var intersectDescendants = function ( object, raycaster, intersects ) {
  3933. var descendants = object.getDescendants();
  3934. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3935. intersectObject( descendants[ i ], raycaster, intersects );
  3936. }
  3937. };
  3938. //
  3939. THREE.Raycaster.prototype.precision = 0.0001;
  3940. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3941. this.ray.set( origin, direction );
  3942. // normalized ray.direction required for accurate distance calculations
  3943. if ( this.ray.direction.length() > 0 ) {
  3944. this.ray.direction.normalize();
  3945. }
  3946. };
  3947. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3948. var intersects = [];
  3949. if ( recursive === true ) {
  3950. intersectDescendants( object, this, intersects );
  3951. }
  3952. intersectObject( object, this, intersects );
  3953. intersects.sort( descSort );
  3954. return intersects;
  3955. };
  3956. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3957. var intersects = [];
  3958. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3959. intersectObject( objects[ i ], this, intersects );
  3960. if ( recursive === true ) {
  3961. intersectDescendants( objects[ i ], this, intersects );
  3962. }
  3963. }
  3964. intersects.sort( descSort );
  3965. return intersects;
  3966. };
  3967. }( THREE ) );
  3968. /**
  3969. * @author mrdoob / http://mrdoob.com/
  3970. * @author mikael emtinger / http://gomo.se/
  3971. * @author alteredq / http://alteredqualia.com/
  3972. * @author WestLangley / http://github.com/WestLangley
  3973. */
  3974. THREE.Object3D = function () {
  3975. this.id = THREE.Math.generateUUID();
  3976. this.name = '';
  3977. this.parent = undefined;
  3978. this.children = [];
  3979. this.up = new THREE.Vector3( 0, 1, 0 );
  3980. this.position = new THREE.Vector3();
  3981. this.rotation = new THREE.Euler();
  3982. this.quaternion = new THREE.Quaternion();
  3983. this.scale = new THREE.Vector3( 1, 1, 1 );
  3984. // keep rotation and quaternion in sync
  3985. this.rotation._quaternion = this.quaternion;
  3986. this.quaternion._euler = this.rotation;
  3987. this.renderDepth = null;
  3988. this.rotationAutoUpdate = true;
  3989. this.matrix = new THREE.Matrix4();
  3990. this.matrixWorld = new THREE.Matrix4();
  3991. this.matrixAutoUpdate = true;
  3992. this.matrixWorldNeedsUpdate = true;
  3993. this.visible = true;
  3994. this.castShadow = false;
  3995. this.receiveShadow = false;
  3996. this.frustumCulled = true;
  3997. this.userData = {};
  3998. };
  3999. THREE.Object3D.prototype = {
  4000. constructor: THREE.Object3D,
  4001. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4002. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4003. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4004. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4005. get eulerOrder () {
  4006. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4007. return this.rotation.order;
  4008. },
  4009. set eulerOrder ( value ) {
  4010. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4011. this.rotation.order = value;
  4012. },
  4013. get useQuaternion () {
  4014. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4015. },
  4016. set useQuaternion ( value ) {
  4017. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4018. },
  4019. applyMatrix: function () {
  4020. var m1 = new THREE.Matrix4();
  4021. return function ( matrix ) {
  4022. this.matrix.multiplyMatrices( matrix, this.matrix );
  4023. this.position.getPositionFromMatrix( this.matrix );
  4024. this.scale.getScaleFromMatrix( this.matrix );
  4025. m1.extractRotation( this.matrix );
  4026. this.quaternion.setFromRotationMatrix( m1 );
  4027. }
  4028. }(),
  4029. rotateOnAxis: function() {
  4030. // rotate object on axis in object space
  4031. // axis is assumed to be normalized
  4032. var q1 = new THREE.Quaternion();
  4033. var q2 = new THREE.Quaternion();
  4034. return function ( axis, angle ) {
  4035. q1.setFromAxisAngle( axis, angle );
  4036. this.quaternion.multiply( q1 );
  4037. return this;
  4038. }
  4039. }(),
  4040. translateOnAxis: function () {
  4041. // translate object by distance along axis in object space
  4042. // axis is assumed to be normalized
  4043. var v1 = new THREE.Vector3();
  4044. return function ( axis, distance ) {
  4045. v1.copy( axis );
  4046. v1.applyQuaternion( this.quaternion );
  4047. this.position.add( v1.multiplyScalar( distance ) );
  4048. return this;
  4049. }
  4050. }(),
  4051. translate: function ( distance, axis ) {
  4052. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4053. return this.translateOnAxis( axis, distance );
  4054. },
  4055. translateX: function () {
  4056. var v1 = new THREE.Vector3( 1, 0, 0 );
  4057. return function ( distance ) {
  4058. return this.translateOnAxis( v1, distance );
  4059. };
  4060. }(),
  4061. translateY: function () {
  4062. var v1 = new THREE.Vector3( 0, 1, 0 );
  4063. return function ( distance ) {
  4064. return this.translateOnAxis( v1, distance );
  4065. };
  4066. }(),
  4067. translateZ: function () {
  4068. var v1 = new THREE.Vector3( 0, 0, 1 );
  4069. return function ( distance ) {
  4070. return this.translateOnAxis( v1, distance );
  4071. };
  4072. }(),
  4073. localToWorld: function ( vector ) {
  4074. return vector.applyMatrix4( this.matrixWorld );
  4075. },
  4076. worldToLocal: function () {
  4077. var m1 = new THREE.Matrix4();
  4078. return function ( vector ) {
  4079. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4080. };
  4081. }(),
  4082. lookAt: function () {
  4083. // This routine does not support objects with rotated and/or translated parent(s)
  4084. var m1 = new THREE.Matrix4();
  4085. return function ( vector ) {
  4086. m1.lookAt( vector, this.position, this.up );
  4087. this.quaternion.setFromRotationMatrix( m1 );
  4088. };
  4089. }(),
  4090. add: function ( object ) {
  4091. if ( object === this ) {
  4092. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4093. return;
  4094. }
  4095. if ( object instanceof THREE.Object3D ) {
  4096. if ( object.parent !== undefined ) {
  4097. object.parent.remove( object );
  4098. }
  4099. object.parent = this;
  4100. this.children.push( object );
  4101. // add to scene
  4102. var scene = this;
  4103. while ( scene.parent !== undefined ) {
  4104. scene = scene.parent;
  4105. }
  4106. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4107. scene.__addObject( object );
  4108. }
  4109. }
  4110. },
  4111. remove: function ( object ) {
  4112. var index = this.children.indexOf( object );
  4113. if ( index !== - 1 ) {
  4114. object.parent = undefined;
  4115. this.children.splice( index, 1 );
  4116. // remove from scene
  4117. var scene = this;
  4118. while ( scene.parent !== undefined ) {
  4119. scene = scene.parent;
  4120. }
  4121. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4122. scene.__removeObject( object );
  4123. }
  4124. }
  4125. },
  4126. traverse: function ( callback ) {
  4127. callback( this );
  4128. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4129. this.children[ i ].traverse( callback );
  4130. }
  4131. },
  4132. getObjectById: function ( id, recursive ) {
  4133. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4134. var child = this.children[ i ];
  4135. if ( child.id === id ) {
  4136. return child;
  4137. }
  4138. if ( recursive === true ) {
  4139. child = child.getObjectById( id, recursive );
  4140. if ( child !== undefined ) {
  4141. return child;
  4142. }
  4143. }
  4144. }
  4145. return undefined;
  4146. },
  4147. getObjectByName: function ( name, recursive ) {
  4148. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4149. var child = this.children[ i ];
  4150. if ( child.name === name ) {
  4151. return child;
  4152. }
  4153. if ( recursive === true ) {
  4154. child = child.getObjectByName( name, recursive );
  4155. if ( child !== undefined ) {
  4156. return child;
  4157. }
  4158. }
  4159. }
  4160. return undefined;
  4161. },
  4162. getChildByName: function ( name, recursive ) {
  4163. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4164. return this.getObjectByName( name, recursive );
  4165. },
  4166. getDescendants: function ( array ) {
  4167. if ( array === undefined ) array = [];
  4168. Array.prototype.push.apply( array, this.children );
  4169. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4170. this.children[ i ].getDescendants( array );
  4171. }
  4172. return array;
  4173. },
  4174. updateMatrix: function () {
  4175. this.matrix.compose( this.position, this.quaternion, this.scale );
  4176. this.matrixWorldNeedsUpdate = true;
  4177. },
  4178. updateMatrixWorld: function ( force ) {
  4179. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4180. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4181. if ( this.parent === undefined ) {
  4182. this.matrixWorld.copy( this.matrix );
  4183. } else {
  4184. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4185. }
  4186. this.matrixWorldNeedsUpdate = false;
  4187. force = true;
  4188. }
  4189. // update children
  4190. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4191. this.children[ i ].updateMatrixWorld( force );
  4192. }
  4193. },
  4194. clone: function ( object, recursive ) {
  4195. if ( object === undefined ) object = new THREE.Object3D();
  4196. if ( recursive === undefined ) recursive = true;
  4197. object.name = this.name;
  4198. object.up.copy( this.up );
  4199. object.position.copy( this.position );
  4200. object.quaternion.copy( this.quaternion );
  4201. object.scale.copy( this.scale );
  4202. object.renderDepth = this.renderDepth;
  4203. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4204. object.matrix.copy( this.matrix );
  4205. object.matrixWorld.copy( this.matrixWorld );
  4206. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4207. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4208. object.visible = this.visible;
  4209. object.castShadow = this.castShadow;
  4210. object.receiveShadow = this.receiveShadow;
  4211. object.frustumCulled = this.frustumCulled;
  4212. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4213. if ( recursive === true ) {
  4214. for ( var i = 0; i < this.children.length; i ++ ) {
  4215. var child = this.children[ i ];
  4216. object.add( child.clone() );
  4217. }
  4218. }
  4219. return object;
  4220. }
  4221. };
  4222. THREE.Object3D.defaultEulerOrder = 'XYZ';
  4223. /**
  4224. * @author mrdoob / http://mrdoob.com/
  4225. * @author supereggbert / http://www.paulbrunt.co.uk/
  4226. * @author julianwa / https://github.com/julianwa
  4227. */
  4228. THREE.Projector = function () {
  4229. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4230. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4231. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4232. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  4233. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4234. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  4235. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4236. _vector3 = new THREE.Vector3(),
  4237. _vector4 = new THREE.Vector4(),
  4238. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4239. _boundingBox = new THREE.Box3(),
  4240. _points3 = new Array( 3 ),
  4241. _points4 = new Array( 4 ),
  4242. _viewMatrix = new THREE.Matrix4(),
  4243. _viewProjectionMatrix = new THREE.Matrix4(),
  4244. _modelMatrix,
  4245. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4246. _normalMatrix = new THREE.Matrix3(),
  4247. _normalViewMatrix = new THREE.Matrix3(),
  4248. _centroid = new THREE.Vector3(),
  4249. _frustum = new THREE.Frustum(),
  4250. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4251. _clippedVertex2PositionScreen = new THREE.Vector4();
  4252. this.projectVector = function ( vector, camera ) {
  4253. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4254. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4255. return vector.applyProjection( _viewProjectionMatrix );
  4256. };
  4257. this.unprojectVector = function ( vector, camera ) {
  4258. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4259. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4260. return vector.applyProjection( _viewProjectionMatrix );
  4261. };
  4262. this.pickingRay = function ( vector, camera ) {
  4263. // set two vectors with opposing z values
  4264. vector.z = -1.0;
  4265. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4266. this.unprojectVector( vector, camera );
  4267. this.unprojectVector( end, camera );
  4268. // find direction from vector to end
  4269. end.sub( vector ).normalize();
  4270. return new THREE.Raycaster( vector, end );
  4271. };
  4272. var getObject = function ( object ) {
  4273. _object = getNextObjectInPool();
  4274. _object.object = object;
  4275. if ( object.renderDepth !== null ) {
  4276. _object.z = object.renderDepth;
  4277. } else {
  4278. _vector3.getPositionFromMatrix( object.matrixWorld );
  4279. _vector3.applyProjection( _viewProjectionMatrix );
  4280. _object.z = _vector3.z;
  4281. }
  4282. return _object;
  4283. };
  4284. var projectObject = function ( object ) {
  4285. if ( object.visible === false ) return;
  4286. if ( object instanceof THREE.Light ) {
  4287. _renderData.lights.push( object );
  4288. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4289. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4290. _renderData.objects.push( getObject( object ) );
  4291. }
  4292. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4293. _renderData.sprites.push( getObject( object ) );
  4294. }
  4295. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4296. projectObject( object.children[ i ] );
  4297. }
  4298. };
  4299. var projectGraph = function ( root, sortObjects ) {
  4300. _objectCount = 0;
  4301. _renderData.objects.length = 0;
  4302. _renderData.sprites.length = 0;
  4303. _renderData.lights.length = 0;
  4304. projectObject( root );
  4305. if ( sortObjects === true ) {
  4306. _renderData.objects.sort( painterSort );
  4307. }
  4308. };
  4309. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4310. var visible = false,
  4311. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4312. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4313. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4314. _face3Count = 0;
  4315. _face4Count = 0;
  4316. _lineCount = 0;
  4317. _particleCount = 0;
  4318. _renderData.elements.length = 0;
  4319. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4320. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4321. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4322. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4323. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4324. _frustum.setFromMatrix( _viewProjectionMatrix );
  4325. projectGraph( scene, sortObjects );
  4326. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4327. object = _renderData.objects[ o ].object;
  4328. _modelMatrix = object.matrixWorld;
  4329. _vertexCount = 0;
  4330. if ( object instanceof THREE.Mesh ) {
  4331. geometry = object.geometry;
  4332. vertices = geometry.vertices;
  4333. faces = geometry.faces;
  4334. faceVertexUvs = geometry.faceVertexUvs;
  4335. _normalMatrix.getNormalMatrix( _modelMatrix );
  4336. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4337. objectMaterials = isFaceMaterial === true ? object.material : null;
  4338. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4339. _vertex = getNextVertexInPool();
  4340. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4341. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4342. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4343. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4344. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4345. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4346. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4347. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4348. }
  4349. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4350. face = faces[ f ];
  4351. var material = isFaceMaterial === true
  4352. ? objectMaterials.materials[ face.materialIndex ]
  4353. : object.material;
  4354. if ( material === undefined ) continue;
  4355. var side = material.side;
  4356. if ( face instanceof THREE.Face3 ) {
  4357. v1 = _vertexPool[ face.a ];
  4358. v2 = _vertexPool[ face.b ];
  4359. v3 = _vertexPool[ face.c ];
  4360. _points3[ 0 ] = v1.positionScreen;
  4361. _points3[ 1 ] = v2.positionScreen;
  4362. _points3[ 2 ] = v3.positionScreen;
  4363. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4364. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4365. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4366. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4367. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4368. _face = getNextFace3InPool();
  4369. _face.v1.copy( v1 );
  4370. _face.v2.copy( v2 );
  4371. _face.v3.copy( v3 );
  4372. } else {
  4373. continue;
  4374. }
  4375. } else {
  4376. continue;
  4377. }
  4378. } else if ( face instanceof THREE.Face4 ) {
  4379. v1 = _vertexPool[ face.a ];
  4380. v2 = _vertexPool[ face.b ];
  4381. v3 = _vertexPool[ face.c ];
  4382. v4 = _vertexPool[ face.d ];
  4383. _points4[ 0 ] = v1.positionScreen;
  4384. _points4[ 1 ] = v2.positionScreen;
  4385. _points4[ 2 ] = v3.positionScreen;
  4386. _points4[ 3 ] = v4.positionScreen;
  4387. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4388. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4389. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4390. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4391. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4392. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4393. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4394. _face = getNextFace4InPool();
  4395. _face.v1.copy( v1 );
  4396. _face.v2.copy( v2 );
  4397. _face.v3.copy( v3 );
  4398. _face.v4.copy( v4 );
  4399. } else {
  4400. continue;
  4401. }
  4402. } else {
  4403. continue;
  4404. }
  4405. }
  4406. _face.normalModel.copy( face.normal );
  4407. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4408. _face.normalModel.negate();
  4409. }
  4410. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4411. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4412. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4413. faceVertexNormals = face.vertexNormals;
  4414. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4415. var normalModel = _face.vertexNormalsModel[ n ];
  4416. normalModel.copy( faceVertexNormals[ n ] );
  4417. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4418. normalModel.negate();
  4419. }
  4420. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4421. var normalModelView = _face.vertexNormalsModelView[ n ];
  4422. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4423. }
  4424. _face.vertexNormalsLength = faceVertexNormals.length;
  4425. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4426. uvs = faceVertexUvs[ c ][ f ];
  4427. if ( uvs === undefined ) continue;
  4428. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4429. _face.uvs[ c ][ u ] = uvs[ u ];
  4430. }
  4431. }
  4432. _face.color = face.color;
  4433. _face.material = material;
  4434. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4435. _face.z = _centroid.z;
  4436. _renderData.elements.push( _face );
  4437. }
  4438. } else if ( object instanceof THREE.Line ) {
  4439. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4440. vertices = object.geometry.vertices;
  4441. v1 = getNextVertexInPool();
  4442. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4443. // Handle LineStrip and LinePieces
  4444. var step = object.type === THREE.LinePieces ? 2 : 1;
  4445. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4446. v1 = getNextVertexInPool();
  4447. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4448. if ( ( v + 1 ) % step > 0 ) continue;
  4449. v2 = _vertexPool[ _vertexCount - 2 ];
  4450. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4451. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4452. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4453. // Perform the perspective divide
  4454. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4455. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4456. _line = getNextLineInPool();
  4457. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4458. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4459. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4460. _line.material = object.material;
  4461. if ( object.material.vertexColors === THREE.VertexColors ) {
  4462. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4463. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4464. }
  4465. _renderData.elements.push( _line );
  4466. }
  4467. }
  4468. }
  4469. }
  4470. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4471. object = _renderData.sprites[ o ].object;
  4472. _modelMatrix = object.matrixWorld;
  4473. if ( object instanceof THREE.Particle ) {
  4474. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4475. _vector4.applyMatrix4( _viewProjectionMatrix );
  4476. _vector4.z /= _vector4.w;
  4477. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4478. _particle = getNextParticleInPool();
  4479. _particle.object = object;
  4480. _particle.x = _vector4.x / _vector4.w;
  4481. _particle.y = _vector4.y / _vector4.w;
  4482. _particle.z = _vector4.z;
  4483. _particle.rotation = object.rotation.z;
  4484. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4485. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4486. _particle.material = object.material;
  4487. _renderData.elements.push( _particle );
  4488. }
  4489. }
  4490. }
  4491. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4492. return _renderData;
  4493. };
  4494. // Pools
  4495. function getNextObjectInPool() {
  4496. if ( _objectCount === _objectPoolLength ) {
  4497. var object = new THREE.RenderableObject();
  4498. _objectPool.push( object );
  4499. _objectPoolLength ++;
  4500. _objectCount ++;
  4501. return object;
  4502. }
  4503. return _objectPool[ _objectCount ++ ];
  4504. }
  4505. function getNextVertexInPool() {
  4506. if ( _vertexCount === _vertexPoolLength ) {
  4507. var vertex = new THREE.RenderableVertex();
  4508. _vertexPool.push( vertex );
  4509. _vertexPoolLength ++;
  4510. _vertexCount ++;
  4511. return vertex;
  4512. }
  4513. return _vertexPool[ _vertexCount ++ ];
  4514. }
  4515. function getNextFace3InPool() {
  4516. if ( _face3Count === _face3PoolLength ) {
  4517. var face = new THREE.RenderableFace3();
  4518. _face3Pool.push( face );
  4519. _face3PoolLength ++;
  4520. _face3Count ++;
  4521. return face;
  4522. }
  4523. return _face3Pool[ _face3Count ++ ];
  4524. }
  4525. function getNextFace4InPool() {
  4526. if ( _face4Count === _face4PoolLength ) {
  4527. var face = new THREE.RenderableFace4();
  4528. _face4Pool.push( face );
  4529. _face4PoolLength ++;
  4530. _face4Count ++;
  4531. return face;
  4532. }
  4533. return _face4Pool[ _face4Count ++ ];
  4534. }
  4535. function getNextLineInPool() {
  4536. if ( _lineCount === _linePoolLength ) {
  4537. var line = new THREE.RenderableLine();
  4538. _linePool.push( line );
  4539. _linePoolLength ++;
  4540. _lineCount ++
  4541. return line;
  4542. }
  4543. return _linePool[ _lineCount ++ ];
  4544. }
  4545. function getNextParticleInPool() {
  4546. if ( _particleCount === _particlePoolLength ) {
  4547. var particle = new THREE.RenderableParticle();
  4548. _particlePool.push( particle );
  4549. _particlePoolLength ++;
  4550. _particleCount ++
  4551. return particle;
  4552. }
  4553. return _particlePool[ _particleCount ++ ];
  4554. }
  4555. //
  4556. function painterSort( a, b ) {
  4557. return b.z - a.z;
  4558. }
  4559. function clipLine( s1, s2 ) {
  4560. var alpha1 = 0, alpha2 = 1,
  4561. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4562. // Z = -1 and Z = +1, respectively.
  4563. bc1near = s1.z + s1.w,
  4564. bc2near = s2.z + s2.w,
  4565. bc1far = - s1.z + s1.w,
  4566. bc2far = - s2.z + s2.w;
  4567. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4568. // Both vertices lie entirely within all clip planes.
  4569. return true;
  4570. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4571. // Both vertices lie entirely outside one of the clip planes.
  4572. return false;
  4573. } else {
  4574. // The line segment spans at least one clip plane.
  4575. if ( bc1near < 0 ) {
  4576. // v1 lies outside the near plane, v2 inside
  4577. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4578. } else if ( bc2near < 0 ) {
  4579. // v2 lies outside the near plane, v1 inside
  4580. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4581. }
  4582. if ( bc1far < 0 ) {
  4583. // v1 lies outside the far plane, v2 inside
  4584. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4585. } else if ( bc2far < 0 ) {
  4586. // v2 lies outside the far plane, v2 inside
  4587. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4588. }
  4589. if ( alpha2 < alpha1 ) {
  4590. // The line segment spans two boundaries, but is outside both of them.
  4591. // (This can't happen when we're only clipping against just near/far but good
  4592. // to leave the check here for future usage if other clip planes are added.)
  4593. return false;
  4594. } else {
  4595. // Update the s1 and s2 vertices to match the clipped line segment.
  4596. s1.lerp( s2, alpha1 );
  4597. s2.lerp( s1, 1 - alpha2 );
  4598. return true;
  4599. }
  4600. }
  4601. }
  4602. };
  4603. /**
  4604. * @author mrdoob / http://mrdoob.com/
  4605. * @author alteredq / http://alteredqualia.com/
  4606. */
  4607. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4608. this.a = a;
  4609. this.b = b;
  4610. this.c = c;
  4611. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4612. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4613. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4614. this.vertexColors = color instanceof Array ? color : [];
  4615. this.vertexTangents = [];
  4616. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4617. this.centroid = new THREE.Vector3();
  4618. };
  4619. THREE.Face3.prototype = {
  4620. constructor: THREE.Face3,
  4621. clone: function () {
  4622. var face = new THREE.Face3( this.a, this.b, this.c );
  4623. face.normal.copy( this.normal );
  4624. face.color.copy( this.color );
  4625. face.centroid.copy( this.centroid );
  4626. face.materialIndex = this.materialIndex;
  4627. var i, il;
  4628. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4629. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4630. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4631. return face;
  4632. }
  4633. };
  4634. /**
  4635. * @author mrdoob / http://mrdoob.com/
  4636. * @author alteredq / http://alteredqualia.com/
  4637. */
  4638. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4639. this.a = a;
  4640. this.b = b;
  4641. this.c = c;
  4642. this.d = d;
  4643. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4644. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4645. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4646. this.vertexColors = color instanceof Array ? color : [];
  4647. this.vertexTangents = [];
  4648. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4649. this.centroid = new THREE.Vector3();
  4650. };
  4651. THREE.Face4.prototype = {
  4652. constructor: THREE.Face4,
  4653. clone: function () {
  4654. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4655. face.normal.copy( this.normal );
  4656. face.color.copy( this.color );
  4657. face.centroid.copy( this.centroid );
  4658. face.materialIndex = this.materialIndex;
  4659. var i, il;
  4660. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4661. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4662. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4663. return face;
  4664. }
  4665. };
  4666. /**
  4667. * @author mrdoob / http://mrdoob.com/
  4668. * @author kile / http://kile.stravaganza.org/
  4669. * @author alteredq / http://alteredqualia.com/
  4670. * @author mikael emtinger / http://gomo.se/
  4671. * @author zz85 / http://www.lab4games.net/zz85/blog
  4672. * @author bhouston / http://exocortex.com
  4673. */
  4674. THREE.Geometry = function () {
  4675. this.id = THREE.Math.generateUUID();
  4676. this.name = '';
  4677. this.vertices = [];
  4678. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4679. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4680. this.faces = [];
  4681. this.faceUvs = [[]];
  4682. this.faceVertexUvs = [[]];
  4683. this.morphTargets = [];
  4684. this.morphColors = [];
  4685. this.morphNormals = [];
  4686. this.skinWeights = [];
  4687. this.skinIndices = [];
  4688. this.lineDistances = [];
  4689. this.boundingBox = null;
  4690. this.boundingSphere = null;
  4691. this.hasTangents = false;
  4692. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4693. // update flags
  4694. this.verticesNeedUpdate = false;
  4695. this.elementsNeedUpdate = false;
  4696. this.uvsNeedUpdate = false;
  4697. this.normalsNeedUpdate = false;
  4698. this.tangentsNeedUpdate = false;
  4699. this.colorsNeedUpdate = false;
  4700. this.lineDistancesNeedUpdate = false;
  4701. this.buffersNeedUpdate = false;
  4702. };
  4703. THREE.Geometry.prototype = {
  4704. constructor: THREE.Geometry,
  4705. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4706. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4707. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4708. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4709. applyMatrix: function ( matrix ) {
  4710. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4711. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4712. var vertex = this.vertices[ i ];
  4713. vertex.applyMatrix4( matrix );
  4714. }
  4715. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4716. var face = this.faces[ i ];
  4717. face.normal.applyMatrix3( normalMatrix ).normalize();
  4718. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4719. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4720. }
  4721. face.centroid.applyMatrix4( matrix );
  4722. }
  4723. if ( this.boundingBox instanceof THREE.Box3 ) {
  4724. this.computeBoundingBox();
  4725. }
  4726. if ( this.boundingSphere instanceof THREE.Sphere ) {
  4727. this.computeBoundingSphere();
  4728. }
  4729. },
  4730. computeCentroids: function () {
  4731. var f, fl, face;
  4732. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4733. face = this.faces[ f ];
  4734. face.centroid.set( 0, 0, 0 );
  4735. if ( face instanceof THREE.Face3 ) {
  4736. face.centroid.add( this.vertices[ face.a ] );
  4737. face.centroid.add( this.vertices[ face.b ] );
  4738. face.centroid.add( this.vertices[ face.c ] );
  4739. face.centroid.divideScalar( 3 );
  4740. } else if ( face instanceof THREE.Face4 ) {
  4741. face.centroid.add( this.vertices[ face.a ] );
  4742. face.centroid.add( this.vertices[ face.b ] );
  4743. face.centroid.add( this.vertices[ face.c ] );
  4744. face.centroid.add( this.vertices[ face.d ] );
  4745. face.centroid.divideScalar( 4 );
  4746. }
  4747. }
  4748. },
  4749. computeFaceNormals: function () {
  4750. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4751. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4752. var face = this.faces[ f ];
  4753. var vA = this.vertices[ face.a ];
  4754. var vB = this.vertices[ face.b ];
  4755. var vC = this.vertices[ face.c ];
  4756. cb.subVectors( vC, vB );
  4757. ab.subVectors( vA, vB );
  4758. cb.cross( ab );
  4759. cb.normalize();
  4760. face.normal.copy( cb );
  4761. }
  4762. },
  4763. computeVertexNormals: function ( areaWeighted ) {
  4764. var v, vl, f, fl, face, vertices;
  4765. // create internal buffers for reuse when calling this method repeatedly
  4766. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4767. if ( this.__tmpVertices === undefined ) {
  4768. this.__tmpVertices = new Array( this.vertices.length );
  4769. vertices = this.__tmpVertices;
  4770. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4771. vertices[ v ] = new THREE.Vector3();
  4772. }
  4773. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4774. face = this.faces[ f ];
  4775. if ( face instanceof THREE.Face3 ) {
  4776. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4777. } else if ( face instanceof THREE.Face4 ) {
  4778. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4779. }
  4780. }
  4781. } else {
  4782. vertices = this.__tmpVertices;
  4783. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4784. vertices[ v ].set( 0, 0, 0 );
  4785. }
  4786. }
  4787. if ( areaWeighted ) {
  4788. // vertex normals weighted by triangle areas
  4789. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4790. var vA, vB, vC, vD;
  4791. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4792. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4793. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4794. face = this.faces[ f ];
  4795. if ( face instanceof THREE.Face3 ) {
  4796. vA = this.vertices[ face.a ];
  4797. vB = this.vertices[ face.b ];
  4798. vC = this.vertices[ face.c ];
  4799. cb.subVectors( vC, vB );
  4800. ab.subVectors( vA, vB );
  4801. cb.cross( ab );
  4802. vertices[ face.a ].add( cb );
  4803. vertices[ face.b ].add( cb );
  4804. vertices[ face.c ].add( cb );
  4805. } else if ( face instanceof THREE.Face4 ) {
  4806. vA = this.vertices[ face.a ];
  4807. vB = this.vertices[ face.b ];
  4808. vC = this.vertices[ face.c ];
  4809. vD = this.vertices[ face.d ];
  4810. // abd
  4811. db.subVectors( vD, vB );
  4812. ab.subVectors( vA, vB );
  4813. db.cross( ab );
  4814. vertices[ face.a ].add( db );
  4815. vertices[ face.b ].add( db );
  4816. vertices[ face.d ].add( db );
  4817. // bcd
  4818. dc.subVectors( vD, vC );
  4819. bc.subVectors( vB, vC );
  4820. dc.cross( bc );
  4821. vertices[ face.b ].add( dc );
  4822. vertices[ face.c ].add( dc );
  4823. vertices[ face.d ].add( dc );
  4824. }
  4825. }
  4826. } else {
  4827. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4828. face = this.faces[ f ];
  4829. if ( face instanceof THREE.Face3 ) {
  4830. vertices[ face.a ].add( face.normal );
  4831. vertices[ face.b ].add( face.normal );
  4832. vertices[ face.c ].add( face.normal );
  4833. } else if ( face instanceof THREE.Face4 ) {
  4834. vertices[ face.a ].add( face.normal );
  4835. vertices[ face.b ].add( face.normal );
  4836. vertices[ face.c ].add( face.normal );
  4837. vertices[ face.d ].add( face.normal );
  4838. }
  4839. }
  4840. }
  4841. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4842. vertices[ v ].normalize();
  4843. }
  4844. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4845. face = this.faces[ f ];
  4846. if ( face instanceof THREE.Face3 ) {
  4847. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4848. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4849. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4850. } else if ( face instanceof THREE.Face4 ) {
  4851. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4852. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4853. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4854. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4855. }
  4856. }
  4857. },
  4858. computeMorphNormals: function () {
  4859. var i, il, f, fl, face;
  4860. // save original normals
  4861. // - create temp variables on first access
  4862. // otherwise just copy (for faster repeated calls)
  4863. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4864. face = this.faces[ f ];
  4865. if ( ! face.__originalFaceNormal ) {
  4866. face.__originalFaceNormal = face.normal.clone();
  4867. } else {
  4868. face.__originalFaceNormal.copy( face.normal );
  4869. }
  4870. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4871. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4872. if ( ! face.__originalVertexNormals[ i ] ) {
  4873. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4874. } else {
  4875. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4876. }
  4877. }
  4878. }
  4879. // use temp geometry to compute face and vertex normals for each morph
  4880. var tmpGeo = new THREE.Geometry();
  4881. tmpGeo.faces = this.faces;
  4882. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4883. // create on first access
  4884. if ( ! this.morphNormals[ i ] ) {
  4885. this.morphNormals[ i ] = {};
  4886. this.morphNormals[ i ].faceNormals = [];
  4887. this.morphNormals[ i ].vertexNormals = [];
  4888. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4889. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4890. var faceNormal, vertexNormals;
  4891. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4892. face = this.faces[ f ];
  4893. faceNormal = new THREE.Vector3();
  4894. if ( face instanceof THREE.Face3 ) {
  4895. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4896. } else {
  4897. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4898. }
  4899. dstNormalsFace.push( faceNormal );
  4900. dstNormalsVertex.push( vertexNormals );
  4901. }
  4902. }
  4903. var morphNormals = this.morphNormals[ i ];
  4904. // set vertices to morph target
  4905. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4906. // compute morph normals
  4907. tmpGeo.computeFaceNormals();
  4908. tmpGeo.computeVertexNormals();
  4909. // store morph normals
  4910. var faceNormal, vertexNormals;
  4911. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4912. face = this.faces[ f ];
  4913. faceNormal = morphNormals.faceNormals[ f ];
  4914. vertexNormals = morphNormals.vertexNormals[ f ];
  4915. faceNormal.copy( face.normal );
  4916. if ( face instanceof THREE.Face3 ) {
  4917. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4918. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4919. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4920. } else {
  4921. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4922. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4923. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4924. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4925. }
  4926. }
  4927. }
  4928. // restore original normals
  4929. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4930. face = this.faces[ f ];
  4931. face.normal = face.__originalFaceNormal;
  4932. face.vertexNormals = face.__originalVertexNormals;
  4933. }
  4934. },
  4935. computeTangents: function () {
  4936. // based on http://www.terathon.com/code/tangent.html
  4937. // tangents go to vertices
  4938. var f, fl, v, vl, i, il, vertexIndex,
  4939. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4940. x1, x2, y1, y2, z1, z2,
  4941. s1, s2, t1, t2, r, t, test,
  4942. tan1 = [], tan2 = [],
  4943. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4944. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4945. n = new THREE.Vector3(), w;
  4946. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4947. tan1[ v ] = new THREE.Vector3();
  4948. tan2[ v ] = new THREE.Vector3();
  4949. }
  4950. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4951. vA = context.vertices[ a ];
  4952. vB = context.vertices[ b ];
  4953. vC = context.vertices[ c ];
  4954. uvA = uv[ ua ];
  4955. uvB = uv[ ub ];
  4956. uvC = uv[ uc ];
  4957. x1 = vB.x - vA.x;
  4958. x2 = vC.x - vA.x;
  4959. y1 = vB.y - vA.y;
  4960. y2 = vC.y - vA.y;
  4961. z1 = vB.z - vA.z;
  4962. z2 = vC.z - vA.z;
  4963. s1 = uvB.x - uvA.x;
  4964. s2 = uvC.x - uvA.x;
  4965. t1 = uvB.y - uvA.y;
  4966. t2 = uvC.y - uvA.y;
  4967. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4968. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4969. ( t2 * y1 - t1 * y2 ) * r,
  4970. ( t2 * z1 - t1 * z2 ) * r );
  4971. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4972. ( s1 * y2 - s2 * y1 ) * r,
  4973. ( s1 * z2 - s2 * z1 ) * r );
  4974. tan1[ a ].add( sdir );
  4975. tan1[ b ].add( sdir );
  4976. tan1[ c ].add( sdir );
  4977. tan2[ a ].add( tdir );
  4978. tan2[ b ].add( tdir );
  4979. tan2[ c ].add( tdir );
  4980. }
  4981. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4982. face = this.faces[ f ];
  4983. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4984. if ( face instanceof THREE.Face3 ) {
  4985. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4986. } else if ( face instanceof THREE.Face4 ) {
  4987. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4988. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4989. }
  4990. }
  4991. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4992. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4993. face = this.faces[ f ];
  4994. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4995. n.copy( face.vertexNormals[ i ] );
  4996. vertexIndex = face[ faceIndex[ i ] ];
  4997. t = tan1[ vertexIndex ];
  4998. // Gram-Schmidt orthogonalize
  4999. tmp.copy( t );
  5000. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5001. // Calculate handedness
  5002. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5003. test = tmp2.dot( tan2[ vertexIndex ] );
  5004. w = (test < 0.0) ? -1.0 : 1.0;
  5005. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5006. }
  5007. }
  5008. this.hasTangents = true;
  5009. },
  5010. computeLineDistances: function ( ) {
  5011. var d = 0;
  5012. var vertices = this.vertices;
  5013. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5014. if ( i > 0 ) {
  5015. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5016. }
  5017. this.lineDistances[ i ] = d;
  5018. }
  5019. },
  5020. computeBoundingBox: function () {
  5021. if ( this.boundingBox === null ) {
  5022. this.boundingBox = new THREE.Box3();
  5023. }
  5024. this.boundingBox.setFromPoints( this.vertices );
  5025. },
  5026. computeBoundingSphere: function () {
  5027. if ( this.boundingSphere === null ) {
  5028. this.boundingSphere = new THREE.Sphere();
  5029. }
  5030. this.boundingSphere.setFromPoints( this.vertices );
  5031. },
  5032. /*
  5033. * Checks for duplicate vertices with hashmap.
  5034. * Duplicated vertices are removed
  5035. * and faces' vertices are updated.
  5036. */
  5037. mergeVertices: function () {
  5038. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5039. var unique = [], changes = [];
  5040. var v, key;
  5041. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5042. var precision = Math.pow( 10, precisionPoints );
  5043. var i,il, face;
  5044. var indices, k, j, jl, u;
  5045. // reset cache of vertices as it now will be changing.
  5046. this.__tmpVertices = undefined;
  5047. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5048. v = this.vertices[ i ];
  5049. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5050. if ( verticesMap[ key ] === undefined ) {
  5051. verticesMap[ key ] = i;
  5052. unique.push( this.vertices[ i ] );
  5053. changes[ i ] = unique.length - 1;
  5054. } else {
  5055. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5056. changes[ i ] = changes[ verticesMap[ key ] ];
  5057. }
  5058. };
  5059. // if faces are completely degenerate after merging vertices, we
  5060. // have to remove them from the geometry.
  5061. var faceIndicesToRemove = [];
  5062. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5063. face = this.faces[ i ];
  5064. if ( face instanceof THREE.Face3 ) {
  5065. face.a = changes[ face.a ];
  5066. face.b = changes[ face.b ];
  5067. face.c = changes[ face.c ];
  5068. indices = [ face.a, face.b, face.c ];
  5069. var dupIndex = -1;
  5070. // if any duplicate vertices are found in a Face3
  5071. // we have to remove the face as nothing can be saved
  5072. for ( var n = 0; n < 3; n ++ ) {
  5073. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5074. dupIndex = n;
  5075. faceIndicesToRemove.push( i );
  5076. break;
  5077. }
  5078. }
  5079. } else if ( face instanceof THREE.Face4 ) {
  5080. face.a = changes[ face.a ];
  5081. face.b = changes[ face.b ];
  5082. face.c = changes[ face.c ];
  5083. face.d = changes[ face.d ];
  5084. // check dups in (a, b, c, d) and convert to -> face3
  5085. indices = [ face.a, face.b, face.c, face.d ];
  5086. var dupIndex = -1;
  5087. for ( var n = 0; n < 4; n ++ ) {
  5088. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  5089. // if more than one duplicated vertex is found
  5090. // we can't generate any valid Face3's, thus
  5091. // we need to remove this face complete.
  5092. if ( dupIndex >= 0 ) {
  5093. faceIndicesToRemove.push( i );
  5094. }
  5095. dupIndex = n;
  5096. }
  5097. }
  5098. if ( dupIndex >= 0 ) {
  5099. indices.splice( dupIndex, 1 );
  5100. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  5101. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5102. u = this.faceVertexUvs[ j ][ i ];
  5103. if ( u ) {
  5104. u.splice( dupIndex, 1 );
  5105. }
  5106. }
  5107. if( face.vertexNormals && face.vertexNormals.length > 0) {
  5108. newFace.vertexNormals = face.vertexNormals;
  5109. newFace.vertexNormals.splice( dupIndex, 1 );
  5110. }
  5111. if( face.vertexColors && face.vertexColors.length > 0 ) {
  5112. newFace.vertexColors = face.vertexColors;
  5113. newFace.vertexColors.splice( dupIndex, 1 );
  5114. }
  5115. this.faces[ i ] = newFace;
  5116. }
  5117. }
  5118. }
  5119. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5120. this.faces.splice( i, 1 );
  5121. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5122. this.faceVertexUvs[ j ].splice( i, 1 );
  5123. }
  5124. }
  5125. // Use unique set of vertices
  5126. var diff = this.vertices.length - unique.length;
  5127. this.vertices = unique;
  5128. return diff;
  5129. },
  5130. clone: function () {
  5131. var geometry = new THREE.Geometry();
  5132. var vertices = this.vertices;
  5133. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5134. geometry.vertices.push( vertices[ i ].clone() );
  5135. }
  5136. var faces = this.faces;
  5137. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5138. geometry.faces.push( faces[ i ].clone() );
  5139. }
  5140. var uvs = this.faceVertexUvs[ 0 ];
  5141. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5142. var uv = uvs[ i ], uvCopy = [];
  5143. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5144. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5145. }
  5146. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5147. }
  5148. return geometry;
  5149. },
  5150. dispose: function () {
  5151. this.dispatchEvent( { type: 'dispose' } );
  5152. }
  5153. };
  5154. /**
  5155. * @author alteredq / http://alteredqualia.com/
  5156. */
  5157. THREE.BufferGeometry = function () {
  5158. this.id = THREE.Math.generateUUID();
  5159. // attributes
  5160. this.attributes = {};
  5161. // attributes typed arrays are kept only if dynamic flag is set
  5162. this.dynamic = false;
  5163. // offsets for chunks when using indexed elements
  5164. this.offsets = [];
  5165. // boundings
  5166. this.boundingBox = null;
  5167. this.boundingSphere = null;
  5168. this.hasTangents = false;
  5169. // for compatibility
  5170. this.morphTargets = [];
  5171. };
  5172. THREE.BufferGeometry.prototype = {
  5173. constructor: THREE.BufferGeometry,
  5174. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  5175. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  5176. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  5177. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  5178. applyMatrix: function ( matrix ) {
  5179. var positionArray;
  5180. var normalArray;
  5181. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5182. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5183. if ( positionArray !== undefined ) {
  5184. matrix.multiplyVector3Array( positionArray );
  5185. this.verticesNeedUpdate = true;
  5186. }
  5187. if ( normalArray !== undefined ) {
  5188. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5189. normalMatrix.multiplyVector3Array( normalArray );
  5190. this.normalizeNormals();
  5191. this.normalsNeedUpdate = true;
  5192. }
  5193. },
  5194. computeBoundingBox: function () {
  5195. if ( this.boundingBox === null ) {
  5196. this.boundingBox = new THREE.Box3();
  5197. }
  5198. var positions = this.attributes[ "position" ].array;
  5199. if ( positions ) {
  5200. var bb = this.boundingBox;
  5201. var x, y, z;
  5202. if( positions.length >= 3 ) {
  5203. bb.min.x = bb.max.x = positions[ 0 ];
  5204. bb.min.y = bb.max.y = positions[ 1 ];
  5205. bb.min.z = bb.max.z = positions[ 2 ];
  5206. }
  5207. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5208. x = positions[ i ];
  5209. y = positions[ i + 1 ];
  5210. z = positions[ i + 2 ];
  5211. // bounding box
  5212. if ( x < bb.min.x ) {
  5213. bb.min.x = x;
  5214. } else if ( x > bb.max.x ) {
  5215. bb.max.x = x;
  5216. }
  5217. if ( y < bb.min.y ) {
  5218. bb.min.y = y;
  5219. } else if ( y > bb.max.y ) {
  5220. bb.max.y = y;
  5221. }
  5222. if ( z < bb.min.z ) {
  5223. bb.min.z = z;
  5224. } else if ( z > bb.max.z ) {
  5225. bb.max.z = z;
  5226. }
  5227. }
  5228. }
  5229. if ( positions === undefined || positions.length === 0 ) {
  5230. this.boundingBox.min.set( 0, 0, 0 );
  5231. this.boundingBox.max.set( 0, 0, 0 );
  5232. }
  5233. },
  5234. computeBoundingSphere: function () {
  5235. if ( this.boundingSphere === null ) {
  5236. this.boundingSphere = new THREE.Sphere();
  5237. }
  5238. var positions = this.attributes[ "position" ].array;
  5239. if ( positions ) {
  5240. var radiusSq, maxRadiusSq = 0;
  5241. var x, y, z;
  5242. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5243. x = positions[ i ];
  5244. y = positions[ i + 1 ];
  5245. z = positions[ i + 2 ];
  5246. radiusSq = x * x + y * y + z * z;
  5247. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  5248. }
  5249. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5250. }
  5251. },
  5252. computeVertexNormals: function () {
  5253. if ( this.attributes[ "position" ] ) {
  5254. var i, il;
  5255. var j, jl;
  5256. var nVertexElements = this.attributes[ "position" ].array.length;
  5257. if ( this.attributes[ "normal" ] === undefined ) {
  5258. this.attributes[ "normal" ] = {
  5259. itemSize: 3,
  5260. array: new Float32Array( nVertexElements )
  5261. };
  5262. } else {
  5263. // reset existing normals to zero
  5264. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5265. this.attributes[ "normal" ].array[ i ] = 0;
  5266. }
  5267. }
  5268. var positions = this.attributes[ "position" ].array;
  5269. var normals = this.attributes[ "normal" ].array;
  5270. var vA, vB, vC, x, y, z,
  5271. pA = new THREE.Vector3(),
  5272. pB = new THREE.Vector3(),
  5273. pC = new THREE.Vector3(),
  5274. cb = new THREE.Vector3(),
  5275. ab = new THREE.Vector3();
  5276. // indexed elements
  5277. if ( this.attributes[ "index" ] ) {
  5278. var indices = this.attributes[ "index" ].array;
  5279. var offsets = this.offsets;
  5280. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5281. var start = offsets[ j ].start;
  5282. var count = offsets[ j ].count;
  5283. var index = offsets[ j ].index;
  5284. for ( i = start, il = start + count; i < il; i += 3 ) {
  5285. vA = index + indices[ i ];
  5286. vB = index + indices[ i + 1 ];
  5287. vC = index + indices[ i + 2 ];
  5288. x = positions[ vA * 3 ];
  5289. y = positions[ vA * 3 + 1 ];
  5290. z = positions[ vA * 3 + 2 ];
  5291. pA.set( x, y, z );
  5292. x = positions[ vB * 3 ];
  5293. y = positions[ vB * 3 + 1 ];
  5294. z = positions[ vB * 3 + 2 ];
  5295. pB.set( x, y, z );
  5296. x = positions[ vC * 3 ];
  5297. y = positions[ vC * 3 + 1 ];
  5298. z = positions[ vC * 3 + 2 ];
  5299. pC.set( x, y, z );
  5300. cb.subVectors( pC, pB );
  5301. ab.subVectors( pA, pB );
  5302. cb.cross( ab );
  5303. normals[ vA * 3 ] += cb.x;
  5304. normals[ vA * 3 + 1 ] += cb.y;
  5305. normals[ vA * 3 + 2 ] += cb.z;
  5306. normals[ vB * 3 ] += cb.x;
  5307. normals[ vB * 3 + 1 ] += cb.y;
  5308. normals[ vB * 3 + 2 ] += cb.z;
  5309. normals[ vC * 3 ] += cb.x;
  5310. normals[ vC * 3 + 1 ] += cb.y;
  5311. normals[ vC * 3 + 2 ] += cb.z;
  5312. }
  5313. }
  5314. // non-indexed elements (unconnected triangle soup)
  5315. } else {
  5316. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5317. x = positions[ i ];
  5318. y = positions[ i + 1 ];
  5319. z = positions[ i + 2 ];
  5320. pA.set( x, y, z );
  5321. x = positions[ i + 3 ];
  5322. y = positions[ i + 4 ];
  5323. z = positions[ i + 5 ];
  5324. pB.set( x, y, z );
  5325. x = positions[ i + 6 ];
  5326. y = positions[ i + 7 ];
  5327. z = positions[ i + 8 ];
  5328. pC.set( x, y, z );
  5329. cb.subVectors( pC, pB );
  5330. ab.subVectors( pA, pB );
  5331. cb.cross( ab );
  5332. normals[ i ] = cb.x;
  5333. normals[ i + 1 ] = cb.y;
  5334. normals[ i + 2 ] = cb.z;
  5335. normals[ i + 3 ] = cb.x;
  5336. normals[ i + 4 ] = cb.y;
  5337. normals[ i + 5 ] = cb.z;
  5338. normals[ i + 6 ] = cb.x;
  5339. normals[ i + 7 ] = cb.y;
  5340. normals[ i + 8 ] = cb.z;
  5341. }
  5342. }
  5343. this.normalizeNormals();
  5344. this.normalsNeedUpdate = true;
  5345. }
  5346. },
  5347. normalizeNormals: function () {
  5348. var normals = this.attributes[ "normal" ].array;
  5349. var x, y, z, n;
  5350. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5351. x = normals[ i ];
  5352. y = normals[ i + 1 ];
  5353. z = normals[ i + 2 ];
  5354. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5355. normals[ i ] *= n;
  5356. normals[ i + 1 ] *= n;
  5357. normals[ i + 2 ] *= n;
  5358. }
  5359. },
  5360. computeTangents: function () {
  5361. // based on http://www.terathon.com/code/tangent.html
  5362. // (per vertex tangents)
  5363. if ( this.attributes[ "index" ] === undefined ||
  5364. this.attributes[ "position" ] === undefined ||
  5365. this.attributes[ "normal" ] === undefined ||
  5366. this.attributes[ "uv" ] === undefined ) {
  5367. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5368. return;
  5369. }
  5370. var indices = this.attributes[ "index" ].array;
  5371. var positions = this.attributes[ "position" ].array;
  5372. var normals = this.attributes[ "normal" ].array;
  5373. var uvs = this.attributes[ "uv" ].array;
  5374. var nVertices = positions.length / 3;
  5375. if ( this.attributes[ "tangent" ] === undefined ) {
  5376. var nTangentElements = 4 * nVertices;
  5377. this.attributes[ "tangent" ] = {
  5378. itemSize: 4,
  5379. array: new Float32Array( nTangentElements )
  5380. };
  5381. }
  5382. var tangents = this.attributes[ "tangent" ].array;
  5383. var tan1 = [], tan2 = [];
  5384. for ( var k = 0; k < nVertices; k ++ ) {
  5385. tan1[ k ] = new THREE.Vector3();
  5386. tan2[ k ] = new THREE.Vector3();
  5387. }
  5388. var xA, yA, zA,
  5389. xB, yB, zB,
  5390. xC, yC, zC,
  5391. uA, vA,
  5392. uB, vB,
  5393. uC, vC,
  5394. x1, x2, y1, y2, z1, z2,
  5395. s1, s2, t1, t2, r;
  5396. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5397. function handleTriangle( a, b, c ) {
  5398. xA = positions[ a * 3 ];
  5399. yA = positions[ a * 3 + 1 ];
  5400. zA = positions[ a * 3 + 2 ];
  5401. xB = positions[ b * 3 ];
  5402. yB = positions[ b * 3 + 1 ];
  5403. zB = positions[ b * 3 + 2 ];
  5404. xC = positions[ c * 3 ];
  5405. yC = positions[ c * 3 + 1 ];
  5406. zC = positions[ c * 3 + 2 ];
  5407. uA = uvs[ a * 2 ];
  5408. vA = uvs[ a * 2 + 1 ];
  5409. uB = uvs[ b * 2 ];
  5410. vB = uvs[ b * 2 + 1 ];
  5411. uC = uvs[ c * 2 ];
  5412. vC = uvs[ c * 2 + 1 ];
  5413. x1 = xB - xA;
  5414. x2 = xC - xA;
  5415. y1 = yB - yA;
  5416. y2 = yC - yA;
  5417. z1 = zB - zA;
  5418. z2 = zC - zA;
  5419. s1 = uB - uA;
  5420. s2 = uC - uA;
  5421. t1 = vB - vA;
  5422. t2 = vC - vA;
  5423. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5424. sdir.set(
  5425. ( t2 * x1 - t1 * x2 ) * r,
  5426. ( t2 * y1 - t1 * y2 ) * r,
  5427. ( t2 * z1 - t1 * z2 ) * r
  5428. );
  5429. tdir.set(
  5430. ( s1 * x2 - s2 * x1 ) * r,
  5431. ( s1 * y2 - s2 * y1 ) * r,
  5432. ( s1 * z2 - s2 * z1 ) * r
  5433. );
  5434. tan1[ a ].add( sdir );
  5435. tan1[ b ].add( sdir );
  5436. tan1[ c ].add( sdir );
  5437. tan2[ a ].add( tdir );
  5438. tan2[ b ].add( tdir );
  5439. tan2[ c ].add( tdir );
  5440. }
  5441. var i, il;
  5442. var j, jl;
  5443. var iA, iB, iC;
  5444. var offsets = this.offsets;
  5445. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5446. var start = offsets[ j ].start;
  5447. var count = offsets[ j ].count;
  5448. var index = offsets[ j ].index;
  5449. for ( i = start, il = start + count; i < il; i += 3 ) {
  5450. iA = index + indices[ i ];
  5451. iB = index + indices[ i + 1 ];
  5452. iC = index + indices[ i + 2 ];
  5453. handleTriangle( iA, iB, iC );
  5454. }
  5455. }
  5456. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5457. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5458. var w, t, test;
  5459. function handleVertex( v ) {
  5460. n.x = normals[ v * 3 ];
  5461. n.y = normals[ v * 3 + 1 ];
  5462. n.z = normals[ v * 3 + 2 ];
  5463. n2.copy( n );
  5464. t = tan1[ v ];
  5465. // Gram-Schmidt orthogonalize
  5466. tmp.copy( t );
  5467. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5468. // Calculate handedness
  5469. tmp2.crossVectors( n2, t );
  5470. test = tmp2.dot( tan2[ v ] );
  5471. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5472. tangents[ v * 4 ] = tmp.x;
  5473. tangents[ v * 4 + 1 ] = tmp.y;
  5474. tangents[ v * 4 + 2 ] = tmp.z;
  5475. tangents[ v * 4 + 3 ] = w;
  5476. }
  5477. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5478. var start = offsets[ j ].start;
  5479. var count = offsets[ j ].count;
  5480. var index = offsets[ j ].index;
  5481. for ( i = start, il = start + count; i < il; i += 3 ) {
  5482. iA = index + indices[ i ];
  5483. iB = index + indices[ i + 1 ];
  5484. iC = index + indices[ i + 2 ];
  5485. handleVertex( iA );
  5486. handleVertex( iB );
  5487. handleVertex( iC );
  5488. }
  5489. }
  5490. this.hasTangents = true;
  5491. this.tangentsNeedUpdate = true;
  5492. },
  5493. dispose: function () {
  5494. this.dispatchEvent( { type: 'dispose' } );
  5495. }
  5496. };
  5497. /**
  5498. * @author mrdoob / http://mrdoob.com/
  5499. * @author mikael emtinger / http://gomo.se/
  5500. * @author WestLangley / http://github.com/WestLangley
  5501. */
  5502. THREE.Camera = function () {
  5503. THREE.Object3D.call( this );
  5504. this.matrixWorldInverse = new THREE.Matrix4();
  5505. this.projectionMatrix = new THREE.Matrix4();
  5506. this.projectionMatrixInverse = new THREE.Matrix4();
  5507. };
  5508. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5509. THREE.Camera.prototype.lookAt = function () {
  5510. // This routine does not support cameras with rotated and/or translated parent(s)
  5511. var m1 = new THREE.Matrix4();
  5512. return function ( vector ) {
  5513. m1.lookAt( this.position, vector, this.up );
  5514. this.quaternion.setFromRotationMatrix( m1 );
  5515. };
  5516. }();
  5517. /**
  5518. * @author alteredq / http://alteredqualia.com/
  5519. */
  5520. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5521. THREE.Camera.call( this );
  5522. this.left = left;
  5523. this.right = right;
  5524. this.top = top;
  5525. this.bottom = bottom;
  5526. this.near = ( near !== undefined ) ? near : 0.1;
  5527. this.far = ( far !== undefined ) ? far : 2000;
  5528. this.updateProjectionMatrix();
  5529. };
  5530. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5531. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5532. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5533. };
  5534. /**
  5535. * @author mrdoob / http://mrdoob.com/
  5536. * @author greggman / http://games.greggman.com/
  5537. * @author zz85 / http://www.lab4games.net/zz85/blog
  5538. */
  5539. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5540. THREE.Camera.call( this );
  5541. this.fov = fov !== undefined ? fov : 50;
  5542. this.aspect = aspect !== undefined ? aspect : 1;
  5543. this.near = near !== undefined ? near : 0.1;
  5544. this.far = far !== undefined ? far : 2000;
  5545. this.updateProjectionMatrix();
  5546. };
  5547. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5548. /**
  5549. * Uses Focal Length (in mm) to estimate and set FOV
  5550. * 35mm (fullframe) camera is used if frame size is not specified;
  5551. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5552. */
  5553. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5554. if ( frameHeight === undefined ) frameHeight = 24;
  5555. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5556. this.updateProjectionMatrix();
  5557. }
  5558. /**
  5559. * Sets an offset in a larger frustum. This is useful for multi-window or
  5560. * multi-monitor/multi-machine setups.
  5561. *
  5562. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5563. * the monitors are in grid like this
  5564. *
  5565. * +---+---+---+
  5566. * | A | B | C |
  5567. * +---+---+---+
  5568. * | D | E | F |
  5569. * +---+---+---+
  5570. *
  5571. * then for each monitor you would call it like this
  5572. *
  5573. * var w = 1920;
  5574. * var h = 1080;
  5575. * var fullWidth = w * 3;
  5576. * var fullHeight = h * 2;
  5577. *
  5578. * --A--
  5579. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5580. * --B--
  5581. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5582. * --C--
  5583. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5584. * --D--
  5585. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5586. * --E--
  5587. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5588. * --F--
  5589. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5590. *
  5591. * Note there is no reason monitors have to be the same size or in a grid.
  5592. */
  5593. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5594. this.fullWidth = fullWidth;
  5595. this.fullHeight = fullHeight;
  5596. this.x = x;
  5597. this.y = y;
  5598. this.width = width;
  5599. this.height = height;
  5600. this.updateProjectionMatrix();
  5601. };
  5602. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5603. if ( this.fullWidth ) {
  5604. var aspect = this.fullWidth / this.fullHeight;
  5605. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5606. var bottom = -top;
  5607. var left = aspect * bottom;
  5608. var right = aspect * top;
  5609. var width = Math.abs( right - left );
  5610. var height = Math.abs( top - bottom );
  5611. this.projectionMatrix.makeFrustum(
  5612. left + this.x * width / this.fullWidth,
  5613. left + ( this.x + this.width ) * width / this.fullWidth,
  5614. top - ( this.y + this.height ) * height / this.fullHeight,
  5615. top - this.y * height / this.fullHeight,
  5616. this.near,
  5617. this.far
  5618. );
  5619. } else {
  5620. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5621. }
  5622. };
  5623. /**
  5624. * @author mrdoob / http://mrdoob.com/
  5625. * @author alteredq / http://alteredqualia.com/
  5626. */
  5627. THREE.Light = function ( hex ) {
  5628. THREE.Object3D.call( this );
  5629. this.color = new THREE.Color( hex );
  5630. };
  5631. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5632. THREE.Light.prototype.clone = function ( light ) {
  5633. if ( light === undefined ) light = new THREE.Light();
  5634. THREE.Object3D.prototype.clone.call( this, light );
  5635. light.color.copy( this.color );
  5636. return light;
  5637. };
  5638. /**
  5639. * @author mrdoob / http://mrdoob.com/
  5640. */
  5641. THREE.AmbientLight = function ( hex ) {
  5642. THREE.Light.call( this, hex );
  5643. };
  5644. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5645. THREE.AmbientLight.prototype.clone = function () {
  5646. var light = new THREE.AmbientLight();
  5647. THREE.Light.prototype.clone.call( this, light );
  5648. return light;
  5649. };
  5650. /**
  5651. * @author MPanknin / http://www.redplant.de/
  5652. * @author alteredq / http://alteredqualia.com/
  5653. */
  5654. THREE.AreaLight = function ( hex, intensity ) {
  5655. THREE.Light.call( this, hex );
  5656. this.normal = new THREE.Vector3( 0, -1, 0 );
  5657. this.right = new THREE.Vector3( 1, 0, 0 );
  5658. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5659. this.width = 1.0;
  5660. this.height = 1.0;
  5661. this.constantAttenuation = 1.5;
  5662. this.linearAttenuation = 0.5;
  5663. this.quadraticAttenuation = 0.1;
  5664. };
  5665. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5666. /**
  5667. * @author mrdoob / http://mrdoob.com/
  5668. * @author alteredq / http://alteredqualia.com/
  5669. */
  5670. THREE.DirectionalLight = function ( hex, intensity ) {
  5671. THREE.Light.call( this, hex );
  5672. this.position.set( 0, 1, 0 );
  5673. this.target = new THREE.Object3D();
  5674. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5675. this.castShadow = false;
  5676. this.onlyShadow = false;
  5677. //
  5678. this.shadowCameraNear = 50;
  5679. this.shadowCameraFar = 5000;
  5680. this.shadowCameraLeft = -500;
  5681. this.shadowCameraRight = 500;
  5682. this.shadowCameraTop = 500;
  5683. this.shadowCameraBottom = -500;
  5684. this.shadowCameraVisible = false;
  5685. this.shadowBias = 0;
  5686. this.shadowDarkness = 0.5;
  5687. this.shadowMapWidth = 512;
  5688. this.shadowMapHeight = 512;
  5689. //
  5690. this.shadowCascade = false;
  5691. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5692. this.shadowCascadeCount = 2;
  5693. this.shadowCascadeBias = [ 0, 0, 0 ];
  5694. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5695. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5696. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5697. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5698. this.shadowCascadeArray = [];
  5699. //
  5700. this.shadowMap = null;
  5701. this.shadowMapSize = null;
  5702. this.shadowCamera = null;
  5703. this.shadowMatrix = null;
  5704. };
  5705. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5706. THREE.DirectionalLight.prototype.clone = function () {
  5707. var light = new THREE.DirectionalLight();
  5708. THREE.Light.prototype.clone.call( this, light );
  5709. light.target = this.target.clone();
  5710. light.intensity = this.intensity;
  5711. light.castShadow = this.castShadow;
  5712. light.onlyShadow = this.onlyShadow;
  5713. return light;
  5714. };
  5715. /**
  5716. * @author alteredq / http://alteredqualia.com/
  5717. */
  5718. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5719. THREE.Light.call( this, skyColorHex );
  5720. this.position.set( 0, 100, 0 );
  5721. this.groundColor = new THREE.Color( groundColorHex );
  5722. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5723. };
  5724. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5725. THREE.HemisphereLight.prototype.clone = function () {
  5726. var light = new THREE.PointLight();
  5727. THREE.Light.prototype.clone.call( this, light );
  5728. light.groundColor.copy( this.groundColor );
  5729. light.intensity = this.intensity;
  5730. return light;
  5731. };
  5732. /**
  5733. * @author mrdoob / http://mrdoob.com/
  5734. */
  5735. THREE.PointLight = function ( hex, intensity, distance ) {
  5736. THREE.Light.call( this, hex );
  5737. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5738. this.distance = ( distance !== undefined ) ? distance : 0;
  5739. };
  5740. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5741. THREE.PointLight.prototype.clone = function () {
  5742. var light = new THREE.PointLight();
  5743. THREE.Light.prototype.clone.call( this, light );
  5744. light.intensity = this.intensity;
  5745. light.distance = this.distance;
  5746. return light;
  5747. };
  5748. /**
  5749. * @author alteredq / http://alteredqualia.com/
  5750. */
  5751. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5752. THREE.Light.call( this, hex );
  5753. this.position.set( 0, 1, 0 );
  5754. this.target = new THREE.Object3D();
  5755. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5756. this.distance = ( distance !== undefined ) ? distance : 0;
  5757. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5758. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5759. this.castShadow = false;
  5760. this.onlyShadow = false;
  5761. //
  5762. this.shadowCameraNear = 50;
  5763. this.shadowCameraFar = 5000;
  5764. this.shadowCameraFov = 50;
  5765. this.shadowCameraVisible = false;
  5766. this.shadowBias = 0;
  5767. this.shadowDarkness = 0.5;
  5768. this.shadowMapWidth = 512;
  5769. this.shadowMapHeight = 512;
  5770. //
  5771. this.shadowMap = null;
  5772. this.shadowMapSize = null;
  5773. this.shadowCamera = null;
  5774. this.shadowMatrix = null;
  5775. };
  5776. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5777. THREE.SpotLight.prototype.clone = function () {
  5778. var light = new THREE.SpotLight();
  5779. THREE.Light.prototype.clone.call( this, light );
  5780. light.target = this.target.clone();
  5781. light.intensity = this.intensity;
  5782. light.distance = this.distance;
  5783. light.angle = this.angle;
  5784. light.exponent = this.exponent;
  5785. light.castShadow = this.castShadow;
  5786. light.onlyShadow = this.onlyShadow;
  5787. return light;
  5788. };
  5789. /**
  5790. * @author alteredq / http://alteredqualia.com/
  5791. */
  5792. THREE.Loader = function ( showStatus ) {
  5793. this.showStatus = showStatus;
  5794. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5795. this.onLoadStart = function () {};
  5796. this.onLoadProgress = function () {};
  5797. this.onLoadComplete = function () {};
  5798. };
  5799. THREE.Loader.prototype = {
  5800. constructor: THREE.Loader,
  5801. crossOrigin: 'anonymous',
  5802. addStatusElement: function () {
  5803. var e = document.createElement( "div" );
  5804. e.style.position = "absolute";
  5805. e.style.right = "0px";
  5806. e.style.top = "0px";
  5807. e.style.fontSize = "0.8em";
  5808. e.style.textAlign = "left";
  5809. e.style.background = "rgba(0,0,0,0.25)";
  5810. e.style.color = "#fff";
  5811. e.style.width = "120px";
  5812. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5813. e.style.zIndex = 1000;
  5814. e.innerHTML = "Loading ...";
  5815. return e;
  5816. },
  5817. updateProgress: function ( progress ) {
  5818. var message = "Loaded ";
  5819. if ( progress.total ) {
  5820. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5821. } else {
  5822. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5823. }
  5824. this.statusDomElement.innerHTML = message;
  5825. },
  5826. extractUrlBase: function ( url ) {
  5827. var parts = url.split( '/' );
  5828. parts.pop();
  5829. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5830. },
  5831. initMaterials: function ( materials, texturePath ) {
  5832. var array = [];
  5833. for ( var i = 0; i < materials.length; ++ i ) {
  5834. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5835. }
  5836. return array;
  5837. },
  5838. needsTangents: function ( materials ) {
  5839. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5840. var m = materials[ i ];
  5841. if ( m instanceof THREE.ShaderMaterial ) return true;
  5842. }
  5843. return false;
  5844. },
  5845. createMaterial: function ( m, texturePath ) {
  5846. var _this = this;
  5847. function is_pow2( n ) {
  5848. var l = Math.log( n ) / Math.LN2;
  5849. return Math.floor( l ) == l;
  5850. }
  5851. function nearest_pow2( n ) {
  5852. var l = Math.log( n ) / Math.LN2;
  5853. return Math.pow( 2, Math.round( l ) );
  5854. }
  5855. function load_image( where, url ) {
  5856. var image = new Image();
  5857. image.onload = function () {
  5858. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5859. var width = nearest_pow2( this.width );
  5860. var height = nearest_pow2( this.height );
  5861. where.image.width = width;
  5862. where.image.height = height;
  5863. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5864. } else {
  5865. where.image = this;
  5866. }
  5867. where.needsUpdate = true;
  5868. };
  5869. image.crossOrigin = _this.crossOrigin;
  5870. image.src = url;
  5871. }
  5872. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5873. var isCompressed = /\.dds$/i.test( sourceFile );
  5874. var fullPath = texturePath + "/" + sourceFile;
  5875. if ( isCompressed ) {
  5876. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5877. where[ name ] = texture;
  5878. } else {
  5879. var texture = document.createElement( 'canvas' );
  5880. where[ name ] = new THREE.Texture( texture );
  5881. }
  5882. where[ name ].sourceFile = sourceFile;
  5883. if( repeat ) {
  5884. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5885. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5886. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5887. }
  5888. if ( offset ) {
  5889. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5890. }
  5891. if ( wrap ) {
  5892. var wrapMap = {
  5893. "repeat": THREE.RepeatWrapping,
  5894. "mirror": THREE.MirroredRepeatWrapping
  5895. }
  5896. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5897. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5898. }
  5899. if ( anisotropy ) {
  5900. where[ name ].anisotropy = anisotropy;
  5901. }
  5902. if ( ! isCompressed ) {
  5903. load_image( where[ name ], fullPath );
  5904. }
  5905. }
  5906. function rgb2hex( rgb ) {
  5907. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5908. }
  5909. // defaults
  5910. var mtype = "MeshLambertMaterial";
  5911. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5912. // parameters from model file
  5913. if ( m.shading ) {
  5914. var shading = m.shading.toLowerCase();
  5915. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5916. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5917. }
  5918. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5919. mpars.blending = THREE[ m.blending ];
  5920. }
  5921. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5922. mpars.transparent = m.transparent;
  5923. }
  5924. if ( m.depthTest !== undefined ) {
  5925. mpars.depthTest = m.depthTest;
  5926. }
  5927. if ( m.depthWrite !== undefined ) {
  5928. mpars.depthWrite = m.depthWrite;
  5929. }
  5930. if ( m.visible !== undefined ) {
  5931. mpars.visible = m.visible;
  5932. }
  5933. if ( m.flipSided !== undefined ) {
  5934. mpars.side = THREE.BackSide;
  5935. }
  5936. if ( m.doubleSided !== undefined ) {
  5937. mpars.side = THREE.DoubleSide;
  5938. }
  5939. if ( m.wireframe !== undefined ) {
  5940. mpars.wireframe = m.wireframe;
  5941. }
  5942. if ( m.vertexColors !== undefined ) {
  5943. if ( m.vertexColors === "face" ) {
  5944. mpars.vertexColors = THREE.FaceColors;
  5945. } else if ( m.vertexColors ) {
  5946. mpars.vertexColors = THREE.VertexColors;
  5947. }
  5948. }
  5949. // colors
  5950. if ( m.colorDiffuse ) {
  5951. mpars.color = rgb2hex( m.colorDiffuse );
  5952. } else if ( m.DbgColor ) {
  5953. mpars.color = m.DbgColor;
  5954. }
  5955. if ( m.colorSpecular ) {
  5956. mpars.specular = rgb2hex( m.colorSpecular );
  5957. }
  5958. if ( m.colorAmbient ) {
  5959. mpars.ambient = rgb2hex( m.colorAmbient );
  5960. }
  5961. // modifiers
  5962. if ( m.transparency ) {
  5963. mpars.opacity = m.transparency;
  5964. }
  5965. if ( m.specularCoef ) {
  5966. mpars.shininess = m.specularCoef;
  5967. }
  5968. // textures
  5969. if ( m.mapDiffuse && texturePath ) {
  5970. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5971. }
  5972. if ( m.mapLight && texturePath ) {
  5973. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5974. }
  5975. if ( m.mapBump && texturePath ) {
  5976. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5977. }
  5978. if ( m.mapNormal && texturePath ) {
  5979. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5980. }
  5981. if ( m.mapSpecular && texturePath ) {
  5982. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5983. }
  5984. //
  5985. if ( m.mapBumpScale ) {
  5986. mpars.bumpScale = m.mapBumpScale;
  5987. }
  5988. // special case for normal mapped material
  5989. if ( m.mapNormal ) {
  5990. var shader = THREE.ShaderLib[ "normalmap" ];
  5991. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5992. uniforms[ "tNormal" ].value = mpars.normalMap;
  5993. if ( m.mapNormalFactor ) {
  5994. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5995. }
  5996. if ( mpars.map ) {
  5997. uniforms[ "tDiffuse" ].value = mpars.map;
  5998. uniforms[ "enableDiffuse" ].value = true;
  5999. }
  6000. if ( mpars.specularMap ) {
  6001. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6002. uniforms[ "enableSpecular" ].value = true;
  6003. }
  6004. if ( mpars.lightMap ) {
  6005. uniforms[ "tAO" ].value = mpars.lightMap;
  6006. uniforms[ "enableAO" ].value = true;
  6007. }
  6008. // for the moment don't handle displacement texture
  6009. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6010. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6011. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6012. uniforms[ "uShininess" ].value = mpars.shininess;
  6013. if ( mpars.opacity !== undefined ) {
  6014. uniforms[ "uOpacity" ].value = mpars.opacity;
  6015. }
  6016. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6017. var material = new THREE.ShaderMaterial( parameters );
  6018. if ( mpars.transparent ) {
  6019. material.transparent = true;
  6020. }
  6021. } else {
  6022. var material = new THREE[ mtype ]( mpars );
  6023. }
  6024. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6025. return material;
  6026. }
  6027. };
  6028. /**
  6029. * @author mrdoob / http://mrdoob.com/
  6030. */
  6031. THREE.XHRLoader = function ( manager ) {
  6032. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6033. };
  6034. THREE.XHRLoader.prototype = {
  6035. constructor: THREE.XHRLoader,
  6036. load: function ( url, onLoad, onProgress, onError ) {
  6037. var scope = this;
  6038. var request = new XMLHttpRequest();
  6039. if ( onLoad !== undefined ) {
  6040. request.addEventListener( 'load', function ( event ) {
  6041. scope.manager.itemEnd( url );
  6042. onLoad( event.target.responseText );
  6043. }, false );
  6044. }
  6045. if ( onProgress !== undefined ) {
  6046. request.addEventListener( 'progress', function ( event ) {
  6047. onProgress( event );
  6048. }, false );
  6049. }
  6050. if ( onError !== undefined ) {
  6051. request.addEventListener( 'error', function ( event ) {
  6052. onError( event );
  6053. }, false );
  6054. }
  6055. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6056. request.open( 'GET', url, true );
  6057. request.send( null );
  6058. scope.manager.itemStart( url );
  6059. },
  6060. setCrossOrigin: function ( value ) {
  6061. this.crossOrigin = value;
  6062. }
  6063. };
  6064. /**
  6065. * @author mrdoob / http://mrdoob.com/
  6066. */
  6067. THREE.ImageLoader = function ( manager ) {
  6068. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6069. };
  6070. THREE.ImageLoader.prototype = {
  6071. constructor: THREE.ImageLoader,
  6072. load: function ( url, onLoad, onProgress, onError ) {
  6073. var scope = this;
  6074. var image = document.createElement( 'img' );
  6075. if ( onLoad !== undefined ) {
  6076. image.addEventListener( 'load', function ( event ) {
  6077. scope.manager.itemEnd( url );
  6078. onLoad( this );
  6079. }, false );
  6080. }
  6081. if ( onProgress !== undefined ) {
  6082. image.addEventListener( 'progress', function ( event ) {
  6083. onProgress( event );
  6084. }, false );
  6085. }
  6086. if ( onError !== undefined ) {
  6087. image.addEventListener( 'error', function ( event ) {
  6088. onError( event );
  6089. }, false );
  6090. }
  6091. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6092. image.src = url;
  6093. scope.manager.itemStart( url );
  6094. },
  6095. setCrossOrigin: function ( value ) {
  6096. this.crossOrigin = value;
  6097. }
  6098. }
  6099. /**
  6100. * @author mrdoob / http://mrdoob.com/
  6101. * @author alteredq / http://alteredqualia.com/
  6102. */
  6103. THREE.JSONLoader = function ( showStatus ) {
  6104. THREE.Loader.call( this, showStatus );
  6105. this.withCredentials = false;
  6106. };
  6107. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6108. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6109. var scope = this;
  6110. // todo: unify load API to for easier SceneLoader use
  6111. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6112. this.onLoadStart();
  6113. this.loadAjaxJSON( this, url, callback, texturePath );
  6114. };
  6115. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6116. var xhr = new XMLHttpRequest();
  6117. var length = 0;
  6118. xhr.onreadystatechange = function () {
  6119. if ( xhr.readyState === xhr.DONE ) {
  6120. if ( xhr.status === 200 || xhr.status === 0 ) {
  6121. if ( xhr.responseText ) {
  6122. var json = JSON.parse( xhr.responseText );
  6123. var result = context.parse( json, texturePath );
  6124. callback( result.geometry, result.materials );
  6125. } else {
  6126. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6127. }
  6128. // in context of more complex asset initialization
  6129. // do not block on single failed file
  6130. // maybe should go even one more level up
  6131. context.onLoadComplete();
  6132. } else {
  6133. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6134. }
  6135. } else if ( xhr.readyState === xhr.LOADING ) {
  6136. if ( callbackProgress ) {
  6137. if ( length === 0 ) {
  6138. length = xhr.getResponseHeader( "Content-Length" );
  6139. }
  6140. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6141. }
  6142. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6143. if ( callbackProgress !== undefined ) {
  6144. length = xhr.getResponseHeader( "Content-Length" );
  6145. }
  6146. }
  6147. };
  6148. xhr.open( "GET", url, true );
  6149. xhr.withCredentials = this.withCredentials;
  6150. xhr.send( null );
  6151. };
  6152. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6153. var scope = this,
  6154. geometry = new THREE.Geometry(),
  6155. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6156. parseModel( scale );
  6157. parseSkin();
  6158. parseMorphing( scale );
  6159. geometry.computeCentroids();
  6160. geometry.computeFaceNormals();
  6161. function parseModel( scale ) {
  6162. function isBitSet( value, position ) {
  6163. return value & ( 1 << position );
  6164. }
  6165. var i, j, fi,
  6166. offset, zLength, nVertices,
  6167. colorIndex, normalIndex, uvIndex, materialIndex,
  6168. type,
  6169. isQuad,
  6170. hasMaterial,
  6171. hasFaceUv, hasFaceVertexUv,
  6172. hasFaceNormal, hasFaceVertexNormal,
  6173. hasFaceColor, hasFaceVertexColor,
  6174. vertex, face, color, normal,
  6175. uvLayer, uvs, u, v,
  6176. faces = json.faces,
  6177. vertices = json.vertices,
  6178. normals = json.normals,
  6179. colors = json.colors,
  6180. nUvLayers = 0;
  6181. // disregard empty arrays
  6182. for ( i = 0; i < json.uvs.length; i++ ) {
  6183. if ( json.uvs[ i ].length ) nUvLayers ++;
  6184. }
  6185. for ( i = 0; i < nUvLayers; i++ ) {
  6186. geometry.faceUvs[ i ] = [];
  6187. geometry.faceVertexUvs[ i ] = [];
  6188. }
  6189. offset = 0;
  6190. zLength = vertices.length;
  6191. while ( offset < zLength ) {
  6192. vertex = new THREE.Vector3();
  6193. vertex.x = vertices[ offset ++ ] * scale;
  6194. vertex.y = vertices[ offset ++ ] * scale;
  6195. vertex.z = vertices[ offset ++ ] * scale;
  6196. geometry.vertices.push( vertex );
  6197. }
  6198. offset = 0;
  6199. zLength = faces.length;
  6200. while ( offset < zLength ) {
  6201. type = faces[ offset ++ ];
  6202. isQuad = isBitSet( type, 0 );
  6203. hasMaterial = isBitSet( type, 1 );
  6204. hasFaceUv = isBitSet( type, 2 );
  6205. hasFaceVertexUv = isBitSet( type, 3 );
  6206. hasFaceNormal = isBitSet( type, 4 );
  6207. hasFaceVertexNormal = isBitSet( type, 5 );
  6208. hasFaceColor = isBitSet( type, 6 );
  6209. hasFaceVertexColor = isBitSet( type, 7 );
  6210. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6211. if ( isQuad ) {
  6212. face = new THREE.Face4();
  6213. face.a = faces[ offset ++ ];
  6214. face.b = faces[ offset ++ ];
  6215. face.c = faces[ offset ++ ];
  6216. face.d = faces[ offset ++ ];
  6217. nVertices = 4;
  6218. } else {
  6219. face = new THREE.Face3();
  6220. face.a = faces[ offset ++ ];
  6221. face.b = faces[ offset ++ ];
  6222. face.c = faces[ offset ++ ];
  6223. nVertices = 3;
  6224. }
  6225. if ( hasMaterial ) {
  6226. materialIndex = faces[ offset ++ ];
  6227. face.materialIndex = materialIndex;
  6228. }
  6229. // to get face <=> uv index correspondence
  6230. fi = geometry.faces.length;
  6231. if ( hasFaceUv ) {
  6232. for ( i = 0; i < nUvLayers; i++ ) {
  6233. uvLayer = json.uvs[ i ];
  6234. uvIndex = faces[ offset ++ ];
  6235. u = uvLayer[ uvIndex * 2 ];
  6236. v = uvLayer[ uvIndex * 2 + 1 ];
  6237. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  6238. }
  6239. }
  6240. if ( hasFaceVertexUv ) {
  6241. for ( i = 0; i < nUvLayers; i++ ) {
  6242. uvLayer = json.uvs[ i ];
  6243. uvs = [];
  6244. for ( j = 0; j < nVertices; j ++ ) {
  6245. uvIndex = faces[ offset ++ ];
  6246. u = uvLayer[ uvIndex * 2 ];
  6247. v = uvLayer[ uvIndex * 2 + 1 ];
  6248. uvs[ j ] = new THREE.Vector2( u, v );
  6249. }
  6250. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  6251. }
  6252. }
  6253. if ( hasFaceNormal ) {
  6254. normalIndex = faces[ offset ++ ] * 3;
  6255. normal = new THREE.Vector3();
  6256. normal.x = normals[ normalIndex ++ ];
  6257. normal.y = normals[ normalIndex ++ ];
  6258. normal.z = normals[ normalIndex ];
  6259. face.normal = normal;
  6260. }
  6261. if ( hasFaceVertexNormal ) {
  6262. for ( i = 0; i < nVertices; i++ ) {
  6263. normalIndex = faces[ offset ++ ] * 3;
  6264. normal = new THREE.Vector3();
  6265. normal.x = normals[ normalIndex ++ ];
  6266. normal.y = normals[ normalIndex ++ ];
  6267. normal.z = normals[ normalIndex ];
  6268. face.vertexNormals.push( normal );
  6269. }
  6270. }
  6271. if ( hasFaceColor ) {
  6272. colorIndex = faces[ offset ++ ];
  6273. color = new THREE.Color( colors[ colorIndex ] );
  6274. face.color = color;
  6275. }
  6276. if ( hasFaceVertexColor ) {
  6277. for ( i = 0; i < nVertices; i++ ) {
  6278. colorIndex = faces[ offset ++ ];
  6279. color = new THREE.Color( colors[ colorIndex ] );
  6280. face.vertexColors.push( color );
  6281. }
  6282. }
  6283. geometry.faces.push( face );
  6284. }
  6285. };
  6286. function parseSkin() {
  6287. var i, l, x, y, z, w, a, b, c, d;
  6288. if ( json.skinWeights ) {
  6289. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6290. x = json.skinWeights[ i ];
  6291. y = json.skinWeights[ i + 1 ];
  6292. z = 0;
  6293. w = 0;
  6294. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6295. }
  6296. }
  6297. if ( json.skinIndices ) {
  6298. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6299. a = json.skinIndices[ i ];
  6300. b = json.skinIndices[ i + 1 ];
  6301. c = 0;
  6302. d = 0;
  6303. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6304. }
  6305. }
  6306. geometry.bones = json.bones;
  6307. geometry.animation = json.animation;
  6308. };
  6309. function parseMorphing( scale ) {
  6310. if ( json.morphTargets !== undefined ) {
  6311. var i, l, v, vl, dstVertices, srcVertices;
  6312. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6313. geometry.morphTargets[ i ] = {};
  6314. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6315. geometry.morphTargets[ i ].vertices = [];
  6316. dstVertices = geometry.morphTargets[ i ].vertices;
  6317. srcVertices = json.morphTargets [ i ].vertices;
  6318. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6319. var vertex = new THREE.Vector3();
  6320. vertex.x = srcVertices[ v ] * scale;
  6321. vertex.y = srcVertices[ v + 1 ] * scale;
  6322. vertex.z = srcVertices[ v + 2 ] * scale;
  6323. dstVertices.push( vertex );
  6324. }
  6325. }
  6326. }
  6327. if ( json.morphColors !== undefined ) {
  6328. var i, l, c, cl, dstColors, srcColors, color;
  6329. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6330. geometry.morphColors[ i ] = {};
  6331. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6332. geometry.morphColors[ i ].colors = [];
  6333. dstColors = geometry.morphColors[ i ].colors;
  6334. srcColors = json.morphColors [ i ].colors;
  6335. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6336. color = new THREE.Color( 0xffaa00 );
  6337. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6338. dstColors.push( color );
  6339. }
  6340. }
  6341. }
  6342. };
  6343. if ( json.materials === undefined ) {
  6344. return { geometry: geometry };
  6345. } else {
  6346. var materials = this.initMaterials( json.materials, texturePath );
  6347. if ( this.needsTangents( materials ) ) {
  6348. geometry.computeTangents();
  6349. }
  6350. return { geometry: geometry, materials: materials };
  6351. }
  6352. };
  6353. /**
  6354. * @author mrdoob / http://mrdoob.com/
  6355. */
  6356. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6357. var scope = this;
  6358. var loaded = 0, total = 0;
  6359. this.onLoad = onLoad;
  6360. this.onProgress = onProgress;
  6361. this.onError = onError;
  6362. this.itemStart = function ( url ) {
  6363. total ++;
  6364. };
  6365. this.itemEnd = function ( url ) {
  6366. loaded ++;
  6367. if ( scope.onProgress !== undefined ) {
  6368. scope.onProgress( url, loaded, total );
  6369. }
  6370. if ( loaded === total && scope.onLoad !== undefined ) {
  6371. scope.onLoad();
  6372. }
  6373. };
  6374. };
  6375. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6376. /**
  6377. * @author mrdoob / http://mrdoob.com/
  6378. */
  6379. THREE.GeometryLoader = function ( manager ) {
  6380. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6381. };
  6382. THREE.GeometryLoader.prototype = {
  6383. constructor: THREE.GeometryLoader,
  6384. load: function ( url, onLoad, onProgress, onError ) {
  6385. var scope = this;
  6386. var loader = new THREE.XHRLoader();
  6387. loader.setCrossOrigin( this.crossOrigin );
  6388. loader.load( url, function ( text ) {
  6389. onLoad( scope.parse( JSON.parse( text ) ) );
  6390. } );
  6391. },
  6392. setCrossOrigin: function ( value ) {
  6393. this.crossOrigin = value;
  6394. },
  6395. parse: function ( json ) {
  6396. }
  6397. };
  6398. /**
  6399. * @author mrdoob / http://mrdoob.com/
  6400. */
  6401. THREE.MaterialLoader = function ( manager ) {
  6402. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6403. };
  6404. THREE.MaterialLoader.prototype = {
  6405. constructor: THREE.MaterialLoader,
  6406. load: function ( url, onLoad, onProgress, onError ) {
  6407. var scope = this;
  6408. var loader = new THREE.XHRLoader();
  6409. loader.setCrossOrigin( this.crossOrigin );
  6410. loader.load( url, function ( text ) {
  6411. onLoad( scope.parse( JSON.parse( text ) ) );
  6412. } );
  6413. },
  6414. setCrossOrigin: function ( value ) {
  6415. this.crossOrigin = value;
  6416. },
  6417. parse: function ( json ) {
  6418. var material;
  6419. switch ( json.type ) {
  6420. case 'MeshBasicMaterial':
  6421. material = new THREE.MeshBasicMaterial( {
  6422. color: json.color,
  6423. opacity: json.opacity,
  6424. transparent: json.transparent,
  6425. wireframe: json.wireframe
  6426. } );
  6427. break;
  6428. case 'MeshLambertMaterial':
  6429. material = new THREE.MeshLambertMaterial( {
  6430. color: json.color,
  6431. ambient: json.ambient,
  6432. emissive: json.emissive,
  6433. opacity: json.opacity,
  6434. transparent: json.transparent,
  6435. wireframe: json.wireframe
  6436. } );
  6437. break;
  6438. case 'MeshPhongMaterial':
  6439. material = new THREE.MeshPhongMaterial( {
  6440. color: json.color,
  6441. ambient: json.ambient,
  6442. emissive: json.emissive,
  6443. specular: json.specular,
  6444. shininess: json.shininess,
  6445. opacity: json.opacity,
  6446. transparent: json.transparent,
  6447. wireframe: json.wireframe
  6448. } );
  6449. break;
  6450. case 'MeshNormalMaterial':
  6451. material = new THREE.MeshNormalMaterial( {
  6452. opacity: json.opacity,
  6453. transparent: json.transparent,
  6454. wireframe: json.wireframe
  6455. } );
  6456. break;
  6457. case 'MeshDepthMaterial':
  6458. material = new THREE.MeshDepthMaterial( {
  6459. opacity: json.opacity,
  6460. transparent: json.transparent,
  6461. wireframe: json.wireframe
  6462. } );
  6463. break;
  6464. }
  6465. return material;
  6466. }
  6467. };
  6468. /**
  6469. * @author mrdoob / http://mrdoob.com/
  6470. */
  6471. THREE.ObjectLoader = function ( manager ) {
  6472. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6473. };
  6474. THREE.ObjectLoader.prototype = {
  6475. constructor: THREE.ObjectLoader,
  6476. load: function ( url, onLoad, onProgress, onError ) {
  6477. var scope = this;
  6478. var loader = new THREE.XHRLoader( scope.manager );
  6479. loader.setCrossOrigin( this.crossOrigin );
  6480. loader.load( url, function ( text ) {
  6481. onLoad( scope.parse( JSON.parse( text ) ) );
  6482. } );
  6483. },
  6484. setCrossOrigin: function ( value ) {
  6485. this.crossOrigin = value;
  6486. },
  6487. parse: function ( json ) {
  6488. var geometries = this.parseGeometries( json.geometries );
  6489. var materials = this.parseMaterials( json.materials );
  6490. var object = this.parseObject( json.object, geometries, materials );
  6491. return object;
  6492. },
  6493. parseGeometries: function ( json ) {
  6494. var geometries = {};
  6495. if ( json !== undefined ) {
  6496. var loader = new THREE.JSONLoader();
  6497. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6498. var geometry;
  6499. var data = json[ i ];
  6500. switch ( data.type ) {
  6501. case 'PlaneGeometry':
  6502. geometry = new THREE.PlaneGeometry(
  6503. data.width,
  6504. data.height,
  6505. data.widthSegments,
  6506. data.heightSegments
  6507. );
  6508. break;
  6509. case 'CubeGeometry':
  6510. geometry = new THREE.CubeGeometry(
  6511. data.width,
  6512. data.height,
  6513. data.depth,
  6514. data.widthSegments,
  6515. data.heightSegments,
  6516. data.depthSegments
  6517. );
  6518. break;
  6519. case 'CylinderGeometry':
  6520. geometry = new THREE.CylinderGeometry(
  6521. data.radiusTop,
  6522. data.radiusBottom,
  6523. data.height,
  6524. data.radiusSegments,
  6525. data.heightSegments,
  6526. data.openEnded
  6527. );
  6528. break;
  6529. case 'SphereGeometry':
  6530. geometry = new THREE.SphereGeometry(
  6531. data.radius,
  6532. data.widthSegments,
  6533. data.heightSegments,
  6534. data.phiStart,
  6535. data.phiLength,
  6536. data.thetaStart,
  6537. data.thetaLength
  6538. );
  6539. break;
  6540. case 'IcosahedronGeometry':
  6541. geometry = new THREE.IcosahedronGeometry(
  6542. data.radius,
  6543. data.detail
  6544. );
  6545. break;
  6546. case 'TorusGeometry':
  6547. geometry = new THREE.TorusGeometry(
  6548. data.radius,
  6549. data.tube,
  6550. data.radialSegments,
  6551. data.tubularSegments,
  6552. data.arc
  6553. );
  6554. break;
  6555. case 'TorusKnotGeometry':
  6556. geometry = new THREE.TorusKnotGeometry(
  6557. data.radius,
  6558. data.tube,
  6559. data.radialSegments,
  6560. data.tubularSegments,
  6561. data.p,
  6562. data.q,
  6563. data.heightScale
  6564. );
  6565. break;
  6566. case 'Geometry':
  6567. geometry = loader.parse( data.data ).geometry;
  6568. break;
  6569. }
  6570. if ( data.id !== undefined ) geometry.id = data.id;
  6571. if ( data.name !== undefined ) geometry.name = data.name;
  6572. geometries[ data.id ] = geometry;
  6573. }
  6574. }
  6575. return geometries;
  6576. },
  6577. parseMaterials: function ( json ) {
  6578. var materials = {};
  6579. if ( json !== undefined ) {
  6580. var loader = new THREE.MaterialLoader();
  6581. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6582. var data = json[ i ];
  6583. var material = loader.parse( data );
  6584. if ( data.id !== undefined ) material.id = data.id;
  6585. if ( data.name !== undefined ) material.name = data.name;
  6586. materials[ data.id ] = material;
  6587. }
  6588. }
  6589. return materials;
  6590. },
  6591. parseObject: function () {
  6592. var matrix = new THREE.Matrix4();
  6593. return function ( data, geometries, materials ) {
  6594. var object;
  6595. switch ( data.type ) {
  6596. case 'Scene':
  6597. object = new THREE.Scene();
  6598. break;
  6599. case 'PerspectiveCamera':
  6600. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6601. break;
  6602. case 'OrthographicCamera':
  6603. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6604. break;
  6605. case 'AmbientLight':
  6606. object = new THREE.AmbientLight( data.color );
  6607. break;
  6608. case 'DirectionalLight':
  6609. object = new THREE.DirectionalLight( data.color, data.intensity );
  6610. break;
  6611. case 'PointLight':
  6612. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6613. break;
  6614. case 'SpotLight':
  6615. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6616. break;
  6617. case 'HemisphereLight':
  6618. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6619. break;
  6620. case 'Mesh':
  6621. object = new THREE.Mesh( geometries[ data.geometry ], materials[ data.material ] );
  6622. break;
  6623. default:
  6624. object = new THREE.Object3D();
  6625. }
  6626. if ( data.matrix !== undefined ) {
  6627. matrix.fromArray( data.matrix );
  6628. matrix.decompose( object.position, object.quaternion, object.scale );
  6629. } else {
  6630. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6631. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6632. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6633. }
  6634. if ( data.id !== undefined ) object.id = data.id;
  6635. if ( data.name !== undefined ) object.name = data.name;
  6636. if ( data.visible !== undefined ) object.visible = data.visible;
  6637. if ( data.userData !== undefined ) object.userData = data.userData;
  6638. if ( data.children !== undefined ) {
  6639. for ( var child in data.children ) {
  6640. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6641. }
  6642. }
  6643. return object;
  6644. }
  6645. }()
  6646. };
  6647. /**
  6648. * @author alteredq / http://alteredqualia.com/
  6649. */
  6650. THREE.SceneLoader = function () {
  6651. this.onLoadStart = function () {};
  6652. this.onLoadProgress = function() {};
  6653. this.onLoadComplete = function () {};
  6654. this.callbackSync = function () {};
  6655. this.callbackProgress = function () {};
  6656. this.geometryHandlers = {};
  6657. this.hierarchyHandlers = {};
  6658. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6659. };
  6660. THREE.SceneLoader.prototype = {
  6661. constructor: THREE.SceneLoader,
  6662. load: function ( url, onLoad, onProgress, onError ) {
  6663. var scope = this;
  6664. var loader = new THREE.XHRLoader( scope.manager );
  6665. loader.setCrossOrigin( this.crossOrigin );
  6666. loader.load( url, function ( text ) {
  6667. scope.parse( JSON.parse( text ), onLoad, url );
  6668. } );
  6669. },
  6670. setCrossOrigin: function ( value ) {
  6671. this.crossOrigin = value;
  6672. },
  6673. addGeometryHandler: function ( typeID, loaderClass ) {
  6674. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  6675. },
  6676. addHierarchyHandler: function ( typeID, loaderClass ) {
  6677. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  6678. },
  6679. parse: function ( json, callbackFinished, url ) {
  6680. var scope = this;
  6681. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6682. var geometry, material, camera, fog,
  6683. texture, images, color,
  6684. light, hex, intensity,
  6685. counter_models, counter_textures,
  6686. total_models, total_textures,
  6687. result;
  6688. var target_array = [];
  6689. var data = json;
  6690. // async geometry loaders
  6691. for ( var typeID in this.geometryHandlers ) {
  6692. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  6693. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6694. }
  6695. // async hierachy loaders
  6696. for ( var typeID in this.hierarchyHandlers ) {
  6697. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  6698. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6699. }
  6700. counter_models = 0;
  6701. counter_textures = 0;
  6702. result = {
  6703. scene: new THREE.Scene(),
  6704. geometries: {},
  6705. face_materials: {},
  6706. materials: {},
  6707. textures: {},
  6708. objects: {},
  6709. cameras: {},
  6710. lights: {},
  6711. fogs: {},
  6712. empties: {},
  6713. groups: {}
  6714. };
  6715. if ( data.transform ) {
  6716. var position = data.transform.position,
  6717. rotation = data.transform.rotation,
  6718. scale = data.transform.scale;
  6719. if ( position ) {
  6720. result.scene.position.fromArray( position );
  6721. }
  6722. if ( rotation ) {
  6723. result.scene.rotation.fromArray( rotation );
  6724. }
  6725. if ( scale ) {
  6726. result.scene.scale.fromArray( scale );
  6727. }
  6728. if ( position || rotation || scale ) {
  6729. result.scene.updateMatrix();
  6730. result.scene.updateMatrixWorld();
  6731. }
  6732. }
  6733. function get_url( source_url, url_type ) {
  6734. if ( url_type == "relativeToHTML" ) {
  6735. return source_url;
  6736. } else {
  6737. return urlBase + "/" + source_url;
  6738. }
  6739. };
  6740. // toplevel loader function, delegates to handle_children
  6741. function handle_objects() {
  6742. handle_children( result.scene, data.objects );
  6743. }
  6744. // handle all the children from the loaded json and attach them to given parent
  6745. function handle_children( parent, children ) {
  6746. var mat, dst, pos, rot, scl, quat;
  6747. for ( var objID in children ) {
  6748. // check by id if child has already been handled,
  6749. // if not, create new object
  6750. var object = result.objects[ objID ];
  6751. var objJSON = children[ objID ];
  6752. if ( object === undefined ) {
  6753. // meshes
  6754. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  6755. if ( objJSON.loading === undefined ) {
  6756. var reservedTypes = {
  6757. "type": 1, "url": 1, "material": 1,
  6758. "position": 1, "rotation": 1, "scale" : 1,
  6759. "visible": 1, "children": 1, "userData": 1,
  6760. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  6761. };
  6762. var loaderParameters = {};
  6763. for ( var parType in objJSON ) {
  6764. if ( ! ( parType in reservedTypes ) ) {
  6765. loaderParameters[ parType ] = objJSON[ parType ];
  6766. }
  6767. }
  6768. material = result.materials[ objJSON.material ];
  6769. objJSON.loading = true;
  6770. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  6771. // ColladaLoader
  6772. if ( loader.options ) {
  6773. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6774. // UTF8Loader
  6775. // OBJLoader
  6776. } else {
  6777. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6778. }
  6779. }
  6780. } else if ( objJSON.geometry !== undefined ) {
  6781. geometry = result.geometries[ objJSON.geometry ];
  6782. // geometry already loaded
  6783. if ( geometry ) {
  6784. var needsTangents = false;
  6785. material = result.materials[ objJSON.material ];
  6786. needsTangents = material instanceof THREE.ShaderMaterial;
  6787. pos = objJSON.position;
  6788. rot = objJSON.rotation;
  6789. scl = objJSON.scale;
  6790. mat = objJSON.matrix;
  6791. quat = objJSON.quaternion;
  6792. // use materials from the model file
  6793. // if there is no material specified in the object
  6794. if ( ! objJSON.material ) {
  6795. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6796. }
  6797. // use materials from the model file
  6798. // if there is just empty face material
  6799. // (must create new material as each model has its own face material)
  6800. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6801. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6802. }
  6803. if ( material instanceof THREE.MeshFaceMaterial ) {
  6804. for ( var i = 0; i < material.materials.length; i ++ ) {
  6805. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6806. }
  6807. }
  6808. if ( needsTangents ) {
  6809. geometry.computeTangents();
  6810. }
  6811. if ( objJSON.skin ) {
  6812. object = new THREE.SkinnedMesh( geometry, material );
  6813. } else if ( objJSON.morph ) {
  6814. object = new THREE.MorphAnimMesh( geometry, material );
  6815. if ( objJSON.duration !== undefined ) {
  6816. object.duration = objJSON.duration;
  6817. }
  6818. if ( objJSON.time !== undefined ) {
  6819. object.time = objJSON.time;
  6820. }
  6821. if ( objJSON.mirroredLoop !== undefined ) {
  6822. object.mirroredLoop = objJSON.mirroredLoop;
  6823. }
  6824. if ( material.morphNormals ) {
  6825. geometry.computeMorphNormals();
  6826. }
  6827. } else {
  6828. object = new THREE.Mesh( geometry, material );
  6829. }
  6830. object.name = objID;
  6831. if ( mat ) {
  6832. object.matrixAutoUpdate = false;
  6833. object.matrix.set(
  6834. mat[0], mat[1], mat[2], mat[3],
  6835. mat[4], mat[5], mat[6], mat[7],
  6836. mat[8], mat[9], mat[10], mat[11],
  6837. mat[12], mat[13], mat[14], mat[15]
  6838. );
  6839. } else {
  6840. object.position.fromArray( pos );
  6841. if ( quat ) {
  6842. object.quaternion.fromArray( quat );
  6843. } else {
  6844. object.rotation.fromArray( rot );
  6845. }
  6846. object.scale.fromArray( scl );
  6847. }
  6848. object.visible = objJSON.visible;
  6849. object.castShadow = objJSON.castShadow;
  6850. object.receiveShadow = objJSON.receiveShadow;
  6851. parent.add( object );
  6852. result.objects[ objID ] = object;
  6853. }
  6854. // lights
  6855. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6856. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6857. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6858. if ( objJSON.type === "DirectionalLight" ) {
  6859. pos = objJSON.direction;
  6860. light = new THREE.DirectionalLight( hex, intensity );
  6861. light.position.fromArray( pos );
  6862. if ( objJSON.target ) {
  6863. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6864. // kill existing default target
  6865. // otherwise it gets added to scene when parent gets added
  6866. light.target = null;
  6867. }
  6868. } else if ( objJSON.type === "PointLight" ) {
  6869. pos = objJSON.position;
  6870. dst = objJSON.distance;
  6871. light = new THREE.PointLight( hex, intensity, dst );
  6872. light.position.fromArray( pos );
  6873. } else if ( objJSON.type === "AmbientLight" ) {
  6874. light = new THREE.AmbientLight( hex );
  6875. }
  6876. parent.add( light );
  6877. light.name = objID;
  6878. result.lights[ objID ] = light;
  6879. result.objects[ objID ] = light;
  6880. // cameras
  6881. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6882. pos = objJSON.position;
  6883. rot = objJSON.rotation;
  6884. quat = objJSON.quaternion;
  6885. if ( objJSON.type === "PerspectiveCamera" ) {
  6886. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6887. } else if ( objJSON.type === "OrthographicCamera" ) {
  6888. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6889. }
  6890. camera.name = objID;
  6891. camera.position.fromArray( pos );
  6892. if ( quat !== undefined ) {
  6893. camera.quaternion.fromArray( quat );
  6894. } else if ( rot !== undefined ) {
  6895. camera.rotation.fromArray( rot );
  6896. }
  6897. parent.add( camera );
  6898. result.cameras[ objID ] = camera;
  6899. result.objects[ objID ] = camera;
  6900. // pure Object3D
  6901. } else {
  6902. pos = objJSON.position;
  6903. rot = objJSON.rotation;
  6904. scl = objJSON.scale;
  6905. quat = objJSON.quaternion;
  6906. object = new THREE.Object3D();
  6907. object.name = objID;
  6908. object.position.fromArray( pos );
  6909. if ( quat ) {
  6910. object.quaternion.fromArray( quat );
  6911. } else {
  6912. object.rotation.fromArray( rot );
  6913. }
  6914. object.scale.fromArray( scl );
  6915. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6916. parent.add( object );
  6917. result.objects[ objID ] = object;
  6918. result.empties[ objID ] = object;
  6919. }
  6920. if ( object ) {
  6921. if ( objJSON.userData !== undefined ) {
  6922. for ( var key in objJSON.userData ) {
  6923. var value = objJSON.userData[ key ];
  6924. object.userData[ key ] = value;
  6925. }
  6926. }
  6927. if ( objJSON.groups !== undefined ) {
  6928. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6929. var groupID = objJSON.groups[ i ];
  6930. if ( result.groups[ groupID ] === undefined ) {
  6931. result.groups[ groupID ] = [];
  6932. }
  6933. result.groups[ groupID ].push( objID );
  6934. }
  6935. }
  6936. }
  6937. }
  6938. if ( object !== undefined && objJSON.children !== undefined ) {
  6939. handle_children( object, objJSON.children );
  6940. }
  6941. }
  6942. };
  6943. function handle_mesh( geo, mat, id ) {
  6944. result.geometries[ id ] = geo;
  6945. result.face_materials[ id ] = mat;
  6946. handle_objects();
  6947. };
  6948. function handle_hierarchy( node, id, parent, material, obj ) {
  6949. var p = obj.position;
  6950. var r = obj.rotation;
  6951. var q = obj.quaternion;
  6952. var s = obj.scale;
  6953. node.position.fromArray( p );
  6954. if ( q ) {
  6955. node.quaternion.fromArray( q );
  6956. } else {
  6957. node.rotation.fromArray( r );
  6958. }
  6959. node.scale.fromArray( s );
  6960. // override children materials
  6961. // if object material was specified in JSON explicitly
  6962. if ( material ) {
  6963. node.traverse( function ( child ) {
  6964. child.material = material;
  6965. } );
  6966. }
  6967. // override children visibility
  6968. // with root node visibility as specified in JSON
  6969. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6970. node.traverse( function ( child ) {
  6971. child.visible = visible;
  6972. } );
  6973. parent.add( node );
  6974. node.name = id;
  6975. result.objects[ id ] = node;
  6976. handle_objects();
  6977. };
  6978. function create_callback_geometry( id ) {
  6979. return function ( geo, mat ) {
  6980. geo.name = id;
  6981. handle_mesh( geo, mat, id );
  6982. counter_models -= 1;
  6983. scope.onLoadComplete();
  6984. async_callback_gate();
  6985. }
  6986. };
  6987. function create_callback_hierachy( id, parent, material, obj ) {
  6988. return function ( event ) {
  6989. var result;
  6990. // loaders which use EventDispatcher
  6991. if ( event.content ) {
  6992. result = event.content;
  6993. // ColladaLoader
  6994. } else if ( event.dae ) {
  6995. result = event.scene;
  6996. // UTF8Loader
  6997. } else {
  6998. result = event;
  6999. }
  7000. handle_hierarchy( result, id, parent, material, obj );
  7001. counter_models -= 1;
  7002. scope.onLoadComplete();
  7003. async_callback_gate();
  7004. }
  7005. };
  7006. function create_callback_embed( id ) {
  7007. return function ( geo, mat ) {
  7008. geo.name = id;
  7009. result.geometries[ id ] = geo;
  7010. result.face_materials[ id ] = mat;
  7011. }
  7012. };
  7013. function async_callback_gate() {
  7014. var progress = {
  7015. totalModels : total_models,
  7016. totalTextures : total_textures,
  7017. loadedModels : total_models - counter_models,
  7018. loadedTextures : total_textures - counter_textures
  7019. };
  7020. scope.callbackProgress( progress, result );
  7021. scope.onLoadProgress();
  7022. if ( counter_models === 0 && counter_textures === 0 ) {
  7023. finalize();
  7024. callbackFinished( result );
  7025. }
  7026. };
  7027. function finalize() {
  7028. // take care of targets which could be asynchronously loaded objects
  7029. for ( var i = 0; i < target_array.length; i ++ ) {
  7030. var ta = target_array[ i ];
  7031. var target = result.objects[ ta.targetName ];
  7032. if ( target ) {
  7033. ta.object.target = target;
  7034. } else {
  7035. // if there was error and target of specified name doesn't exist in the scene file
  7036. // create instead dummy target
  7037. // (target must be added to scene explicitly as parent is already added)
  7038. ta.object.target = new THREE.Object3D();
  7039. result.scene.add( ta.object.target );
  7040. }
  7041. ta.object.target.userData.targetInverse = ta.object;
  7042. }
  7043. };
  7044. var callbackTexture = function ( count ) {
  7045. counter_textures -= count;
  7046. async_callback_gate();
  7047. scope.onLoadComplete();
  7048. };
  7049. // must use this instead of just directly calling callbackTexture
  7050. // because of closure in the calling context loop
  7051. var generateTextureCallback = function ( count ) {
  7052. return function () {
  7053. callbackTexture( count );
  7054. };
  7055. };
  7056. function traverse_json_hierarchy( objJSON, callback ) {
  7057. callback( objJSON );
  7058. if ( objJSON.children !== undefined ) {
  7059. for ( var objChildID in objJSON.children ) {
  7060. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7061. }
  7062. }
  7063. };
  7064. // first go synchronous elements
  7065. // fogs
  7066. var fogID, fogJSON;
  7067. for ( fogID in data.fogs ) {
  7068. fogJSON = data.fogs[ fogID ];
  7069. if ( fogJSON.type === "linear" ) {
  7070. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7071. } else if ( fogJSON.type === "exp2" ) {
  7072. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7073. }
  7074. color = fogJSON.color;
  7075. fog.color.setRGB( color[0], color[1], color[2] );
  7076. result.fogs[ fogID ] = fog;
  7077. }
  7078. // now come potentially asynchronous elements
  7079. // geometries
  7080. // count how many geometries will be loaded asynchronously
  7081. var geoID, geoJSON;
  7082. for ( geoID in data.geometries ) {
  7083. geoJSON = data.geometries[ geoID ];
  7084. if ( geoJSON.type in this.geometryHandlers ) {
  7085. counter_models += 1;
  7086. scope.onLoadStart();
  7087. }
  7088. }
  7089. // count how many hierarchies will be loaded asynchronously
  7090. for ( var objID in data.objects ) {
  7091. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7092. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7093. counter_models += 1;
  7094. scope.onLoadStart();
  7095. }
  7096. });
  7097. }
  7098. total_models = counter_models;
  7099. for ( geoID in data.geometries ) {
  7100. geoJSON = data.geometries[ geoID ];
  7101. if ( geoJSON.type === "cube" ) {
  7102. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7103. geometry.name = geoID;
  7104. result.geometries[ geoID ] = geometry;
  7105. } else if ( geoJSON.type === "plane" ) {
  7106. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7107. geometry.name = geoID;
  7108. result.geometries[ geoID ] = geometry;
  7109. } else if ( geoJSON.type === "sphere" ) {
  7110. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7111. geometry.name = geoID;
  7112. result.geometries[ geoID ] = geometry;
  7113. } else if ( geoJSON.type === "cylinder" ) {
  7114. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7115. geometry.name = geoID;
  7116. result.geometries[ geoID ] = geometry;
  7117. } else if ( geoJSON.type === "torus" ) {
  7118. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7119. geometry.name = geoID;
  7120. result.geometries[ geoID ] = geometry;
  7121. } else if ( geoJSON.type === "icosahedron" ) {
  7122. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7123. geometry.name = geoID;
  7124. result.geometries[ geoID ] = geometry;
  7125. } else if ( geoJSON.type in this.geometryHandlers ) {
  7126. var loaderParameters = {};
  7127. for ( var parType in geoJSON ) {
  7128. if ( parType !== "type" && parType !== "url" ) {
  7129. loaderParameters[ parType ] = geoJSON[ parType ];
  7130. }
  7131. }
  7132. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7133. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7134. } else if ( geoJSON.type === "embedded" ) {
  7135. var modelJson = data.embeds[ geoJSON.id ],
  7136. texture_path = "";
  7137. // pass metadata along to jsonLoader so it knows the format version
  7138. modelJson.metadata = data.metadata;
  7139. if ( modelJson ) {
  7140. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7141. var model = jsonLoader.parse( modelJson, texture_path );
  7142. create_callback_embed( geoID )( model.geometry, model.materials );
  7143. }
  7144. }
  7145. }
  7146. // textures
  7147. // count how many textures will be loaded asynchronously
  7148. var textureID, textureJSON;
  7149. for ( textureID in data.textures ) {
  7150. textureJSON = data.textures[ textureID ];
  7151. if ( textureJSON.url instanceof Array ) {
  7152. counter_textures += textureJSON.url.length;
  7153. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7154. scope.onLoadStart();
  7155. }
  7156. } else {
  7157. counter_textures += 1;
  7158. scope.onLoadStart();
  7159. }
  7160. }
  7161. total_textures = counter_textures;
  7162. for ( textureID in data.textures ) {
  7163. textureJSON = data.textures[ textureID ];
  7164. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7165. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7166. }
  7167. if ( textureJSON.url instanceof Array ) {
  7168. var count = textureJSON.url.length;
  7169. var url_array = [];
  7170. for( var i = 0; i < count; i ++ ) {
  7171. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7172. }
  7173. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7174. if ( isCompressed ) {
  7175. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7176. } else {
  7177. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7178. }
  7179. } else {
  7180. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7181. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7182. var textureCallback = generateTextureCallback( 1 );
  7183. if ( isCompressed ) {
  7184. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7185. } else {
  7186. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7187. }
  7188. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7189. texture.minFilter = THREE[ textureJSON.minFilter ];
  7190. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7191. texture.magFilter = THREE[ textureJSON.magFilter ];
  7192. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7193. if ( textureJSON.repeat ) {
  7194. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7195. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7196. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7197. }
  7198. if ( textureJSON.offset ) {
  7199. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7200. }
  7201. // handle wrap after repeat so that default repeat can be overriden
  7202. if ( textureJSON.wrap ) {
  7203. var wrapMap = {
  7204. "repeat": THREE.RepeatWrapping,
  7205. "mirror": THREE.MirroredRepeatWrapping
  7206. }
  7207. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7208. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7209. }
  7210. }
  7211. result.textures[ textureID ] = texture;
  7212. }
  7213. // materials
  7214. var matID, matJSON;
  7215. var parID;
  7216. for ( matID in data.materials ) {
  7217. matJSON = data.materials[ matID ];
  7218. for ( parID in matJSON.parameters ) {
  7219. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7220. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7221. } else if ( parID === "shading" ) {
  7222. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7223. } else if ( parID === "side" ) {
  7224. if ( matJSON.parameters[ parID ] == "double" ) {
  7225. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7226. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7227. matJSON.parameters[ parID ] = THREE.BackSide;
  7228. } else {
  7229. matJSON.parameters[ parID ] = THREE.FrontSide;
  7230. }
  7231. } else if ( parID === "blending" ) {
  7232. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7233. } else if ( parID === "combine" ) {
  7234. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7235. } else if ( parID === "vertexColors" ) {
  7236. if ( matJSON.parameters[ parID ] == "face" ) {
  7237. matJSON.parameters[ parID ] = THREE.FaceColors;
  7238. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7239. } else if ( matJSON.parameters[ parID ] ) {
  7240. matJSON.parameters[ parID ] = THREE.VertexColors;
  7241. }
  7242. } else if ( parID === "wrapRGB" ) {
  7243. var v3 = matJSON.parameters[ parID ];
  7244. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7245. }
  7246. }
  7247. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7248. matJSON.parameters.transparent = true;
  7249. }
  7250. if ( matJSON.parameters.normalMap ) {
  7251. var shader = THREE.ShaderLib[ "normalmap" ];
  7252. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7253. var diffuse = matJSON.parameters.color;
  7254. var specular = matJSON.parameters.specular;
  7255. var ambient = matJSON.parameters.ambient;
  7256. var shininess = matJSON.parameters.shininess;
  7257. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7258. if ( matJSON.parameters.normalScale ) {
  7259. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7260. }
  7261. if ( matJSON.parameters.map ) {
  7262. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7263. uniforms[ "enableDiffuse" ].value = true;
  7264. }
  7265. if ( matJSON.parameters.envMap ) {
  7266. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7267. uniforms[ "enableReflection" ].value = true;
  7268. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7269. }
  7270. if ( matJSON.parameters.lightMap ) {
  7271. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7272. uniforms[ "enableAO" ].value = true;
  7273. }
  7274. if ( matJSON.parameters.specularMap ) {
  7275. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7276. uniforms[ "enableSpecular" ].value = true;
  7277. }
  7278. if ( matJSON.parameters.displacementMap ) {
  7279. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7280. uniforms[ "enableDisplacement" ].value = true;
  7281. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7282. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7283. }
  7284. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7285. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7286. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7287. uniforms[ "uShininess" ].value = shininess;
  7288. if ( matJSON.parameters.opacity ) {
  7289. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7290. }
  7291. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7292. material = new THREE.ShaderMaterial( parameters );
  7293. } else {
  7294. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7295. }
  7296. material.name = matID;
  7297. result.materials[ matID ] = material;
  7298. }
  7299. // second pass through all materials to initialize MeshFaceMaterials
  7300. // that could be referring to other materials out of order
  7301. for ( matID in data.materials ) {
  7302. matJSON = data.materials[ matID ];
  7303. if ( matJSON.parameters.materials ) {
  7304. var materialArray = [];
  7305. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7306. var label = matJSON.parameters.materials[ i ];
  7307. materialArray.push( result.materials[ label ] );
  7308. }
  7309. result.materials[ matID ].materials = materialArray;
  7310. }
  7311. }
  7312. // objects ( synchronous init of procedural primitives )
  7313. handle_objects();
  7314. // defaults
  7315. if ( result.cameras && data.defaults.camera ) {
  7316. result.currentCamera = result.cameras[ data.defaults.camera ];
  7317. }
  7318. if ( result.fogs && data.defaults.fog ) {
  7319. result.scene.fog = result.fogs[ data.defaults.fog ];
  7320. }
  7321. // synchronous callback
  7322. scope.callbackSync( result );
  7323. // just in case there are no async elements
  7324. async_callback_gate();
  7325. }
  7326. }
  7327. /**
  7328. * @author mrdoob / http://mrdoob.com/
  7329. */
  7330. THREE.TextureLoader = function ( manager ) {
  7331. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7332. };
  7333. THREE.TextureLoader.prototype = {
  7334. constructor: THREE.TextureLoader,
  7335. load: function ( url, onLoad, onProgress, onError ) {
  7336. var scope = this;
  7337. var loader = new THREE.ImageLoader( scope.manager );
  7338. loader.setCrossOrigin( this.crossOrigin );
  7339. loader.load( url, function ( image ) {
  7340. var texture = new THREE.Texture( image );
  7341. texture.needsUpdate = true;
  7342. if ( onLoad !== undefined ) {
  7343. onLoad( texture );
  7344. }
  7345. } );
  7346. },
  7347. setCrossOrigin: function ( value ) {
  7348. this.crossOrigin = value;
  7349. }
  7350. };
  7351. /**
  7352. * @author mrdoob / http://mrdoob.com/
  7353. * @author alteredq / http://alteredqualia.com/
  7354. */
  7355. THREE.Material = function () {
  7356. this.id = THREE.Math.generateUUID();
  7357. this.name = '';
  7358. this.side = THREE.FrontSide;
  7359. this.opacity = 1;
  7360. this.transparent = false;
  7361. this.blending = THREE.NormalBlending;
  7362. this.blendSrc = THREE.SrcAlphaFactor;
  7363. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7364. this.blendEquation = THREE.AddEquation;
  7365. this.depthTest = true;
  7366. this.depthWrite = true;
  7367. this.polygonOffset = false;
  7368. this.polygonOffsetFactor = 0;
  7369. this.polygonOffsetUnits = 0;
  7370. this.alphaTest = 0;
  7371. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7372. this.visible = true;
  7373. this.needsUpdate = true;
  7374. };
  7375. THREE.Material.prototype = {
  7376. constructor: THREE.Material,
  7377. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7378. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7379. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7380. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7381. setValues: function ( values ) {
  7382. if ( values === undefined ) return;
  7383. for ( var key in values ) {
  7384. var newValue = values[ key ];
  7385. if ( newValue === undefined ) {
  7386. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7387. continue;
  7388. }
  7389. if ( key in this ) {
  7390. var currentValue = this[ key ];
  7391. if ( currentValue instanceof THREE.Color ) {
  7392. currentValue.set( newValue );
  7393. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7394. currentValue.copy( newValue );
  7395. } else if ( key == 'overdraw') {
  7396. // ensure overdraw is backwards-compatable with legacy boolean type
  7397. this[ key ] = Number(newValue);
  7398. } else {
  7399. this[ key ] = newValue;
  7400. }
  7401. }
  7402. }
  7403. },
  7404. clone: function ( material ) {
  7405. if ( material === undefined ) material = new THREE.Material();
  7406. material.name = this.name;
  7407. material.side = this.side;
  7408. material.opacity = this.opacity;
  7409. material.transparent = this.transparent;
  7410. material.blending = this.blending;
  7411. material.blendSrc = this.blendSrc;
  7412. material.blendDst = this.blendDst;
  7413. material.blendEquation = this.blendEquation;
  7414. material.depthTest = this.depthTest;
  7415. material.depthWrite = this.depthWrite;
  7416. material.polygonOffset = this.polygonOffset;
  7417. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7418. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7419. material.alphaTest = this.alphaTest;
  7420. material.overdraw = this.overdraw;
  7421. material.visible = this.visible;
  7422. return material;
  7423. },
  7424. dispose: function () {
  7425. this.dispatchEvent( { type: 'dispose' } );
  7426. }
  7427. };
  7428. /**
  7429. * @author mrdoob / http://mrdoob.com/
  7430. * @author alteredq / http://alteredqualia.com/
  7431. *
  7432. * parameters = {
  7433. * color: <hex>,
  7434. * opacity: <float>,
  7435. *
  7436. * blending: THREE.NormalBlending,
  7437. * depthTest: <bool>,
  7438. * depthWrite: <bool>,
  7439. *
  7440. * linewidth: <float>,
  7441. * linecap: "round",
  7442. * linejoin: "round",
  7443. *
  7444. * vertexColors: <bool>
  7445. *
  7446. * fog: <bool>
  7447. * }
  7448. */
  7449. THREE.LineBasicMaterial = function ( parameters ) {
  7450. THREE.Material.call( this );
  7451. this.color = new THREE.Color( 0xffffff );
  7452. this.linewidth = 1;
  7453. this.linecap = 'round';
  7454. this.linejoin = 'round';
  7455. this.vertexColors = false;
  7456. this.fog = true;
  7457. this.setValues( parameters );
  7458. };
  7459. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7460. THREE.LineBasicMaterial.prototype.clone = function () {
  7461. var material = new THREE.LineBasicMaterial();
  7462. THREE.Material.prototype.clone.call( this, material );
  7463. material.color.copy( this.color );
  7464. material.linewidth = this.linewidth;
  7465. material.linecap = this.linecap;
  7466. material.linejoin = this.linejoin;
  7467. material.vertexColors = this.vertexColors;
  7468. material.fog = this.fog;
  7469. return material;
  7470. };
  7471. /**
  7472. * @author alteredq / http://alteredqualia.com/
  7473. *
  7474. * parameters = {
  7475. * color: <hex>,
  7476. * opacity: <float>,
  7477. *
  7478. * blending: THREE.NormalBlending,
  7479. * depthTest: <bool>,
  7480. * depthWrite: <bool>,
  7481. *
  7482. * linewidth: <float>,
  7483. *
  7484. * scale: <float>,
  7485. * dashSize: <float>,
  7486. * gapSize: <float>,
  7487. *
  7488. * vertexColors: <bool>
  7489. *
  7490. * fog: <bool>
  7491. * }
  7492. */
  7493. THREE.LineDashedMaterial = function ( parameters ) {
  7494. THREE.Material.call( this );
  7495. this.color = new THREE.Color( 0xffffff );
  7496. this.linewidth = 1;
  7497. this.scale = 1;
  7498. this.dashSize = 3;
  7499. this.gapSize = 1;
  7500. this.vertexColors = false;
  7501. this.fog = true;
  7502. this.setValues( parameters );
  7503. };
  7504. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7505. THREE.LineDashedMaterial.prototype.clone = function () {
  7506. var material = new THREE.LineDashedMaterial();
  7507. THREE.Material.prototype.clone.call( this, material );
  7508. material.color.copy( this.color );
  7509. material.linewidth = this.linewidth;
  7510. material.scale = this.scale;
  7511. material.dashSize = this.dashSize;
  7512. material.gapSize = this.gapSize;
  7513. material.vertexColors = this.vertexColors;
  7514. material.fog = this.fog;
  7515. return material;
  7516. };
  7517. /**
  7518. * @author mrdoob / http://mrdoob.com/
  7519. * @author alteredq / http://alteredqualia.com/
  7520. *
  7521. * parameters = {
  7522. * color: <hex>,
  7523. * opacity: <float>,
  7524. * map: new THREE.Texture( <Image> ),
  7525. *
  7526. * lightMap: new THREE.Texture( <Image> ),
  7527. *
  7528. * specularMap: new THREE.Texture( <Image> ),
  7529. *
  7530. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7531. * combine: THREE.Multiply,
  7532. * reflectivity: <float>,
  7533. * refractionRatio: <float>,
  7534. *
  7535. * shading: THREE.SmoothShading,
  7536. * blending: THREE.NormalBlending,
  7537. * depthTest: <bool>,
  7538. * depthWrite: <bool>,
  7539. *
  7540. * wireframe: <boolean>,
  7541. * wireframeLinewidth: <float>,
  7542. *
  7543. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7544. *
  7545. * skinning: <bool>,
  7546. * morphTargets: <bool>,
  7547. *
  7548. * fog: <bool>
  7549. * }
  7550. */
  7551. THREE.MeshBasicMaterial = function ( parameters ) {
  7552. THREE.Material.call( this );
  7553. this.color = new THREE.Color( 0xffffff ); // emissive
  7554. this.map = null;
  7555. this.lightMap = null;
  7556. this.specularMap = null;
  7557. this.envMap = null;
  7558. this.combine = THREE.MultiplyOperation;
  7559. this.reflectivity = 1;
  7560. this.refractionRatio = 0.98;
  7561. this.fog = true;
  7562. this.shading = THREE.SmoothShading;
  7563. this.wireframe = false;
  7564. this.wireframeLinewidth = 1;
  7565. this.wireframeLinecap = 'round';
  7566. this.wireframeLinejoin = 'round';
  7567. this.vertexColors = THREE.NoColors;
  7568. this.skinning = false;
  7569. this.morphTargets = false;
  7570. this.setValues( parameters );
  7571. };
  7572. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7573. THREE.MeshBasicMaterial.prototype.clone = function () {
  7574. var material = new THREE.MeshBasicMaterial();
  7575. THREE.Material.prototype.clone.call( this, material );
  7576. material.color.copy( this.color );
  7577. material.map = this.map;
  7578. material.lightMap = this.lightMap;
  7579. material.specularMap = this.specularMap;
  7580. material.envMap = this.envMap;
  7581. material.combine = this.combine;
  7582. material.reflectivity = this.reflectivity;
  7583. material.refractionRatio = this.refractionRatio;
  7584. material.fog = this.fog;
  7585. material.shading = this.shading;
  7586. material.wireframe = this.wireframe;
  7587. material.wireframeLinewidth = this.wireframeLinewidth;
  7588. material.wireframeLinecap = this.wireframeLinecap;
  7589. material.wireframeLinejoin = this.wireframeLinejoin;
  7590. material.vertexColors = this.vertexColors;
  7591. material.skinning = this.skinning;
  7592. material.morphTargets = this.morphTargets;
  7593. return material;
  7594. };
  7595. /**
  7596. * @author mrdoob / http://mrdoob.com/
  7597. * @author alteredq / http://alteredqualia.com/
  7598. *
  7599. * parameters = {
  7600. * color: <hex>,
  7601. * ambient: <hex>,
  7602. * emissive: <hex>,
  7603. * opacity: <float>,
  7604. *
  7605. * map: new THREE.Texture( <Image> ),
  7606. *
  7607. * lightMap: new THREE.Texture( <Image> ),
  7608. *
  7609. * specularMap: new THREE.Texture( <Image> ),
  7610. *
  7611. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7612. * combine: THREE.Multiply,
  7613. * reflectivity: <float>,
  7614. * refractionRatio: <float>,
  7615. *
  7616. * shading: THREE.SmoothShading,
  7617. * blending: THREE.NormalBlending,
  7618. * depthTest: <bool>,
  7619. * depthWrite: <bool>,
  7620. *
  7621. * wireframe: <boolean>,
  7622. * wireframeLinewidth: <float>,
  7623. *
  7624. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7625. *
  7626. * skinning: <bool>,
  7627. * morphTargets: <bool>,
  7628. * morphNormals: <bool>,
  7629. *
  7630. * fog: <bool>
  7631. * }
  7632. */
  7633. THREE.MeshLambertMaterial = function ( parameters ) {
  7634. THREE.Material.call( this );
  7635. this.color = new THREE.Color( 0xffffff ); // diffuse
  7636. this.ambient = new THREE.Color( 0xffffff );
  7637. this.emissive = new THREE.Color( 0x000000 );
  7638. this.wrapAround = false;
  7639. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7640. this.map = null;
  7641. this.lightMap = null;
  7642. this.specularMap = null;
  7643. this.envMap = null;
  7644. this.combine = THREE.MultiplyOperation;
  7645. this.reflectivity = 1;
  7646. this.refractionRatio = 0.98;
  7647. this.fog = true;
  7648. this.shading = THREE.SmoothShading;
  7649. this.wireframe = false;
  7650. this.wireframeLinewidth = 1;
  7651. this.wireframeLinecap = 'round';
  7652. this.wireframeLinejoin = 'round';
  7653. this.vertexColors = THREE.NoColors;
  7654. this.skinning = false;
  7655. this.morphTargets = false;
  7656. this.morphNormals = false;
  7657. this.setValues( parameters );
  7658. };
  7659. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7660. THREE.MeshLambertMaterial.prototype.clone = function () {
  7661. var material = new THREE.MeshLambertMaterial();
  7662. THREE.Material.prototype.clone.call( this, material );
  7663. material.color.copy( this.color );
  7664. material.ambient.copy( this.ambient );
  7665. material.emissive.copy( this.emissive );
  7666. material.wrapAround = this.wrapAround;
  7667. material.wrapRGB.copy( this.wrapRGB );
  7668. material.map = this.map;
  7669. material.lightMap = this.lightMap;
  7670. material.specularMap = this.specularMap;
  7671. material.envMap = this.envMap;
  7672. material.combine = this.combine;
  7673. material.reflectivity = this.reflectivity;
  7674. material.refractionRatio = this.refractionRatio;
  7675. material.fog = this.fog;
  7676. material.shading = this.shading;
  7677. material.wireframe = this.wireframe;
  7678. material.wireframeLinewidth = this.wireframeLinewidth;
  7679. material.wireframeLinecap = this.wireframeLinecap;
  7680. material.wireframeLinejoin = this.wireframeLinejoin;
  7681. material.vertexColors = this.vertexColors;
  7682. material.skinning = this.skinning;
  7683. material.morphTargets = this.morphTargets;
  7684. material.morphNormals = this.morphNormals;
  7685. return material;
  7686. };
  7687. /**
  7688. * @author mrdoob / http://mrdoob.com/
  7689. * @author alteredq / http://alteredqualia.com/
  7690. *
  7691. * parameters = {
  7692. * color: <hex>,
  7693. * ambient: <hex>,
  7694. * emissive: <hex>,
  7695. * specular: <hex>,
  7696. * shininess: <float>,
  7697. * opacity: <float>,
  7698. *
  7699. * map: new THREE.Texture( <Image> ),
  7700. *
  7701. * lightMap: new THREE.Texture( <Image> ),
  7702. *
  7703. * bumpMap: new THREE.Texture( <Image> ),
  7704. * bumpScale: <float>,
  7705. *
  7706. * normalMap: new THREE.Texture( <Image> ),
  7707. * normalScale: <Vector2>,
  7708. *
  7709. * specularMap: new THREE.Texture( <Image> ),
  7710. *
  7711. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7712. * combine: THREE.Multiply,
  7713. * reflectivity: <float>,
  7714. * refractionRatio: <float>,
  7715. *
  7716. * shading: THREE.SmoothShading,
  7717. * blending: THREE.NormalBlending,
  7718. * depthTest: <bool>,
  7719. * depthWrite: <bool>,
  7720. *
  7721. * wireframe: <boolean>,
  7722. * wireframeLinewidth: <float>,
  7723. *
  7724. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7725. *
  7726. * skinning: <bool>,
  7727. * morphTargets: <bool>,
  7728. * morphNormals: <bool>,
  7729. *
  7730. * fog: <bool>
  7731. * }
  7732. */
  7733. THREE.MeshPhongMaterial = function ( parameters ) {
  7734. THREE.Material.call( this );
  7735. this.color = new THREE.Color( 0xffffff ); // diffuse
  7736. this.ambient = new THREE.Color( 0xffffff );
  7737. this.emissive = new THREE.Color( 0x000000 );
  7738. this.specular = new THREE.Color( 0x111111 );
  7739. this.shininess = 30;
  7740. this.metal = false;
  7741. this.perPixel = true;
  7742. this.wrapAround = false;
  7743. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7744. this.map = null;
  7745. this.lightMap = null;
  7746. this.bumpMap = null;
  7747. this.bumpScale = 1;
  7748. this.normalMap = null;
  7749. this.normalScale = new THREE.Vector2( 1, 1 );
  7750. this.specularMap = null;
  7751. this.envMap = null;
  7752. this.combine = THREE.MultiplyOperation;
  7753. this.reflectivity = 1;
  7754. this.refractionRatio = 0.98;
  7755. this.fog = true;
  7756. this.shading = THREE.SmoothShading;
  7757. this.wireframe = false;
  7758. this.wireframeLinewidth = 1;
  7759. this.wireframeLinecap = 'round';
  7760. this.wireframeLinejoin = 'round';
  7761. this.vertexColors = THREE.NoColors;
  7762. this.skinning = false;
  7763. this.morphTargets = false;
  7764. this.morphNormals = false;
  7765. this.setValues( parameters );
  7766. };
  7767. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7768. THREE.MeshPhongMaterial.prototype.clone = function () {
  7769. var material = new THREE.MeshPhongMaterial();
  7770. THREE.Material.prototype.clone.call( this, material );
  7771. material.color.copy( this.color );
  7772. material.ambient.copy( this.ambient );
  7773. material.emissive.copy( this.emissive );
  7774. material.specular.copy( this.specular );
  7775. material.shininess = this.shininess;
  7776. material.metal = this.metal;
  7777. material.perPixel = this.perPixel;
  7778. material.wrapAround = this.wrapAround;
  7779. material.wrapRGB.copy( this.wrapRGB );
  7780. material.map = this.map;
  7781. material.lightMap = this.lightMap;
  7782. material.bumpMap = this.bumpMap;
  7783. material.bumpScale = this.bumpScale;
  7784. material.normalMap = this.normalMap;
  7785. material.normalScale.copy( this.normalScale );
  7786. material.specularMap = this.specularMap;
  7787. material.envMap = this.envMap;
  7788. material.combine = this.combine;
  7789. material.reflectivity = this.reflectivity;
  7790. material.refractionRatio = this.refractionRatio;
  7791. material.fog = this.fog;
  7792. material.shading = this.shading;
  7793. material.wireframe = this.wireframe;
  7794. material.wireframeLinewidth = this.wireframeLinewidth;
  7795. material.wireframeLinecap = this.wireframeLinecap;
  7796. material.wireframeLinejoin = this.wireframeLinejoin;
  7797. material.vertexColors = this.vertexColors;
  7798. material.skinning = this.skinning;
  7799. material.morphTargets = this.morphTargets;
  7800. material.morphNormals = this.morphNormals;
  7801. return material;
  7802. };
  7803. /**
  7804. * @author mrdoob / http://mrdoob.com/
  7805. * @author alteredq / http://alteredqualia.com/
  7806. *
  7807. * parameters = {
  7808. * opacity: <float>,
  7809. *
  7810. * blending: THREE.NormalBlending,
  7811. * depthTest: <bool>,
  7812. * depthWrite: <bool>,
  7813. *
  7814. * wireframe: <boolean>,
  7815. * wireframeLinewidth: <float>
  7816. * }
  7817. */
  7818. THREE.MeshDepthMaterial = function ( parameters ) {
  7819. THREE.Material.call( this );
  7820. this.wireframe = false;
  7821. this.wireframeLinewidth = 1;
  7822. this.setValues( parameters );
  7823. };
  7824. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7825. THREE.MeshDepthMaterial.prototype.clone = function () {
  7826. var material = new THREE.MeshDepthMaterial();
  7827. THREE.Material.prototype.clone.call( this, material );
  7828. material.wireframe = this.wireframe;
  7829. material.wireframeLinewidth = this.wireframeLinewidth;
  7830. return material;
  7831. };
  7832. /**
  7833. * @author mrdoob / http://mrdoob.com/
  7834. *
  7835. * parameters = {
  7836. * opacity: <float>,
  7837. *
  7838. * shading: THREE.FlatShading,
  7839. * blending: THREE.NormalBlending,
  7840. * depthTest: <bool>,
  7841. * depthWrite: <bool>,
  7842. *
  7843. * wireframe: <boolean>,
  7844. * wireframeLinewidth: <float>
  7845. * }
  7846. */
  7847. THREE.MeshNormalMaterial = function ( parameters ) {
  7848. THREE.Material.call( this, parameters );
  7849. this.shading = THREE.FlatShading;
  7850. this.wireframe = false;
  7851. this.wireframeLinewidth = 1;
  7852. this.morphTargets = false;
  7853. this.setValues( parameters );
  7854. };
  7855. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7856. THREE.MeshNormalMaterial.prototype.clone = function () {
  7857. var material = new THREE.MeshNormalMaterial();
  7858. THREE.Material.prototype.clone.call( this, material );
  7859. material.shading = this.shading;
  7860. material.wireframe = this.wireframe;
  7861. material.wireframeLinewidth = this.wireframeLinewidth;
  7862. return material;
  7863. };
  7864. /**
  7865. * @author mrdoob / http://mrdoob.com/
  7866. */
  7867. THREE.MeshFaceMaterial = function ( materials ) {
  7868. this.materials = materials instanceof Array ? materials : [];
  7869. };
  7870. THREE.MeshFaceMaterial.prototype.clone = function () {
  7871. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7872. };
  7873. /**
  7874. * @author mrdoob / http://mrdoob.com/
  7875. * @author alteredq / http://alteredqualia.com/
  7876. *
  7877. * parameters = {
  7878. * color: <hex>,
  7879. * opacity: <float>,
  7880. * map: new THREE.Texture( <Image> ),
  7881. *
  7882. * size: <float>,
  7883. *
  7884. * blending: THREE.NormalBlending,
  7885. * depthTest: <bool>,
  7886. * depthWrite: <bool>,
  7887. *
  7888. * vertexColors: <bool>,
  7889. *
  7890. * fog: <bool>
  7891. * }
  7892. */
  7893. THREE.ParticleBasicMaterial = function ( parameters ) {
  7894. THREE.Material.call( this );
  7895. this.color = new THREE.Color( 0xffffff );
  7896. this.map = null;
  7897. this.size = 1;
  7898. this.sizeAttenuation = true;
  7899. this.vertexColors = false;
  7900. this.fog = true;
  7901. this.setValues( parameters );
  7902. };
  7903. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7904. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7905. var material = new THREE.ParticleBasicMaterial();
  7906. THREE.Material.prototype.clone.call( this, material );
  7907. material.color.copy( this.color );
  7908. material.map = this.map;
  7909. material.size = this.size;
  7910. material.sizeAttenuation = this.sizeAttenuation;
  7911. material.vertexColors = this.vertexColors;
  7912. material.fog = this.fog;
  7913. return material;
  7914. };
  7915. /**
  7916. * @author mrdoob / http://mrdoob.com/
  7917. *
  7918. * parameters = {
  7919. * color: <hex>,
  7920. * program: <function>,
  7921. * opacity: <float>,
  7922. * blending: THREE.NormalBlending
  7923. * }
  7924. */
  7925. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7926. THREE.Material.call( this );
  7927. this.color = new THREE.Color( 0xffffff );
  7928. this.program = function ( context, color ) {};
  7929. this.setValues( parameters );
  7930. };
  7931. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7932. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7933. var material = new THREE.ParticleCanvasMaterial();
  7934. THREE.Material.prototype.clone.call( this, material );
  7935. material.color.copy( this.color );
  7936. material.program = this.program;
  7937. return material;
  7938. };
  7939. /**
  7940. * @author alteredq / http://alteredqualia.com/
  7941. *
  7942. * parameters = {
  7943. * fragmentShader: <string>,
  7944. * vertexShader: <string>,
  7945. *
  7946. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7947. *
  7948. * defines: { "label" : "value" },
  7949. *
  7950. * shading: THREE.SmoothShading,
  7951. * blending: THREE.NormalBlending,
  7952. * depthTest: <bool>,
  7953. * depthWrite: <bool>,
  7954. *
  7955. * wireframe: <boolean>,
  7956. * wireframeLinewidth: <float>,
  7957. *
  7958. * lights: <bool>,
  7959. *
  7960. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7961. *
  7962. * skinning: <bool>,
  7963. * morphTargets: <bool>,
  7964. * morphNormals: <bool>,
  7965. *
  7966. * fog: <bool>
  7967. * }
  7968. */
  7969. THREE.ShaderMaterial = function ( parameters ) {
  7970. THREE.Material.call( this );
  7971. this.fragmentShader = "void main() {}";
  7972. this.vertexShader = "void main() {}";
  7973. this.uniforms = {};
  7974. this.defines = {};
  7975. this.attributes = null;
  7976. this.shading = THREE.SmoothShading;
  7977. this.linewidth = 1;
  7978. this.wireframe = false;
  7979. this.wireframeLinewidth = 1;
  7980. this.fog = false; // set to use scene fog
  7981. this.lights = false; // set to use scene lights
  7982. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7983. this.skinning = false; // set to use skinning attribute streams
  7984. this.morphTargets = false; // set to use morph targets
  7985. this.morphNormals = false; // set to use morph normals
  7986. this.setValues( parameters );
  7987. };
  7988. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7989. THREE.ShaderMaterial.prototype.clone = function () {
  7990. var material = new THREE.ShaderMaterial();
  7991. THREE.Material.prototype.clone.call( this, material );
  7992. material.fragmentShader = this.fragmentShader;
  7993. material.vertexShader = this.vertexShader;
  7994. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7995. material.attributes = this.attributes;
  7996. material.defines = this.defines;
  7997. material.shading = this.shading;
  7998. material.wireframe = this.wireframe;
  7999. material.wireframeLinewidth = this.wireframeLinewidth;
  8000. material.fog = this.fog;
  8001. material.lights = this.lights;
  8002. material.vertexColors = this.vertexColors;
  8003. material.skinning = this.skinning;
  8004. material.morphTargets = this.morphTargets;
  8005. material.morphNormals = this.morphNormals;
  8006. return material;
  8007. };
  8008. /**
  8009. * @author alteredq / http://alteredqualia.com/
  8010. *
  8011. * parameters = {
  8012. * color: <hex>,
  8013. * opacity: <float>,
  8014. * map: new THREE.Texture( <Image> ),
  8015. *
  8016. * blending: THREE.NormalBlending,
  8017. * depthTest: <bool>,
  8018. * depthWrite: <bool>,
  8019. *
  8020. * useScreenCoordinates: <bool>,
  8021. * sizeAttenuation: <bool>,
  8022. * scaleByViewport: <bool>,
  8023. * alignment: THREE.SpriteAlignment.center,
  8024. *
  8025. * uvOffset: new THREE.Vector2(),
  8026. * uvScale: new THREE.Vector2(),
  8027. *
  8028. * fog: <bool>
  8029. * }
  8030. */
  8031. THREE.SpriteMaterial = function ( parameters ) {
  8032. THREE.Material.call( this );
  8033. // defaults
  8034. this.color = new THREE.Color( 0xffffff );
  8035. this.map = new THREE.Texture();
  8036. this.useScreenCoordinates = true;
  8037. this.depthTest = !this.useScreenCoordinates;
  8038. this.sizeAttenuation = !this.useScreenCoordinates;
  8039. this.scaleByViewport = !this.sizeAttenuation;
  8040. this.alignment = THREE.SpriteAlignment.center.clone();
  8041. this.fog = false;
  8042. this.uvOffset = new THREE.Vector2( 0, 0 );
  8043. this.uvScale = new THREE.Vector2( 1, 1 );
  8044. // set parameters
  8045. this.setValues( parameters );
  8046. // override coupled defaults if not specified explicitly by parameters
  8047. parameters = parameters || {};
  8048. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  8049. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  8050. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  8051. };
  8052. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8053. THREE.SpriteMaterial.prototype.clone = function () {
  8054. var material = new THREE.SpriteMaterial();
  8055. THREE.Material.prototype.clone.call( this, material );
  8056. material.color.copy( this.color );
  8057. material.map = this.map;
  8058. material.useScreenCoordinates = this.useScreenCoordinates;
  8059. material.sizeAttenuation = this.sizeAttenuation;
  8060. material.scaleByViewport = this.scaleByViewport;
  8061. material.alignment.copy( this.alignment );
  8062. material.uvOffset.copy( this.uvOffset );
  8063. material.uvScale.copy( this.uvScale );
  8064. material.fog = this.fog;
  8065. return material;
  8066. };
  8067. // Alignment enums
  8068. THREE.SpriteAlignment = {};
  8069. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  8070. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  8071. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  8072. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  8073. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  8074. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  8075. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  8076. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  8077. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  8078. /**
  8079. * @author mrdoob / http://mrdoob.com/
  8080. * @author alteredq / http://alteredqualia.com/
  8081. * @author szimek / https://github.com/szimek/
  8082. */
  8083. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8084. this.id = THREE.Math.generateUUID();
  8085. this.name = '';
  8086. this.image = image;
  8087. this.mipmaps = [];
  8088. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8089. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8090. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8091. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8092. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8093. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8094. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8095. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8096. this.offset = new THREE.Vector2( 0, 0 );
  8097. this.repeat = new THREE.Vector2( 1, 1 );
  8098. this.generateMipmaps = true;
  8099. this.premultiplyAlpha = false;
  8100. this.flipY = true;
  8101. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8102. this.needsUpdate = false;
  8103. this.onUpdate = null;
  8104. };
  8105. THREE.Texture.prototype = {
  8106. constructor: THREE.Texture,
  8107. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  8108. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  8109. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  8110. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  8111. clone: function ( texture ) {
  8112. if ( texture === undefined ) texture = new THREE.Texture();
  8113. texture.image = this.image;
  8114. texture.mipmaps = this.mipmaps.slice(0);
  8115. texture.mapping = this.mapping;
  8116. texture.wrapS = this.wrapS;
  8117. texture.wrapT = this.wrapT;
  8118. texture.magFilter = this.magFilter;
  8119. texture.minFilter = this.minFilter;
  8120. texture.anisotropy = this.anisotropy;
  8121. texture.format = this.format;
  8122. texture.type = this.type;
  8123. texture.offset.copy( this.offset );
  8124. texture.repeat.copy( this.repeat );
  8125. texture.generateMipmaps = this.generateMipmaps;
  8126. texture.premultiplyAlpha = this.premultiplyAlpha;
  8127. texture.flipY = this.flipY;
  8128. texture.unpackAlignment = this.unpackAlignment;
  8129. return texture;
  8130. },
  8131. dispose: function () {
  8132. this.dispatchEvent( { type: 'dispose' } );
  8133. }
  8134. };
  8135. /**
  8136. * @author alteredq / http://alteredqualia.com/
  8137. */
  8138. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8139. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8140. this.image = { width: width, height: height };
  8141. this.mipmaps = mipmaps;
  8142. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8143. };
  8144. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8145. THREE.CompressedTexture.prototype.clone = function () {
  8146. var texture = new THREE.CompressedTexture();
  8147. THREE.Texture.prototype.clone.call( this, texture );
  8148. return texture;
  8149. };
  8150. /**
  8151. * @author alteredq / http://alteredqualia.com/
  8152. */
  8153. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8154. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8155. this.image = { data: data, width: width, height: height };
  8156. };
  8157. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8158. THREE.DataTexture.prototype.clone = function () {
  8159. var texture = new THREE.DataTexture();
  8160. THREE.Texture.prototype.clone.call( this, texture );
  8161. return texture;
  8162. };
  8163. /**
  8164. * @author mrdoob / http://mrdoob.com/
  8165. */
  8166. THREE.Particle = function ( material ) {
  8167. THREE.Object3D.call( this );
  8168. this.material = material;
  8169. };
  8170. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  8171. THREE.Particle.prototype.clone = function ( object ) {
  8172. if ( object === undefined ) object = new THREE.Particle( this.material );
  8173. THREE.Object3D.prototype.clone.call( this, object );
  8174. return object;
  8175. };
  8176. /**
  8177. * @author alteredq / http://alteredqualia.com/
  8178. */
  8179. THREE.ParticleSystem = function ( geometry, material ) {
  8180. THREE.Object3D.call( this );
  8181. this.geometry = geometry;
  8182. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  8183. this.sortParticles = false;
  8184. if ( this.geometry ) {
  8185. // calc bound radius
  8186. if( this.geometry.boundingSphere === null ) {
  8187. this.geometry.computeBoundingSphere();
  8188. }
  8189. }
  8190. this.frustumCulled = false;
  8191. };
  8192. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8193. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8194. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8195. object.sortParticles = this.sortParticles;
  8196. THREE.Object3D.prototype.clone.call( this, object );
  8197. return object;
  8198. };
  8199. /**
  8200. * @author mrdoob / http://mrdoob.com/
  8201. */
  8202. THREE.Line = function ( geometry, material, type ) {
  8203. THREE.Object3D.call( this );
  8204. this.geometry = geometry;
  8205. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8206. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8207. if ( this.geometry ) {
  8208. if ( ! this.geometry.boundingSphere ) {
  8209. this.geometry.computeBoundingSphere();
  8210. }
  8211. }
  8212. };
  8213. THREE.LineStrip = 0;
  8214. THREE.LinePieces = 1;
  8215. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8216. THREE.Line.prototype.clone = function ( object ) {
  8217. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8218. THREE.Object3D.prototype.clone.call( this, object );
  8219. return object;
  8220. };
  8221. /**
  8222. * @author mrdoob / http://mrdoob.com/
  8223. * @author alteredq / http://alteredqualia.com/
  8224. * @author mikael emtinger / http://gomo.se/
  8225. * @author jonobr1 / http://jonobr1.com/
  8226. */
  8227. THREE.Mesh = function ( geometry, material ) {
  8228. THREE.Object3D.call( this );
  8229. this.geometry = null;
  8230. this.material = null;
  8231. this.setGeometry( geometry );
  8232. this.setMaterial( material );
  8233. };
  8234. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8235. THREE.Mesh.prototype.setGeometry = function ( geometry ) {
  8236. if ( geometry !== undefined ) {
  8237. this.geometry = geometry;
  8238. if ( this.geometry.boundingSphere === null ) {
  8239. this.geometry.computeBoundingSphere();
  8240. }
  8241. this.updateMorphTargets();
  8242. }
  8243. };
  8244. THREE.Mesh.prototype.setMaterial = function ( material ) {
  8245. if ( material !== undefined ) {
  8246. this.material = material;
  8247. } else {
  8248. this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  8249. }
  8250. };
  8251. THREE.Mesh.prototype.updateMorphTargets = function () {
  8252. if ( this.geometry.morphTargets.length > 0 ) {
  8253. this.morphTargetBase = -1;
  8254. this.morphTargetForcedOrder = [];
  8255. this.morphTargetInfluences = [];
  8256. this.morphTargetDictionary = {};
  8257. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8258. this.morphTargetInfluences.push( 0 );
  8259. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8260. }
  8261. }
  8262. };
  8263. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8264. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8265. return this.morphTargetDictionary[ name ];
  8266. }
  8267. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8268. return 0;
  8269. };
  8270. THREE.Mesh.prototype.clone = function ( object ) {
  8271. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8272. THREE.Object3D.prototype.clone.call( this, object );
  8273. return object;
  8274. };
  8275. /**
  8276. * @author mikael emtinger / http://gomo.se/
  8277. * @author alteredq / http://alteredqualia.com/
  8278. */
  8279. THREE.Bone = function( belongsToSkin ) {
  8280. THREE.Object3D.call( this );
  8281. this.skin = belongsToSkin;
  8282. this.skinMatrix = new THREE.Matrix4();
  8283. };
  8284. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8285. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8286. // update local
  8287. if ( this.matrixAutoUpdate ) {
  8288. forceUpdate |= this.updateMatrix();
  8289. }
  8290. // update skin matrix
  8291. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8292. if( parentSkinMatrix ) {
  8293. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8294. } else {
  8295. this.skinMatrix.copy( this.matrix );
  8296. }
  8297. this.matrixWorldNeedsUpdate = false;
  8298. forceUpdate = true;
  8299. }
  8300. // update children
  8301. var child, i, l = this.children.length;
  8302. for ( i = 0; i < l; i ++ ) {
  8303. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8304. }
  8305. };
  8306. /**
  8307. * @author mikael emtinger / http://gomo.se/
  8308. * @author alteredq / http://alteredqualia.com/
  8309. */
  8310. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8311. THREE.Mesh.call( this, geometry, material );
  8312. //
  8313. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8314. // init bones
  8315. this.identityMatrix = new THREE.Matrix4();
  8316. this.bones = [];
  8317. this.boneMatrices = [];
  8318. var b, bone, gbone, p, q, s;
  8319. if ( this.geometry && this.geometry.bones !== undefined ) {
  8320. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8321. gbone = this.geometry.bones[ b ];
  8322. p = gbone.pos;
  8323. q = gbone.rotq;
  8324. s = gbone.scl;
  8325. bone = this.addBone();
  8326. bone.name = gbone.name;
  8327. bone.position.set( p[0], p[1], p[2] );
  8328. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8329. if ( s !== undefined ) {
  8330. bone.scale.set( s[0], s[1], s[2] );
  8331. } else {
  8332. bone.scale.set( 1, 1, 1 );
  8333. }
  8334. }
  8335. for ( b = 0; b < this.bones.length; b ++ ) {
  8336. gbone = this.geometry.bones[ b ];
  8337. bone = this.bones[ b ];
  8338. if ( gbone.parent === -1 ) {
  8339. this.add( bone );
  8340. } else {
  8341. this.bones[ gbone.parent ].add( bone );
  8342. }
  8343. }
  8344. //
  8345. var nBones = this.bones.length;
  8346. if ( this.useVertexTexture ) {
  8347. // layout (1 matrix = 4 pixels)
  8348. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8349. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8350. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8351. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8352. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8353. var size;
  8354. if ( nBones > 256 )
  8355. size = 64;
  8356. else if ( nBones > 64 )
  8357. size = 32;
  8358. else if ( nBones > 16 )
  8359. size = 16;
  8360. else
  8361. size = 8;
  8362. this.boneTextureWidth = size;
  8363. this.boneTextureHeight = size;
  8364. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8365. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8366. this.boneTexture.minFilter = THREE.NearestFilter;
  8367. this.boneTexture.magFilter = THREE.NearestFilter;
  8368. this.boneTexture.generateMipmaps = false;
  8369. this.boneTexture.flipY = false;
  8370. } else {
  8371. this.boneMatrices = new Float32Array( 16 * nBones );
  8372. }
  8373. this.pose();
  8374. }
  8375. };
  8376. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8377. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8378. if ( bone === undefined ) {
  8379. bone = new THREE.Bone( this );
  8380. }
  8381. this.bones.push( bone );
  8382. return bone;
  8383. };
  8384. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8385. var offsetMatrix = new THREE.Matrix4();
  8386. return function ( force ) {
  8387. this.matrixAutoUpdate && this.updateMatrix();
  8388. // update matrixWorld
  8389. if ( this.matrixWorldNeedsUpdate || force ) {
  8390. if ( this.parent ) {
  8391. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8392. } else {
  8393. this.matrixWorld.copy( this.matrix );
  8394. }
  8395. this.matrixWorldNeedsUpdate = false;
  8396. force = true;
  8397. }
  8398. // update children
  8399. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8400. var child = this.children[ i ];
  8401. if ( child instanceof THREE.Bone ) {
  8402. child.update( this.identityMatrix, false );
  8403. } else {
  8404. child.updateMatrixWorld( true );
  8405. }
  8406. }
  8407. // make a snapshot of the bones' rest position
  8408. if ( this.boneInverses == undefined ) {
  8409. this.boneInverses = [];
  8410. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8411. var inverse = new THREE.Matrix4();
  8412. inverse.getInverse( this.bones[ b ].skinMatrix );
  8413. this.boneInverses.push( inverse );
  8414. }
  8415. }
  8416. // flatten bone matrices to array
  8417. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8418. // compute the offset between the current and the original transform;
  8419. // TODO: we could get rid of this multiplication step if the skinMatrix
  8420. // was already representing the offset; however, this requires some
  8421. // major changes to the animation system
  8422. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8423. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8424. }
  8425. if ( this.useVertexTexture ) {
  8426. this.boneTexture.needsUpdate = true;
  8427. }
  8428. };
  8429. }();
  8430. THREE.SkinnedMesh.prototype.pose = function () {
  8431. this.updateMatrixWorld( true );
  8432. this.normalizeSkinWeights();
  8433. };
  8434. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8435. if ( this.geometry instanceof THREE.Geometry ) {
  8436. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8437. var sw = this.geometry.skinWeights[ i ];
  8438. var scale = 1.0 / sw.lengthManhattan();
  8439. if ( scale !== Infinity ) {
  8440. sw.multiplyScalar( scale );
  8441. } else {
  8442. sw.set( 1 ); // this will be normalized by the shader anyway
  8443. }
  8444. }
  8445. } else {
  8446. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8447. }
  8448. };
  8449. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8450. if ( object === undefined ) {
  8451. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8452. }
  8453. THREE.Mesh.prototype.clone.call( this, object );
  8454. return object;
  8455. };
  8456. /**
  8457. * @author alteredq / http://alteredqualia.com/
  8458. */
  8459. THREE.MorphAnimMesh = function ( geometry, material ) {
  8460. THREE.Mesh.call( this, geometry, material );
  8461. // API
  8462. this.duration = 1000; // milliseconds
  8463. this.mirroredLoop = false;
  8464. this.time = 0;
  8465. // internals
  8466. this.lastKeyframe = 0;
  8467. this.currentKeyframe = 0;
  8468. this.direction = 1;
  8469. this.directionBackwards = false;
  8470. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8471. };
  8472. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8473. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8474. this.startKeyframe = start;
  8475. this.endKeyframe = end;
  8476. this.length = this.endKeyframe - this.startKeyframe + 1;
  8477. };
  8478. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8479. this.direction = 1;
  8480. this.directionBackwards = false;
  8481. };
  8482. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8483. this.direction = -1;
  8484. this.directionBackwards = true;
  8485. };
  8486. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8487. var geometry = this.geometry;
  8488. if ( ! geometry.animations ) geometry.animations = {};
  8489. var firstAnimation, animations = geometry.animations;
  8490. var pattern = /([a-z]+)(\d+)/;
  8491. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8492. var morph = geometry.morphTargets[ i ];
  8493. var parts = morph.name.match( pattern );
  8494. if ( parts && parts.length > 1 ) {
  8495. var label = parts[ 1 ];
  8496. var num = parts[ 2 ];
  8497. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8498. var animation = animations[ label ];
  8499. if ( i < animation.start ) animation.start = i;
  8500. if ( i > animation.end ) animation.end = i;
  8501. if ( ! firstAnimation ) firstAnimation = label;
  8502. }
  8503. }
  8504. geometry.firstAnimation = firstAnimation;
  8505. };
  8506. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8507. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8508. this.geometry.animations[ label ] = { start: start, end: end };
  8509. };
  8510. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8511. var animation = this.geometry.animations[ label ];
  8512. if ( animation ) {
  8513. this.setFrameRange( animation.start, animation.end );
  8514. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8515. this.time = 0;
  8516. } else {
  8517. console.warn( "animation[" + label + "] undefined" );
  8518. }
  8519. };
  8520. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8521. var frameTime = this.duration / this.length;
  8522. this.time += this.direction * delta;
  8523. if ( this.mirroredLoop ) {
  8524. if ( this.time > this.duration || this.time < 0 ) {
  8525. this.direction *= -1;
  8526. if ( this.time > this.duration ) {
  8527. this.time = this.duration;
  8528. this.directionBackwards = true;
  8529. }
  8530. if ( this.time < 0 ) {
  8531. this.time = 0;
  8532. this.directionBackwards = false;
  8533. }
  8534. }
  8535. } else {
  8536. this.time = this.time % this.duration;
  8537. if ( this.time < 0 ) this.time += this.duration;
  8538. }
  8539. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8540. if ( keyframe !== this.currentKeyframe ) {
  8541. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8542. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8543. this.morphTargetInfluences[ keyframe ] = 0;
  8544. this.lastKeyframe = this.currentKeyframe;
  8545. this.currentKeyframe = keyframe;
  8546. }
  8547. var mix = ( this.time % frameTime ) / frameTime;
  8548. if ( this.directionBackwards ) {
  8549. mix = 1 - mix;
  8550. }
  8551. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8552. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8553. };
  8554. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8555. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8556. object.duration = this.duration;
  8557. object.mirroredLoop = this.mirroredLoop;
  8558. object.time = this.time;
  8559. object.lastKeyframe = this.lastKeyframe;
  8560. object.currentKeyframe = this.currentKeyframe;
  8561. object.direction = this.direction;
  8562. object.directionBackwards = this.directionBackwards;
  8563. THREE.Mesh.prototype.clone.call( this, object );
  8564. return object;
  8565. };
  8566. /**
  8567. * @author alteredq / http://alteredqualia.com/
  8568. */
  8569. THREE.Ribbon = function ( geometry, material ) {
  8570. THREE.Object3D.call( this );
  8571. this.geometry = geometry;
  8572. this.material = material;
  8573. };
  8574. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8575. THREE.Ribbon.prototype.clone = function ( object ) {
  8576. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8577. THREE.Object3D.prototype.clone.call( this, object );
  8578. return object;
  8579. };
  8580. /**
  8581. * @author mikael emtinger / http://gomo.se/
  8582. * @author alteredq / http://alteredqualia.com/
  8583. * @author mrdoob / http://mrdoob.com/
  8584. */
  8585. THREE.LOD = function () {
  8586. THREE.Object3D.call( this );
  8587. this.objects = [];
  8588. };
  8589. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8590. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8591. if ( distance === undefined ) distance = 0;
  8592. distance = Math.abs( distance );
  8593. for ( var l = 0; l < this.objects.length; l ++ ) {
  8594. if ( distance < this.objects[ l ].distance ) {
  8595. break;
  8596. }
  8597. }
  8598. this.objects.splice( l, 0, { distance: distance, object: object } );
  8599. this.add( object );
  8600. };
  8601. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8602. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8603. if ( distance < this.objects[ i ].distance ) {
  8604. break;
  8605. }
  8606. }
  8607. return this.objects[ i - 1 ].object;
  8608. };
  8609. THREE.LOD.prototype.update = function () {
  8610. var v1 = new THREE.Vector3();
  8611. var v2 = new THREE.Vector3();
  8612. return function ( camera ) {
  8613. if ( this.objects.length > 1 ) {
  8614. v1.getPositionFromMatrix( camera.matrixWorld );
  8615. v2.getPositionFromMatrix( this.matrixWorld );
  8616. var distance = v1.distanceTo( v2 );
  8617. this.objects[ 0 ].object.visible = true;
  8618. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8619. if ( distance >= this.objects[ i ].distance ) {
  8620. this.objects[ i - 1 ].object.visible = false;
  8621. this.objects[ i ].object.visible = true;
  8622. } else {
  8623. break;
  8624. }
  8625. }
  8626. for( ; i < l; i ++ ) {
  8627. this.objects[ i ].object.visible = false;
  8628. }
  8629. }
  8630. };
  8631. }();
  8632. THREE.LOD.prototype.clone = function () {
  8633. // TODO
  8634. };
  8635. /**
  8636. * @author mikael emtinger / http://gomo.se/
  8637. * @author alteredq / http://alteredqualia.com/
  8638. */
  8639. THREE.Sprite = function ( material ) {
  8640. THREE.Object3D.call( this );
  8641. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8642. this.rotation3d = this.rotation;
  8643. this.rotation = 0;
  8644. };
  8645. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8646. /*
  8647. * Custom update matrix
  8648. */
  8649. THREE.Sprite.prototype.updateMatrix = function () {
  8650. this.rotation3d.set( 0, 0, this.rotation, this.rotation3d.order );
  8651. this.quaternion.setFromEuler( this.rotation3d );
  8652. this.matrix.compose( this.position, this.quaternion, this.scale );
  8653. this.matrixWorldNeedsUpdate = true;
  8654. };
  8655. THREE.Sprite.prototype.clone = function ( object ) {
  8656. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8657. THREE.Object3D.prototype.clone.call( this, object );
  8658. return object;
  8659. };
  8660. /**
  8661. * @author mrdoob / http://mrdoob.com/
  8662. */
  8663. THREE.Scene = function () {
  8664. THREE.Object3D.call( this );
  8665. this.fog = null;
  8666. this.overrideMaterial = null;
  8667. this.autoUpdate = true; // checked by the renderer
  8668. this.matrixAutoUpdate = false;
  8669. this.__objects = [];
  8670. this.__lights = [];
  8671. this.__objectsAdded = [];
  8672. this.__objectsRemoved = [];
  8673. };
  8674. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8675. THREE.Scene.prototype.__addObject = function ( object ) {
  8676. if ( object instanceof THREE.Light ) {
  8677. if ( this.__lights.indexOf( object ) === - 1 ) {
  8678. this.__lights.push( object );
  8679. }
  8680. if ( object.target && object.target.parent === undefined ) {
  8681. this.add( object.target );
  8682. }
  8683. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8684. if ( this.__objects.indexOf( object ) === - 1 ) {
  8685. this.__objects.push( object );
  8686. this.__objectsAdded.push( object );
  8687. // check if previously removed
  8688. var i = this.__objectsRemoved.indexOf( object );
  8689. if ( i !== -1 ) {
  8690. this.__objectsRemoved.splice( i, 1 );
  8691. }
  8692. }
  8693. }
  8694. for ( var c = 0; c < object.children.length; c ++ ) {
  8695. this.__addObject( object.children[ c ] );
  8696. }
  8697. };
  8698. THREE.Scene.prototype.__removeObject = function ( object ) {
  8699. if ( object instanceof THREE.Light ) {
  8700. var i = this.__lights.indexOf( object );
  8701. if ( i !== -1 ) {
  8702. this.__lights.splice( i, 1 );
  8703. }
  8704. } else if ( !( object instanceof THREE.Camera ) ) {
  8705. var i = this.__objects.indexOf( object );
  8706. if( i !== -1 ) {
  8707. this.__objects.splice( i, 1 );
  8708. this.__objectsRemoved.push( object );
  8709. // check if previously added
  8710. var ai = this.__objectsAdded.indexOf( object );
  8711. if ( ai !== -1 ) {
  8712. this.__objectsAdded.splice( ai, 1 );
  8713. }
  8714. }
  8715. }
  8716. for ( var c = 0; c < object.children.length; c ++ ) {
  8717. this.__removeObject( object.children[ c ] );
  8718. }
  8719. };
  8720. THREE.Scene.prototype.clone = function ( object ) {
  8721. if ( object === undefined ) object = new THREE.Scene();
  8722. THREE.Object3D.prototype.clone.call(this, object);
  8723. if ( this.fog !== null ) object.fog = this.fog.clone();
  8724. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8725. object.autoUpdate = this.autoUpdate;
  8726. object.matrixAutoUpdate = this.matrixAutoUpdate;
  8727. return object;
  8728. };
  8729. /**
  8730. * @author mrdoob / http://mrdoob.com/
  8731. * @author alteredq / http://alteredqualia.com/
  8732. */
  8733. THREE.Fog = function ( hex, near, far ) {
  8734. this.name = '';
  8735. this.color = new THREE.Color( hex );
  8736. this.near = ( near !== undefined ) ? near : 1;
  8737. this.far = ( far !== undefined ) ? far : 1000;
  8738. };
  8739. THREE.Fog.prototype.clone = function () {
  8740. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8741. };
  8742. /**
  8743. * @author mrdoob / http://mrdoob.com/
  8744. * @author alteredq / http://alteredqualia.com/
  8745. */
  8746. THREE.FogExp2 = function ( hex, density ) {
  8747. this.name = '';
  8748. this.color = new THREE.Color( hex );
  8749. this.density = ( density !== undefined ) ? density : 0.00025;
  8750. };
  8751. THREE.FogExp2.prototype.clone = function () {
  8752. return new THREE.FogExp2( this.color.getHex(), this.density );
  8753. };
  8754. /**
  8755. * @author mrdoob / http://mrdoob.com/
  8756. */
  8757. THREE.CanvasRenderer = function ( parameters ) {
  8758. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8759. var smoothstep = THREE.Math.smoothstep;
  8760. parameters = parameters || {};
  8761. var _this = this,
  8762. _renderData, _elements, _lights,
  8763. _projector = new THREE.Projector(),
  8764. _canvas = parameters.canvas !== undefined
  8765. ? parameters.canvas
  8766. : document.createElement( 'canvas' ),
  8767. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8768. _context = _canvas.getContext( '2d' ),
  8769. _clearColor = new THREE.Color( 0x000000 ),
  8770. _clearAlpha = 0,
  8771. _contextGlobalAlpha = 1,
  8772. _contextGlobalCompositeOperation = 0,
  8773. _contextStrokeStyle = null,
  8774. _contextFillStyle = null,
  8775. _contextLineWidth = null,
  8776. _contextLineCap = null,
  8777. _contextLineJoin = null,
  8778. _contextDashSize = null,
  8779. _contextGapSize = 0,
  8780. _camera,
  8781. _v1, _v2, _v3, _v4,
  8782. _v5 = new THREE.RenderableVertex(),
  8783. _v6 = new THREE.RenderableVertex(),
  8784. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8785. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8786. _color = new THREE.Color(),
  8787. _color1 = new THREE.Color(),
  8788. _color2 = new THREE.Color(),
  8789. _color3 = new THREE.Color(),
  8790. _color4 = new THREE.Color(),
  8791. _diffuseColor = new THREE.Color(),
  8792. _emissiveColor = new THREE.Color(),
  8793. _lightColor = new THREE.Color(),
  8794. _patterns = {}, _imagedatas = {},
  8795. _near, _far,
  8796. _image, _uvs,
  8797. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8798. _clipBox = new THREE.Box2(),
  8799. _clearBox = new THREE.Box2(),
  8800. _elemBox = new THREE.Box2(),
  8801. _ambientLight = new THREE.Color(),
  8802. _directionalLights = new THREE.Color(),
  8803. _pointLights = new THREE.Color(),
  8804. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8805. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8806. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8807. _pixelMap = document.createElement( 'canvas' );
  8808. _pixelMap.width = _pixelMap.height = 2;
  8809. _pixelMapContext = _pixelMap.getContext( '2d' );
  8810. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8811. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8812. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8813. _pixelMapData = _pixelMapImage.data;
  8814. _gradientMap = document.createElement( 'canvas' );
  8815. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8816. _gradientMapContext = _gradientMap.getContext( '2d' );
  8817. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8818. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8819. _gradientMapQuality --; // Fix UVs
  8820. // dash+gap fallbacks for Firefox and everything else
  8821. if ( _context.setLineDash === undefined ) {
  8822. if ( _context.mozDash !== undefined ) {
  8823. _context.setLineDash = function ( values ) {
  8824. _context.mozDash = values[ 0 ] !== null ? values : null;
  8825. }
  8826. } else {
  8827. _context.setLineDash = function () {}
  8828. }
  8829. }
  8830. this.domElement = _canvas;
  8831. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8832. ? parameters.devicePixelRatio
  8833. : window.devicePixelRatio !== undefined
  8834. ? window.devicePixelRatio
  8835. : 1;
  8836. this.autoClear = true;
  8837. this.sortObjects = true;
  8838. this.sortElements = true;
  8839. this.info = {
  8840. render: {
  8841. vertices: 0,
  8842. faces: 0
  8843. }
  8844. }
  8845. // WebGLRenderer compatibility
  8846. this.supportsVertexTextures = function () {};
  8847. this.setFaceCulling = function () {};
  8848. this.setSize = function ( width, height, updateStyle ) {
  8849. _canvasWidth = width * this.devicePixelRatio;
  8850. _canvasHeight = height * this.devicePixelRatio;
  8851. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8852. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8853. _canvas.width = _canvasWidth;
  8854. _canvas.height = _canvasHeight;
  8855. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  8856. _canvas.style.width = width + 'px';
  8857. _canvas.style.height = height + 'px';
  8858. }
  8859. _clipBox.set(
  8860. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8861. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8862. );
  8863. _clearBox.set(
  8864. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8865. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8866. );
  8867. _contextGlobalAlpha = 1;
  8868. _contextGlobalCompositeOperation = 0;
  8869. _contextStrokeStyle = null;
  8870. _contextFillStyle = null;
  8871. _contextLineWidth = null;
  8872. _contextLineCap = null;
  8873. _contextLineJoin = null;
  8874. };
  8875. this.setClearColor = function ( color, alpha ) {
  8876. _clearColor.set( color );
  8877. _clearAlpha = alpha !== undefined ? alpha : 1;
  8878. _clearBox.set(
  8879. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8880. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8881. );
  8882. };
  8883. this.setClearColorHex = function ( hex, alpha ) {
  8884. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  8885. this.setClearColor( hex, alpha );
  8886. };
  8887. this.getMaxAnisotropy = function () {
  8888. return 0;
  8889. };
  8890. this.clear = function () {
  8891. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8892. if ( _clearBox.empty() === false ) {
  8893. _clearBox.intersect( _clipBox );
  8894. _clearBox.expandByScalar( 2 );
  8895. if ( _clearAlpha < 1 ) {
  8896. _context.clearRect(
  8897. _clearBox.min.x | 0,
  8898. _clearBox.min.y | 0,
  8899. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8900. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8901. );
  8902. }
  8903. if ( _clearAlpha > 0 ) {
  8904. setBlending( THREE.NormalBlending );
  8905. setOpacity( 1 );
  8906. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  8907. _context.fillRect(
  8908. _clearBox.min.x | 0,
  8909. _clearBox.min.y | 0,
  8910. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8911. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8912. );
  8913. }
  8914. _clearBox.makeEmpty();
  8915. }
  8916. };
  8917. this.render = function ( scene, camera ) {
  8918. if ( camera instanceof THREE.Camera === false ) {
  8919. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8920. return;
  8921. }
  8922. if ( this.autoClear === true ) this.clear();
  8923. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8924. _this.info.render.vertices = 0;
  8925. _this.info.render.faces = 0;
  8926. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8927. _elements = _renderData.elements;
  8928. _lights = _renderData.lights;
  8929. _camera = camera;
  8930. /* DEBUG
  8931. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8932. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8933. */
  8934. calculateLights();
  8935. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8936. var element = _elements[ e ];
  8937. var material = element.material;
  8938. if ( material === undefined || material.visible === false ) continue;
  8939. _elemBox.makeEmpty();
  8940. if ( element instanceof THREE.RenderableParticle ) {
  8941. _v1 = element;
  8942. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8943. renderParticle( _v1, element, material );
  8944. } else if ( element instanceof THREE.RenderableLine ) {
  8945. _v1 = element.v1; _v2 = element.v2;
  8946. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8947. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8948. _elemBox.setFromPoints( [
  8949. _v1.positionScreen,
  8950. _v2.positionScreen
  8951. ] );
  8952. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8953. renderLine( _v1, _v2, element, material );
  8954. }
  8955. } else if ( element instanceof THREE.RenderableFace3 ) {
  8956. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8957. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8958. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8959. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8960. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8961. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8962. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8963. if ( material.overdraw > 0 ) {
  8964. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8965. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  8966. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  8967. }
  8968. _elemBox.setFromPoints( [
  8969. _v1.positionScreen,
  8970. _v2.positionScreen,
  8971. _v3.positionScreen
  8972. ] );
  8973. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8974. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8975. }
  8976. } else if ( element instanceof THREE.RenderableFace4 ) {
  8977. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8978. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8979. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8980. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8981. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8982. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8983. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8984. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8985. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8986. _v5.positionScreen.copy( _v2.positionScreen );
  8987. _v6.positionScreen.copy( _v4.positionScreen );
  8988. if ( material.overdraw > 0 ) {
  8989. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8990. expand( _v2.positionScreen, _v4.positionScreen, material.overdraw );
  8991. expand( _v4.positionScreen, _v1.positionScreen, material.overdraw );
  8992. expand( _v3.positionScreen, _v5.positionScreen, material.overdraw );
  8993. expand( _v3.positionScreen, _v6.positionScreen, material.overdraw );
  8994. }
  8995. _elemBox.setFromPoints( [
  8996. _v1.positionScreen,
  8997. _v2.positionScreen,
  8998. _v3.positionScreen,
  8999. _v4.positionScreen
  9000. ] );
  9001. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9002. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material );
  9003. }
  9004. }
  9005. /* DEBUG
  9006. setLineWidth( 1 );
  9007. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9008. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9009. */
  9010. _clearBox.union( _elemBox );
  9011. }
  9012. /* DEBUG
  9013. setLineWidth( 1 );
  9014. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9015. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9016. */
  9017. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9018. };
  9019. //
  9020. function calculateLights() {
  9021. _ambientLight.setRGB( 0, 0, 0 );
  9022. _directionalLights.setRGB( 0, 0, 0 );
  9023. _pointLights.setRGB( 0, 0, 0 );
  9024. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9025. var light = _lights[ l ];
  9026. var lightColor = light.color;
  9027. if ( light instanceof THREE.AmbientLight ) {
  9028. _ambientLight.add( lightColor );
  9029. } else if ( light instanceof THREE.DirectionalLight ) {
  9030. // for particles
  9031. _directionalLights.add( lightColor );
  9032. } else if ( light instanceof THREE.PointLight ) {
  9033. // for particles
  9034. _pointLights.add( lightColor );
  9035. }
  9036. }
  9037. }
  9038. function calculateLight( position, normal, color ) {
  9039. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9040. var light = _lights[ l ];
  9041. _lightColor.copy( light.color );
  9042. if ( light instanceof THREE.DirectionalLight ) {
  9043. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  9044. var amount = normal.dot( lightPosition );
  9045. if ( amount <= 0 ) continue;
  9046. amount *= light.intensity;
  9047. color.add( _lightColor.multiplyScalar( amount ) );
  9048. } else if ( light instanceof THREE.PointLight ) {
  9049. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  9050. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9051. if ( amount <= 0 ) continue;
  9052. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9053. if ( amount == 0 ) continue;
  9054. amount *= light.intensity;
  9055. color.add( _lightColor.multiplyScalar( amount ) );
  9056. }
  9057. }
  9058. }
  9059. function renderParticle( v1, element, material ) {
  9060. setOpacity( material.opacity );
  9061. setBlending( material.blending );
  9062. var width, height, scaleX, scaleY,
  9063. bitmap, bitmapWidth, bitmapHeight;
  9064. if ( material instanceof THREE.ParticleBasicMaterial ) {
  9065. if ( material.map === null ) {
  9066. scaleX = element.object.scale.x;
  9067. scaleY = element.object.scale.y;
  9068. // TODO: Be able to disable this
  9069. scaleX *= element.scale.x * _canvasWidthHalf;
  9070. scaleY *= element.scale.y * _canvasHeightHalf;
  9071. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  9072. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  9073. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9074. _elemBox.makeEmpty();
  9075. return;
  9076. }
  9077. setFillStyle( material.color.getStyle() );
  9078. _context.save();
  9079. _context.translate( v1.x, v1.y );
  9080. _context.rotate( - element.rotation );
  9081. _context.scale( scaleX, scaleY );
  9082. _context.fillRect( -1, -1, 2, 2 );
  9083. _context.restore();
  9084. } else {
  9085. bitmap = material.map.image;
  9086. bitmapWidth = bitmap.width >> 1;
  9087. bitmapHeight = bitmap.height >> 1;
  9088. scaleX = element.scale.x * _canvasWidthHalf;
  9089. scaleY = element.scale.y * _canvasHeightHalf;
  9090. width = scaleX * bitmapWidth;
  9091. height = scaleY * bitmapHeight;
  9092. // TODO: Rotations break this...
  9093. _elemBox.min.set( v1.x - width, v1.y - height );
  9094. _elemBox.max.set( v1.x + width, v1.y + height );
  9095. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9096. _elemBox.makeEmpty();
  9097. return;
  9098. }
  9099. _context.save();
  9100. _context.translate( v1.x, v1.y );
  9101. _context.rotate( - element.rotation );
  9102. _context.scale( scaleX, - scaleY );
  9103. _context.translate( - bitmapWidth, - bitmapHeight );
  9104. _context.drawImage( bitmap, 0, 0 );
  9105. _context.restore();
  9106. }
  9107. /* DEBUG
  9108. setStrokeStyle( 'rgb(255,255,0)' );
  9109. _context.beginPath();
  9110. _context.moveTo( v1.x - 10, v1.y );
  9111. _context.lineTo( v1.x + 10, v1.y );
  9112. _context.moveTo( v1.x, v1.y - 10 );
  9113. _context.lineTo( v1.x, v1.y + 10 );
  9114. _context.stroke();
  9115. */
  9116. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  9117. width = element.scale.x * _canvasWidthHalf;
  9118. height = element.scale.y * _canvasHeightHalf;
  9119. _elemBox.min.set( v1.x - width, v1.y - height );
  9120. _elemBox.max.set( v1.x + width, v1.y + height );
  9121. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9122. _elemBox.makeEmpty();
  9123. return;
  9124. }
  9125. setStrokeStyle( material.color.getStyle() );
  9126. setFillStyle( material.color.getStyle() );
  9127. _context.save();
  9128. _context.translate( v1.x, v1.y );
  9129. _context.rotate( - element.rotation );
  9130. _context.scale( width, height );
  9131. material.program( _context );
  9132. _context.restore();
  9133. }
  9134. }
  9135. function renderLine( v1, v2, element, material ) {
  9136. setOpacity( material.opacity );
  9137. setBlending( material.blending );
  9138. _context.beginPath();
  9139. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9140. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9141. if ( material instanceof THREE.LineBasicMaterial ) {
  9142. setLineWidth( material.linewidth );
  9143. setLineCap( material.linecap );
  9144. setLineJoin( material.linejoin );
  9145. if ( material.vertexColors !== THREE.VertexColors ) {
  9146. setStrokeStyle( material.color.getStyle() );
  9147. } else {
  9148. var colorStyle1 = element.vertexColors[0].getStyle();
  9149. var colorStyle2 = element.vertexColors[1].getStyle();
  9150. if ( colorStyle1 === colorStyle2 ) {
  9151. setStrokeStyle( colorStyle1 );
  9152. } else {
  9153. try {
  9154. var grad = _context.createLinearGradient(
  9155. v1.positionScreen.x,
  9156. v1.positionScreen.y,
  9157. v2.positionScreen.x,
  9158. v2.positionScreen.y
  9159. );
  9160. grad.addColorStop( 0, colorStyle1 );
  9161. grad.addColorStop( 1, colorStyle2 );
  9162. } catch ( exception ) {
  9163. grad = colorStyle1;
  9164. }
  9165. setStrokeStyle( grad );
  9166. }
  9167. }
  9168. _context.stroke();
  9169. _elemBox.expandByScalar( material.linewidth * 2 );
  9170. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9171. setLineWidth( material.linewidth );
  9172. setLineCap( material.linecap );
  9173. setLineJoin( material.linejoin );
  9174. setStrokeStyle( material.color.getStyle() );
  9175. setDashAndGap( material.dashSize, material.gapSize );
  9176. _context.stroke();
  9177. _elemBox.expandByScalar( material.linewidth * 2 );
  9178. setDashAndGap( null, null );
  9179. }
  9180. }
  9181. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9182. _this.info.render.vertices += 3;
  9183. _this.info.render.faces ++;
  9184. setOpacity( material.opacity );
  9185. setBlending( material.blending );
  9186. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9187. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9188. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9189. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9190. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9191. _diffuseColor.copy( material.color );
  9192. _emissiveColor.copy( material.emissive );
  9193. if ( material.vertexColors === THREE.FaceColors ) {
  9194. _diffuseColor.multiply( element.color );
  9195. }
  9196. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  9197. _color1.copy( _ambientLight );
  9198. _color2.copy( _ambientLight );
  9199. _color3.copy( _ambientLight );
  9200. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9201. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9202. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9203. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9204. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9205. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9206. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9207. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9208. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9209. } else {
  9210. _color.copy( _ambientLight );
  9211. calculateLight( element.centroidModel, element.normalModel, _color );
  9212. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9213. material.wireframe === true
  9214. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9215. : fillPath( _color );
  9216. }
  9217. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9218. if ( material.map !== null ) {
  9219. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9220. _uvs = element.uvs[ 0 ];
  9221. 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 );
  9222. }
  9223. } else if ( material.envMap !== null ) {
  9224. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9225. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9226. _uv1x = 0.5 * _vector3.x + 0.5;
  9227. _uv1y = 0.5 * _vector3.y + 0.5;
  9228. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9229. _uv2x = 0.5 * _vector3.x + 0.5;
  9230. _uv2y = 0.5 * _vector3.y + 0.5;
  9231. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9232. _uv3x = 0.5 * _vector3.x + 0.5;
  9233. _uv3y = 0.5 * _vector3.y + 0.5;
  9234. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9235. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  9236. }*/
  9237. } else {
  9238. _color.copy( material.color );
  9239. if ( material.vertexColors === THREE.FaceColors ) {
  9240. _color.multiply( element.color );
  9241. }
  9242. material.wireframe === true
  9243. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9244. : fillPath( _color );
  9245. }
  9246. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9247. _near = _camera.near;
  9248. _far = _camera.far;
  9249. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9250. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9251. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9252. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9253. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9254. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9255. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9256. var normal;
  9257. if ( material.shading == THREE.FlatShading ) {
  9258. normal = element.normalModelView;
  9259. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9260. material.wireframe === true
  9261. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9262. : fillPath( _color );
  9263. } else if ( material.shading == THREE.SmoothShading ) {
  9264. normal = element.vertexNormalsModelView[ uv1 ];
  9265. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9266. normal = element.vertexNormalsModelView[ uv2 ];
  9267. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9268. normal = element.vertexNormalsModelView[ uv3 ];
  9269. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9270. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9271. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9272. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9273. }
  9274. }
  9275. }
  9276. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  9277. _this.info.render.vertices += 4;
  9278. _this.info.render.faces ++;
  9279. setOpacity( material.opacity );
  9280. setBlending( material.blending );
  9281. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  9282. // Let renderFace3() handle this
  9283. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  9284. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  9285. return;
  9286. }
  9287. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9288. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9289. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9290. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  9291. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  9292. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  9293. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9294. _diffuseColor.copy( material.color );
  9295. _emissiveColor.copy( material.emissive );
  9296. if ( material.vertexColors === THREE.FaceColors ) {
  9297. _diffuseColor.multiply( element.color );
  9298. }
  9299. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  9300. _color1.copy( _ambientLight );
  9301. _color2.copy( _ambientLight );
  9302. _color3.copy( _ambientLight );
  9303. _color4.copy( _ambientLight );
  9304. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9305. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9306. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  9307. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  9308. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9309. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9310. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9311. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  9312. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9313. // TODO: UVs are incorrect, v4->v3?
  9314. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9315. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9316. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9317. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9318. } else {
  9319. _color.copy( _ambientLight );
  9320. calculateLight( element.centroidModel, element.normalModel, _color );
  9321. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9322. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9323. material.wireframe === true
  9324. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9325. : fillPath( _color );
  9326. }
  9327. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  9328. _color.copy( material.color );
  9329. if ( material.vertexColors === THREE.FaceColors ) {
  9330. _color.multiply( element.color );
  9331. }
  9332. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9333. material.wireframe === true
  9334. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9335. : fillPath( _color );
  9336. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9337. var normal;
  9338. if ( material.shading == THREE.FlatShading ) {
  9339. normal = element.normalModelView;
  9340. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9341. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9342. material.wireframe === true
  9343. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9344. : fillPath( _color );
  9345. } else if ( material.shading == THREE.SmoothShading ) {
  9346. normal = element.vertexNormalsModelView[ 0 ];
  9347. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9348. normal = element.vertexNormalsModelView[ 1 ];
  9349. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9350. normal = element.vertexNormalsModelView[ 3 ];
  9351. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9352. normal = element.vertexNormalsModelView[ 2 ];
  9353. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9354. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9355. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9356. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9357. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9358. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9359. }
  9360. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9361. _near = _camera.near;
  9362. _far = _camera.far;
  9363. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9364. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9365. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  9366. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9367. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9368. // TODO: UVs are incorrect, v4->v3?
  9369. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9370. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9371. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9372. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9373. }
  9374. }
  9375. //
  9376. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9377. _context.beginPath();
  9378. _context.moveTo( x0, y0 );
  9379. _context.lineTo( x1, y1 );
  9380. _context.lineTo( x2, y2 );
  9381. _context.closePath();
  9382. }
  9383. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  9384. _context.beginPath();
  9385. _context.moveTo( x0, y0 );
  9386. _context.lineTo( x1, y1 );
  9387. _context.lineTo( x2, y2 );
  9388. _context.lineTo( x3, y3 );
  9389. _context.closePath();
  9390. }
  9391. function strokePath( color, linewidth, linecap, linejoin ) {
  9392. setLineWidth( linewidth );
  9393. setLineCap( linecap );
  9394. setLineJoin( linejoin );
  9395. setStrokeStyle( color.getStyle() );
  9396. _context.stroke();
  9397. _elemBox.expandByScalar( linewidth * 2 );
  9398. }
  9399. function fillPath( color ) {
  9400. setFillStyle( color.getStyle() );
  9401. _context.fill();
  9402. }
  9403. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9404. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  9405. if ( texture.needsUpdate === true ) {
  9406. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  9407. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  9408. _patterns[ texture.id ] = _context.createPattern(
  9409. texture.image, repeatX === true && repeatY === true
  9410. ? 'repeat'
  9411. : repeatX === true && repeatY === false
  9412. ? 'repeat-x'
  9413. : repeatX === false && repeatY === true
  9414. ? 'repeat-y'
  9415. : 'no-repeat'
  9416. );
  9417. texture.needsUpdate = false;
  9418. }
  9419. _patterns[ texture.id ] === undefined
  9420. ? setFillStyle( 'rgba(0,0,0,1)' )
  9421. : setFillStyle( _patterns[ texture.id ] );
  9422. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9423. var a, b, c, d, e, f, det, idet,
  9424. offsetX = texture.offset.x / texture.repeat.x,
  9425. offsetY = texture.offset.y / texture.repeat.y,
  9426. width = texture.image.width * texture.repeat.x,
  9427. height = texture.image.height * texture.repeat.y;
  9428. u0 = ( u0 + offsetX ) * width;
  9429. v0 = ( 1.0 - v0 + offsetY ) * height;
  9430. u1 = ( u1 + offsetX ) * width;
  9431. v1 = ( 1.0 - v1 + offsetY ) * height;
  9432. u2 = ( u2 + offsetX ) * width;
  9433. v2 = ( 1.0 - v2 + offsetY ) * height;
  9434. x1 -= x0; y1 -= y0;
  9435. x2 -= x0; y2 -= y0;
  9436. u1 -= u0; v1 -= v0;
  9437. u2 -= u0; v2 -= v0;
  9438. det = u1 * v2 - u2 * v1;
  9439. if ( det === 0 ) {
  9440. if ( _imagedatas[ texture.id ] === undefined ) {
  9441. var canvas = document.createElement( 'canvas' )
  9442. canvas.width = texture.image.width;
  9443. canvas.height = texture.image.height;
  9444. var context = canvas.getContext( '2d' );
  9445. context.drawImage( texture.image, 0, 0 );
  9446. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9447. }
  9448. var data = _imagedatas[ texture.id ];
  9449. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9450. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9451. fillPath( _color );
  9452. return;
  9453. }
  9454. idet = 1 / det;
  9455. a = ( v2 * x1 - v1 * x2 ) * idet;
  9456. b = ( v2 * y1 - v1 * y2 ) * idet;
  9457. c = ( u1 * x2 - u2 * x1 ) * idet;
  9458. d = ( u1 * y2 - u2 * y1 ) * idet;
  9459. e = x0 - a * u0 - c * v0;
  9460. f = y0 - b * u0 - d * v0;
  9461. _context.save();
  9462. _context.transform( a, b, c, d, e, f );
  9463. _context.fill();
  9464. _context.restore();
  9465. }
  9466. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9467. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9468. var a, b, c, d, e, f, det, idet,
  9469. width = image.width - 1,
  9470. height = image.height - 1;
  9471. u0 *= width; v0 *= height;
  9472. u1 *= width; v1 *= height;
  9473. u2 *= width; v2 *= height;
  9474. x1 -= x0; y1 -= y0;
  9475. x2 -= x0; y2 -= y0;
  9476. u1 -= u0; v1 -= v0;
  9477. u2 -= u0; v2 -= v0;
  9478. det = u1 * v2 - u2 * v1;
  9479. idet = 1 / det;
  9480. a = ( v2 * x1 - v1 * x2 ) * idet;
  9481. b = ( v2 * y1 - v1 * y2 ) * idet;
  9482. c = ( u1 * x2 - u2 * x1 ) * idet;
  9483. d = ( u1 * y2 - u2 * y1 ) * idet;
  9484. e = x0 - a * u0 - c * v0;
  9485. f = y0 - b * u0 - d * v0;
  9486. _context.save();
  9487. _context.transform( a, b, c, d, e, f );
  9488. _context.clip();
  9489. _context.drawImage( image, 0, 0 );
  9490. _context.restore();
  9491. }
  9492. function getGradientTexture( color1, color2, color3, color4 ) {
  9493. // http://mrdoob.com/blog/post/710
  9494. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9495. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9496. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9497. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9498. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9499. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9500. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9501. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9502. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9503. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9504. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9505. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9506. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9507. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9508. return _gradientMap;
  9509. }
  9510. // Hide anti-alias gaps
  9511. function expand( v1, v2, pixels ) {
  9512. var x = v2.x - v1.x, y = v2.y - v1.y,
  9513. det = x * x + y * y, idet;
  9514. if ( det === 0 ) return;
  9515. idet = pixels / Math.sqrt( det );
  9516. x *= idet; y *= idet;
  9517. v2.x += x; v2.y += y;
  9518. v1.x -= x; v1.y -= y;
  9519. }
  9520. // Context cached methods.
  9521. function setOpacity( value ) {
  9522. if ( _contextGlobalAlpha !== value ) {
  9523. _context.globalAlpha = value;
  9524. _contextGlobalAlpha = value;
  9525. }
  9526. }
  9527. function setBlending( value ) {
  9528. if ( _contextGlobalCompositeOperation !== value ) {
  9529. if ( value === THREE.NormalBlending ) {
  9530. _context.globalCompositeOperation = 'source-over';
  9531. } else if ( value === THREE.AdditiveBlending ) {
  9532. _context.globalCompositeOperation = 'lighter';
  9533. } else if ( value === THREE.SubtractiveBlending ) {
  9534. _context.globalCompositeOperation = 'darker';
  9535. }
  9536. _contextGlobalCompositeOperation = value;
  9537. }
  9538. }
  9539. function setLineWidth( value ) {
  9540. if ( _contextLineWidth !== value ) {
  9541. _context.lineWidth = value;
  9542. _contextLineWidth = value;
  9543. }
  9544. }
  9545. function setLineCap( value ) {
  9546. // "butt", "round", "square"
  9547. if ( _contextLineCap !== value ) {
  9548. _context.lineCap = value;
  9549. _contextLineCap = value;
  9550. }
  9551. }
  9552. function setLineJoin( value ) {
  9553. // "round", "bevel", "miter"
  9554. if ( _contextLineJoin !== value ) {
  9555. _context.lineJoin = value;
  9556. _contextLineJoin = value;
  9557. }
  9558. }
  9559. function setStrokeStyle( value ) {
  9560. if ( _contextStrokeStyle !== value ) {
  9561. _context.strokeStyle = value;
  9562. _contextStrokeStyle = value;
  9563. }
  9564. }
  9565. function setFillStyle( value ) {
  9566. if ( _contextFillStyle !== value ) {
  9567. _context.fillStyle = value;
  9568. _contextFillStyle = value;
  9569. }
  9570. }
  9571. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9572. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9573. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9574. _contextDashSize = dashSizeValue;
  9575. _contextGapSize = gapSizeValue;
  9576. }
  9577. }
  9578. };
  9579. /**
  9580. * @author alteredq / http://alteredqualia.com/
  9581. * @author mrdoob / http://mrdoob.com/
  9582. * @author mikael emtinger / http://gomo.se/
  9583. */
  9584. THREE.ShaderChunk = {
  9585. // FOG
  9586. fog_pars_fragment: [
  9587. "#ifdef USE_FOG",
  9588. "uniform vec3 fogColor;",
  9589. "#ifdef FOG_EXP2",
  9590. "uniform float fogDensity;",
  9591. "#else",
  9592. "uniform float fogNear;",
  9593. "uniform float fogFar;",
  9594. "#endif",
  9595. "#endif"
  9596. ].join("\n"),
  9597. fog_fragment: [
  9598. "#ifdef USE_FOG",
  9599. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9600. "#ifdef FOG_EXP2",
  9601. "const float LOG2 = 1.442695;",
  9602. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9603. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9604. "#else",
  9605. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9606. "#endif",
  9607. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9608. "#endif"
  9609. ].join("\n"),
  9610. // ENVIRONMENT MAP
  9611. envmap_pars_fragment: [
  9612. "#ifdef USE_ENVMAP",
  9613. "uniform float reflectivity;",
  9614. "uniform samplerCube envMap;",
  9615. "uniform float flipEnvMap;",
  9616. "uniform int combine;",
  9617. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9618. "uniform bool useRefract;",
  9619. "uniform float refractionRatio;",
  9620. "#else",
  9621. "varying vec3 vReflect;",
  9622. "#endif",
  9623. "#endif"
  9624. ].join("\n"),
  9625. envmap_fragment: [
  9626. "#ifdef USE_ENVMAP",
  9627. "vec3 reflectVec;",
  9628. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9629. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9630. "if ( useRefract ) {",
  9631. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9632. "} else { ",
  9633. "reflectVec = reflect( cameraToVertex, normal );",
  9634. "}",
  9635. "#else",
  9636. "reflectVec = vReflect;",
  9637. "#endif",
  9638. "#ifdef DOUBLE_SIDED",
  9639. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9640. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9641. "#else",
  9642. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9643. "#endif",
  9644. "#ifdef GAMMA_INPUT",
  9645. "cubeColor.xyz *= cubeColor.xyz;",
  9646. "#endif",
  9647. "if ( combine == 1 ) {",
  9648. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9649. "} else if ( combine == 2 ) {",
  9650. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9651. "} else {",
  9652. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9653. "}",
  9654. "#endif"
  9655. ].join("\n"),
  9656. envmap_pars_vertex: [
  9657. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9658. "varying vec3 vReflect;",
  9659. "uniform float refractionRatio;",
  9660. "uniform bool useRefract;",
  9661. "#endif"
  9662. ].join("\n"),
  9663. worldpos_vertex : [
  9664. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9665. "#ifdef USE_SKINNING",
  9666. "vec4 worldPosition = modelMatrix * skinned;",
  9667. "#endif",
  9668. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9669. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9670. "#endif",
  9671. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9672. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9673. "#endif",
  9674. "#endif"
  9675. ].join("\n"),
  9676. envmap_vertex : [
  9677. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9678. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9679. "worldNormal = normalize( worldNormal );",
  9680. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9681. "if ( useRefract ) {",
  9682. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9683. "} else {",
  9684. "vReflect = reflect( cameraToVertex, worldNormal );",
  9685. "}",
  9686. "#endif"
  9687. ].join("\n"),
  9688. // COLOR MAP (particles)
  9689. map_particle_pars_fragment: [
  9690. "#ifdef USE_MAP",
  9691. "uniform sampler2D map;",
  9692. "#endif"
  9693. ].join("\n"),
  9694. map_particle_fragment: [
  9695. "#ifdef USE_MAP",
  9696. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9697. "#endif"
  9698. ].join("\n"),
  9699. // COLOR MAP (triangles)
  9700. map_pars_vertex: [
  9701. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9702. "varying vec2 vUv;",
  9703. "uniform vec4 offsetRepeat;",
  9704. "#endif"
  9705. ].join("\n"),
  9706. map_pars_fragment: [
  9707. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9708. "varying vec2 vUv;",
  9709. "#endif",
  9710. "#ifdef USE_MAP",
  9711. "uniform sampler2D map;",
  9712. "#endif"
  9713. ].join("\n"),
  9714. map_vertex: [
  9715. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9716. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9717. "#endif"
  9718. ].join("\n"),
  9719. map_fragment: [
  9720. "#ifdef USE_MAP",
  9721. "vec4 texelColor = texture2D( map, vUv );",
  9722. "#ifdef GAMMA_INPUT",
  9723. "texelColor.xyz *= texelColor.xyz;",
  9724. "#endif",
  9725. "gl_FragColor = gl_FragColor * texelColor;",
  9726. "#endif"
  9727. ].join("\n"),
  9728. // LIGHT MAP
  9729. lightmap_pars_fragment: [
  9730. "#ifdef USE_LIGHTMAP",
  9731. "varying vec2 vUv2;",
  9732. "uniform sampler2D lightMap;",
  9733. "#endif"
  9734. ].join("\n"),
  9735. lightmap_pars_vertex: [
  9736. "#ifdef USE_LIGHTMAP",
  9737. "varying vec2 vUv2;",
  9738. "#endif"
  9739. ].join("\n"),
  9740. lightmap_fragment: [
  9741. "#ifdef USE_LIGHTMAP",
  9742. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9743. "#endif"
  9744. ].join("\n"),
  9745. lightmap_vertex: [
  9746. "#ifdef USE_LIGHTMAP",
  9747. "vUv2 = uv2;",
  9748. "#endif"
  9749. ].join("\n"),
  9750. // BUMP MAP
  9751. bumpmap_pars_fragment: [
  9752. "#ifdef USE_BUMPMAP",
  9753. "uniform sampler2D bumpMap;",
  9754. "uniform float bumpScale;",
  9755. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9756. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9757. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9758. "vec2 dHdxy_fwd() {",
  9759. "vec2 dSTdx = dFdx( vUv );",
  9760. "vec2 dSTdy = dFdy( vUv );",
  9761. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9762. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9763. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9764. "return vec2( dBx, dBy );",
  9765. "}",
  9766. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9767. "vec3 vSigmaX = dFdx( surf_pos );",
  9768. "vec3 vSigmaY = dFdy( surf_pos );",
  9769. "vec3 vN = surf_norm;", // normalized
  9770. "vec3 R1 = cross( vSigmaY, vN );",
  9771. "vec3 R2 = cross( vN, vSigmaX );",
  9772. "float fDet = dot( vSigmaX, R1 );",
  9773. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9774. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9775. "}",
  9776. "#endif"
  9777. ].join("\n"),
  9778. // NORMAL MAP
  9779. normalmap_pars_fragment: [
  9780. "#ifdef USE_NORMALMAP",
  9781. "uniform sampler2D normalMap;",
  9782. "uniform vec2 normalScale;",
  9783. // Per-Pixel Tangent Space Normal Mapping
  9784. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9785. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9786. "vec3 q0 = dFdx( eye_pos.xyz );",
  9787. "vec3 q1 = dFdy( eye_pos.xyz );",
  9788. "vec2 st0 = dFdx( vUv.st );",
  9789. "vec2 st1 = dFdy( vUv.st );",
  9790. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9791. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9792. "vec3 N = normalize( surf_norm );",
  9793. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9794. "mapN.xy = normalScale * mapN.xy;",
  9795. "mat3 tsn = mat3( S, T, N );",
  9796. "return normalize( tsn * mapN );",
  9797. "}",
  9798. "#endif"
  9799. ].join("\n"),
  9800. // SPECULAR MAP
  9801. specularmap_pars_fragment: [
  9802. "#ifdef USE_SPECULARMAP",
  9803. "uniform sampler2D specularMap;",
  9804. "#endif"
  9805. ].join("\n"),
  9806. specularmap_fragment: [
  9807. "float specularStrength;",
  9808. "#ifdef USE_SPECULARMAP",
  9809. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9810. "specularStrength = texelSpecular.r;",
  9811. "#else",
  9812. "specularStrength = 1.0;",
  9813. "#endif"
  9814. ].join("\n"),
  9815. // LIGHTS LAMBERT
  9816. lights_lambert_pars_vertex: [
  9817. "uniform vec3 ambient;",
  9818. "uniform vec3 diffuse;",
  9819. "uniform vec3 emissive;",
  9820. "uniform vec3 ambientLightColor;",
  9821. "#if MAX_DIR_LIGHTS > 0",
  9822. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9823. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9824. "#endif",
  9825. "#if MAX_HEMI_LIGHTS > 0",
  9826. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9827. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9828. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9829. "#endif",
  9830. "#if MAX_POINT_LIGHTS > 0",
  9831. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9832. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9833. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9834. "#endif",
  9835. "#if MAX_SPOT_LIGHTS > 0",
  9836. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9837. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9838. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9839. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9840. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9841. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9842. "#endif",
  9843. "#ifdef WRAP_AROUND",
  9844. "uniform vec3 wrapRGB;",
  9845. "#endif"
  9846. ].join("\n"),
  9847. lights_lambert_vertex: [
  9848. "vLightFront = vec3( 0.0 );",
  9849. "#ifdef DOUBLE_SIDED",
  9850. "vLightBack = vec3( 0.0 );",
  9851. "#endif",
  9852. "transformedNormal = normalize( transformedNormal );",
  9853. "#if MAX_DIR_LIGHTS > 0",
  9854. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9855. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9856. "vec3 dirVector = normalize( lDirection.xyz );",
  9857. "float dotProduct = dot( transformedNormal, dirVector );",
  9858. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9859. "#ifdef DOUBLE_SIDED",
  9860. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9861. "#ifdef WRAP_AROUND",
  9862. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9863. "#endif",
  9864. "#endif",
  9865. "#ifdef WRAP_AROUND",
  9866. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9867. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9868. "#ifdef DOUBLE_SIDED",
  9869. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9870. "#endif",
  9871. "#endif",
  9872. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9873. "#ifdef DOUBLE_SIDED",
  9874. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9875. "#endif",
  9876. "}",
  9877. "#endif",
  9878. "#if MAX_POINT_LIGHTS > 0",
  9879. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9880. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9881. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9882. "float lDistance = 1.0;",
  9883. "if ( pointLightDistance[ i ] > 0.0 )",
  9884. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9885. "lVector = normalize( lVector );",
  9886. "float dotProduct = dot( transformedNormal, lVector );",
  9887. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9888. "#ifdef DOUBLE_SIDED",
  9889. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9890. "#ifdef WRAP_AROUND",
  9891. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9892. "#endif",
  9893. "#endif",
  9894. "#ifdef WRAP_AROUND",
  9895. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9896. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9897. "#ifdef DOUBLE_SIDED",
  9898. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9899. "#endif",
  9900. "#endif",
  9901. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9902. "#ifdef DOUBLE_SIDED",
  9903. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9904. "#endif",
  9905. "}",
  9906. "#endif",
  9907. "#if MAX_SPOT_LIGHTS > 0",
  9908. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9909. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9910. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9911. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9912. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9913. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9914. "float lDistance = 1.0;",
  9915. "if ( spotLightDistance[ i ] > 0.0 )",
  9916. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9917. "lVector = normalize( lVector );",
  9918. "float dotProduct = dot( transformedNormal, lVector );",
  9919. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9920. "#ifdef DOUBLE_SIDED",
  9921. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9922. "#ifdef WRAP_AROUND",
  9923. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9924. "#endif",
  9925. "#endif",
  9926. "#ifdef WRAP_AROUND",
  9927. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9928. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9929. "#ifdef DOUBLE_SIDED",
  9930. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9931. "#endif",
  9932. "#endif",
  9933. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9934. "#ifdef DOUBLE_SIDED",
  9935. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9936. "#endif",
  9937. "}",
  9938. "}",
  9939. "#endif",
  9940. "#if MAX_HEMI_LIGHTS > 0",
  9941. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9942. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9943. "vec3 lVector = normalize( lDirection.xyz );",
  9944. "float dotProduct = dot( transformedNormal, lVector );",
  9945. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9946. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9947. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9948. "#ifdef DOUBLE_SIDED",
  9949. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9950. "#endif",
  9951. "}",
  9952. "#endif",
  9953. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9954. "#ifdef DOUBLE_SIDED",
  9955. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9956. "#endif"
  9957. ].join("\n"),
  9958. // LIGHTS PHONG
  9959. lights_phong_pars_vertex: [
  9960. "#ifndef PHONG_PER_PIXEL",
  9961. "#if MAX_POINT_LIGHTS > 0",
  9962. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9963. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9964. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9965. "#endif",
  9966. "#if MAX_SPOT_LIGHTS > 0",
  9967. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9968. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9969. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9970. "#endif",
  9971. "#endif",
  9972. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9973. "varying vec3 vWorldPosition;",
  9974. "#endif"
  9975. ].join("\n"),
  9976. lights_phong_vertex: [
  9977. "#ifndef PHONG_PER_PIXEL",
  9978. "#if MAX_POINT_LIGHTS > 0",
  9979. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9980. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9981. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9982. "float lDistance = 1.0;",
  9983. "if ( pointLightDistance[ i ] > 0.0 )",
  9984. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9985. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9986. "}",
  9987. "#endif",
  9988. "#if MAX_SPOT_LIGHTS > 0",
  9989. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9990. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9991. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9992. "float lDistance = 1.0;",
  9993. "if ( spotLightDistance[ i ] > 0.0 )",
  9994. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9995. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9996. "}",
  9997. "#endif",
  9998. "#endif",
  9999. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10000. "vWorldPosition = worldPosition.xyz;",
  10001. "#endif"
  10002. ].join("\n"),
  10003. lights_phong_pars_fragment: [
  10004. "uniform vec3 ambientLightColor;",
  10005. "#if MAX_DIR_LIGHTS > 0",
  10006. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10007. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10008. "#endif",
  10009. "#if MAX_HEMI_LIGHTS > 0",
  10010. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10011. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10012. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10013. "#endif",
  10014. "#if MAX_POINT_LIGHTS > 0",
  10015. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10016. "#ifdef PHONG_PER_PIXEL",
  10017. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10018. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10019. "#else",
  10020. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10021. "#endif",
  10022. "#endif",
  10023. "#if MAX_SPOT_LIGHTS > 0",
  10024. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10025. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10026. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10027. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10028. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10029. "#ifdef PHONG_PER_PIXEL",
  10030. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10031. "#else",
  10032. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10033. "#endif",
  10034. "#endif",
  10035. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10036. "varying vec3 vWorldPosition;",
  10037. "#endif",
  10038. "#ifdef WRAP_AROUND",
  10039. "uniform vec3 wrapRGB;",
  10040. "#endif",
  10041. "varying vec3 vViewPosition;",
  10042. "varying vec3 vNormal;"
  10043. ].join("\n"),
  10044. lights_phong_fragment: [
  10045. "vec3 normal = normalize( vNormal );",
  10046. "vec3 viewPosition = normalize( vViewPosition );",
  10047. "#ifdef DOUBLE_SIDED",
  10048. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10049. "#endif",
  10050. "#ifdef USE_NORMALMAP",
  10051. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10052. "#elif defined( USE_BUMPMAP )",
  10053. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10054. "#endif",
  10055. "#if MAX_POINT_LIGHTS > 0",
  10056. "vec3 pointDiffuse = vec3( 0.0 );",
  10057. "vec3 pointSpecular = vec3( 0.0 );",
  10058. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10059. "#ifdef PHONG_PER_PIXEL",
  10060. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10061. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10062. "float lDistance = 1.0;",
  10063. "if ( pointLightDistance[ i ] > 0.0 )",
  10064. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10065. "lVector = normalize( lVector );",
  10066. "#else",
  10067. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10068. "float lDistance = vPointLight[ i ].w;",
  10069. "#endif",
  10070. // diffuse
  10071. "float dotProduct = dot( normal, lVector );",
  10072. "#ifdef WRAP_AROUND",
  10073. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10074. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10075. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10076. "#else",
  10077. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10078. "#endif",
  10079. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10080. // specular
  10081. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10082. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10083. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10084. "#ifdef PHYSICALLY_BASED_SHADING",
  10085. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10086. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10087. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10088. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10089. "#else",
  10090. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10091. "#endif",
  10092. "}",
  10093. "#endif",
  10094. "#if MAX_SPOT_LIGHTS > 0",
  10095. "vec3 spotDiffuse = vec3( 0.0 );",
  10096. "vec3 spotSpecular = vec3( 0.0 );",
  10097. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10098. "#ifdef PHONG_PER_PIXEL",
  10099. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10100. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10101. "float lDistance = 1.0;",
  10102. "if ( spotLightDistance[ i ] > 0.0 )",
  10103. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10104. "lVector = normalize( lVector );",
  10105. "#else",
  10106. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10107. "float lDistance = vSpotLight[ i ].w;",
  10108. "#endif",
  10109. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10110. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10111. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10112. // diffuse
  10113. "float dotProduct = dot( normal, lVector );",
  10114. "#ifdef WRAP_AROUND",
  10115. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10116. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10117. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10118. "#else",
  10119. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10120. "#endif",
  10121. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10122. // specular
  10123. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10124. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10125. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10126. "#ifdef PHYSICALLY_BASED_SHADING",
  10127. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10128. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10129. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10130. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10131. "#else",
  10132. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10133. "#endif",
  10134. "}",
  10135. "}",
  10136. "#endif",
  10137. "#if MAX_DIR_LIGHTS > 0",
  10138. "vec3 dirDiffuse = vec3( 0.0 );",
  10139. "vec3 dirSpecular = vec3( 0.0 );" ,
  10140. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10141. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10142. "vec3 dirVector = normalize( lDirection.xyz );",
  10143. // diffuse
  10144. "float dotProduct = dot( normal, dirVector );",
  10145. "#ifdef WRAP_AROUND",
  10146. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10147. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10148. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10149. "#else",
  10150. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10151. "#endif",
  10152. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10153. // specular
  10154. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10155. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10156. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10157. "#ifdef PHYSICALLY_BASED_SHADING",
  10158. /*
  10159. // fresnel term from skin shader
  10160. "const float F0 = 0.128;",
  10161. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10162. "float exponential = pow( base, 5.0 );",
  10163. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10164. */
  10165. /*
  10166. // fresnel term from fresnel shader
  10167. "const float mFresnelBias = 0.08;",
  10168. "const float mFresnelScale = 0.3;",
  10169. "const float mFresnelPower = 5.0;",
  10170. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10171. */
  10172. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10173. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10174. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10175. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10176. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10177. "#else",
  10178. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10179. "#endif",
  10180. "}",
  10181. "#endif",
  10182. "#if MAX_HEMI_LIGHTS > 0",
  10183. "vec3 hemiDiffuse = vec3( 0.0 );",
  10184. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10185. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10186. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10187. "vec3 lVector = normalize( lDirection.xyz );",
  10188. // diffuse
  10189. "float dotProduct = dot( normal, lVector );",
  10190. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10191. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10192. "hemiDiffuse += diffuse * hemiColor;",
  10193. // specular (sky light)
  10194. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10195. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10196. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10197. // specular (ground light)
  10198. "vec3 lVectorGround = -lVector;",
  10199. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10200. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10201. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10202. "#ifdef PHYSICALLY_BASED_SHADING",
  10203. "float dotProductGround = dot( normal, lVectorGround );",
  10204. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10205. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10206. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10207. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10208. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10209. "#else",
  10210. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10211. "#endif",
  10212. "}",
  10213. "#endif",
  10214. "vec3 totalDiffuse = vec3( 0.0 );",
  10215. "vec3 totalSpecular = vec3( 0.0 );",
  10216. "#if MAX_DIR_LIGHTS > 0",
  10217. "totalDiffuse += dirDiffuse;",
  10218. "totalSpecular += dirSpecular;",
  10219. "#endif",
  10220. "#if MAX_HEMI_LIGHTS > 0",
  10221. "totalDiffuse += hemiDiffuse;",
  10222. "totalSpecular += hemiSpecular;",
  10223. "#endif",
  10224. "#if MAX_POINT_LIGHTS > 0",
  10225. "totalDiffuse += pointDiffuse;",
  10226. "totalSpecular += pointSpecular;",
  10227. "#endif",
  10228. "#if MAX_SPOT_LIGHTS > 0",
  10229. "totalDiffuse += spotDiffuse;",
  10230. "totalSpecular += spotSpecular;",
  10231. "#endif",
  10232. "#ifdef METAL",
  10233. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10234. "#else",
  10235. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10236. "#endif"
  10237. ].join("\n"),
  10238. // VERTEX COLORS
  10239. color_pars_fragment: [
  10240. "#ifdef USE_COLOR",
  10241. "varying vec3 vColor;",
  10242. "#endif"
  10243. ].join("\n"),
  10244. color_fragment: [
  10245. "#ifdef USE_COLOR",
  10246. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  10247. "#endif"
  10248. ].join("\n"),
  10249. color_pars_vertex: [
  10250. "#ifdef USE_COLOR",
  10251. "varying vec3 vColor;",
  10252. "#endif"
  10253. ].join("\n"),
  10254. color_vertex: [
  10255. "#ifdef USE_COLOR",
  10256. "#ifdef GAMMA_INPUT",
  10257. "vColor = color * color;",
  10258. "#else",
  10259. "vColor = color;",
  10260. "#endif",
  10261. "#endif"
  10262. ].join("\n"),
  10263. // SKINNING
  10264. skinning_pars_vertex: [
  10265. "#ifdef USE_SKINNING",
  10266. "#ifdef BONE_TEXTURE",
  10267. "uniform sampler2D boneTexture;",
  10268. "mat4 getBoneMatrix( const in float i ) {",
  10269. "float j = i * 4.0;",
  10270. "float x = mod( j, N_BONE_PIXEL_X );",
  10271. "float y = floor( j / N_BONE_PIXEL_X );",
  10272. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  10273. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  10274. "y = dy * ( y + 0.5 );",
  10275. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10276. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10277. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10278. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10279. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10280. "return bone;",
  10281. "}",
  10282. "#else",
  10283. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10284. "mat4 getBoneMatrix( const in float i ) {",
  10285. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10286. "return bone;",
  10287. "}",
  10288. "#endif",
  10289. "#endif"
  10290. ].join("\n"),
  10291. skinbase_vertex: [
  10292. "#ifdef USE_SKINNING",
  10293. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10294. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10295. "#endif"
  10296. ].join("\n"),
  10297. skinning_vertex: [
  10298. "#ifdef USE_SKINNING",
  10299. "#ifdef USE_MORPHTARGETS",
  10300. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10301. "#else",
  10302. "vec4 skinVertex = vec4( position, 1.0 );",
  10303. "#endif",
  10304. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10305. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10306. "#endif"
  10307. ].join("\n"),
  10308. // MORPHING
  10309. morphtarget_pars_vertex: [
  10310. "#ifdef USE_MORPHTARGETS",
  10311. "#ifndef USE_MORPHNORMALS",
  10312. "uniform float morphTargetInfluences[ 8 ];",
  10313. "#else",
  10314. "uniform float morphTargetInfluences[ 4 ];",
  10315. "#endif",
  10316. "#endif"
  10317. ].join("\n"),
  10318. morphtarget_vertex: [
  10319. "#ifdef USE_MORPHTARGETS",
  10320. "vec3 morphed = vec3( 0.0 );",
  10321. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10322. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10323. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10324. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10325. "#ifndef USE_MORPHNORMALS",
  10326. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10327. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10328. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10329. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10330. "#endif",
  10331. "morphed += position;",
  10332. "#endif"
  10333. ].join("\n"),
  10334. default_vertex : [
  10335. "vec4 mvPosition;",
  10336. "#ifdef USE_SKINNING",
  10337. "mvPosition = modelViewMatrix * skinned;",
  10338. "#endif",
  10339. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10340. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10341. "#endif",
  10342. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10343. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10344. "#endif",
  10345. "gl_Position = projectionMatrix * mvPosition;"
  10346. ].join("\n"),
  10347. morphnormal_vertex: [
  10348. "#ifdef USE_MORPHNORMALS",
  10349. "vec3 morphedNormal = vec3( 0.0 );",
  10350. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10351. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10352. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10353. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10354. "morphedNormal += normal;",
  10355. "#endif"
  10356. ].join("\n"),
  10357. skinnormal_vertex: [
  10358. "#ifdef USE_SKINNING",
  10359. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10360. "skinMatrix += skinWeight.y * boneMatY;",
  10361. "#ifdef USE_MORPHNORMALS",
  10362. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10363. "#else",
  10364. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10365. "#endif",
  10366. "#endif"
  10367. ].join("\n"),
  10368. defaultnormal_vertex: [
  10369. "vec3 objectNormal;",
  10370. "#ifdef USE_SKINNING",
  10371. "objectNormal = skinnedNormal.xyz;",
  10372. "#endif",
  10373. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10374. "objectNormal = morphedNormal;",
  10375. "#endif",
  10376. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10377. "objectNormal = normal;",
  10378. "#endif",
  10379. "#ifdef FLIP_SIDED",
  10380. "objectNormal = -objectNormal;",
  10381. "#endif",
  10382. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10383. ].join("\n"),
  10384. // SHADOW MAP
  10385. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10386. // http://spidergl.org/example.php?id=6
  10387. // http://fabiensanglard.net/shadowmapping
  10388. shadowmap_pars_fragment: [
  10389. "#ifdef USE_SHADOWMAP",
  10390. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10391. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10392. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10393. "uniform float shadowBias[ MAX_SHADOWS ];",
  10394. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10395. "float unpackDepth( const in vec4 rgba_depth ) {",
  10396. "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 );",
  10397. "float depth = dot( rgba_depth, bit_shift );",
  10398. "return depth;",
  10399. "}",
  10400. "#endif"
  10401. ].join("\n"),
  10402. shadowmap_fragment: [
  10403. "#ifdef USE_SHADOWMAP",
  10404. "#ifdef SHADOWMAP_DEBUG",
  10405. "vec3 frustumColors[3];",
  10406. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10407. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10408. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10409. "#endif",
  10410. "#ifdef SHADOWMAP_CASCADE",
  10411. "int inFrustumCount = 0;",
  10412. "#endif",
  10413. "float fDepth;",
  10414. "vec3 shadowColor = vec3( 1.0 );",
  10415. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10416. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10417. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10418. // "if ( all( something, something ) )" using this instead
  10419. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10420. "bool inFrustum = all( inFrustumVec );",
  10421. // don't shadow pixels outside of light frustum
  10422. // use just first frustum (for cascades)
  10423. // don't shadow pixels behind far plane of light frustum
  10424. "#ifdef SHADOWMAP_CASCADE",
  10425. "inFrustumCount += int( inFrustum );",
  10426. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10427. "#else",
  10428. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10429. "#endif",
  10430. "bool frustumTest = all( frustumTestVec );",
  10431. "if ( frustumTest ) {",
  10432. "shadowCoord.z += shadowBias[ i ];",
  10433. "#if defined( SHADOWMAP_TYPE_PCF )",
  10434. // Percentage-close filtering
  10435. // (9 pixel kernel)
  10436. // http://fabiensanglard.net/shadowmappingPCF/
  10437. "float shadow = 0.0;",
  10438. /*
  10439. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10440. // must enroll loop manually
  10441. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10442. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10443. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10444. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10445. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10446. "float fDepth = unpackDepth( rgbaDepth );",
  10447. "if ( fDepth < shadowCoord.z )",
  10448. "shadow += 1.0;",
  10449. "}",
  10450. "shadow /= 9.0;",
  10451. */
  10452. "const float shadowDelta = 1.0 / 9.0;",
  10453. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10454. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10455. "float dx0 = -1.25 * xPixelOffset;",
  10456. "float dy0 = -1.25 * yPixelOffset;",
  10457. "float dx1 = 1.25 * xPixelOffset;",
  10458. "float dy1 = 1.25 * yPixelOffset;",
  10459. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10460. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10461. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10462. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10463. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10464. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10465. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10466. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10467. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10468. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10469. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10470. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10471. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10472. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10473. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10474. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10475. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10476. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10477. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10478. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10479. // Percentage-close filtering
  10480. // (9 pixel kernel)
  10481. // http://fabiensanglard.net/shadowmappingPCF/
  10482. "float shadow = 0.0;",
  10483. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10484. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10485. "float dx0 = -1.0 * xPixelOffset;",
  10486. "float dy0 = -1.0 * yPixelOffset;",
  10487. "float dx1 = 1.0 * xPixelOffset;",
  10488. "float dy1 = 1.0 * yPixelOffset;",
  10489. "mat3 shadowKernel;",
  10490. "mat3 depthKernel;",
  10491. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10492. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10493. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10494. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10495. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10496. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10497. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10498. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10499. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10500. "vec3 shadowZ = vec3( shadowCoord.z );",
  10501. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10502. "shadowKernel[0] *= vec3(0.25);",
  10503. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10504. "shadowKernel[1] *= vec3(0.25);",
  10505. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10506. "shadowKernel[2] *= vec3(0.25);",
  10507. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10508. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10509. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10510. "vec4 shadowValues;",
  10511. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10512. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10513. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10514. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10515. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10516. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10517. "#else",
  10518. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10519. "float fDepth = unpackDepth( rgbaDepth );",
  10520. "if ( fDepth < shadowCoord.z )",
  10521. // spot with multiple shadows is darker
  10522. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10523. // spot with multiple shadows has the same color as single shadow spot
  10524. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10525. "#endif",
  10526. "}",
  10527. "#ifdef SHADOWMAP_DEBUG",
  10528. "#ifdef SHADOWMAP_CASCADE",
  10529. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10530. "#else",
  10531. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10532. "#endif",
  10533. "#endif",
  10534. "}",
  10535. "#ifdef GAMMA_OUTPUT",
  10536. "shadowColor *= shadowColor;",
  10537. "#endif",
  10538. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10539. "#endif"
  10540. ].join("\n"),
  10541. shadowmap_pars_vertex: [
  10542. "#ifdef USE_SHADOWMAP",
  10543. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10544. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10545. "#endif"
  10546. ].join("\n"),
  10547. shadowmap_vertex: [
  10548. "#ifdef USE_SHADOWMAP",
  10549. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10550. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10551. "}",
  10552. "#endif"
  10553. ].join("\n"),
  10554. // ALPHATEST
  10555. alphatest_fragment: [
  10556. "#ifdef ALPHATEST",
  10557. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10558. "#endif"
  10559. ].join("\n"),
  10560. // LINEAR SPACE
  10561. linear_to_gamma_fragment: [
  10562. "#ifdef GAMMA_OUTPUT",
  10563. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10564. "#endif"
  10565. ].join("\n")
  10566. };
  10567. THREE.UniformsUtils = {
  10568. merge: function ( uniforms ) {
  10569. var u, p, tmp, merged = {};
  10570. for ( u = 0; u < uniforms.length; u ++ ) {
  10571. tmp = this.clone( uniforms[ u ] );
  10572. for ( p in tmp ) {
  10573. merged[ p ] = tmp[ p ];
  10574. }
  10575. }
  10576. return merged;
  10577. },
  10578. clone: function ( uniforms_src ) {
  10579. var u, p, parameter, parameter_src, uniforms_dst = {};
  10580. for ( u in uniforms_src ) {
  10581. uniforms_dst[ u ] = {};
  10582. for ( p in uniforms_src[ u ] ) {
  10583. parameter_src = uniforms_src[ u ][ p ];
  10584. if ( parameter_src instanceof THREE.Color ||
  10585. parameter_src instanceof THREE.Vector2 ||
  10586. parameter_src instanceof THREE.Vector3 ||
  10587. parameter_src instanceof THREE.Vector4 ||
  10588. parameter_src instanceof THREE.Matrix4 ||
  10589. parameter_src instanceof THREE.Texture ) {
  10590. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10591. } else if ( parameter_src instanceof Array ) {
  10592. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10593. } else {
  10594. uniforms_dst[ u ][ p ] = parameter_src;
  10595. }
  10596. }
  10597. }
  10598. return uniforms_dst;
  10599. }
  10600. };
  10601. THREE.UniformsLib = {
  10602. common: {
  10603. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10604. "opacity" : { type: "f", value: 1.0 },
  10605. "map" : { type: "t", value: null },
  10606. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10607. "lightMap" : { type: "t", value: null },
  10608. "specularMap" : { type: "t", value: null },
  10609. "envMap" : { type: "t", value: null },
  10610. "flipEnvMap" : { type: "f", value: -1 },
  10611. "useRefract" : { type: "i", value: 0 },
  10612. "reflectivity" : { type: "f", value: 1.0 },
  10613. "refractionRatio" : { type: "f", value: 0.98 },
  10614. "combine" : { type: "i", value: 0 },
  10615. "morphTargetInfluences" : { type: "f", value: 0 }
  10616. },
  10617. bump: {
  10618. "bumpMap" : { type: "t", value: null },
  10619. "bumpScale" : { type: "f", value: 1 }
  10620. },
  10621. normalmap: {
  10622. "normalMap" : { type: "t", value: null },
  10623. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10624. },
  10625. fog : {
  10626. "fogDensity" : { type: "f", value: 0.00025 },
  10627. "fogNear" : { type: "f", value: 1 },
  10628. "fogFar" : { type: "f", value: 2000 },
  10629. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10630. },
  10631. lights: {
  10632. "ambientLightColor" : { type: "fv", value: [] },
  10633. "directionalLightDirection" : { type: "fv", value: [] },
  10634. "directionalLightColor" : { type: "fv", value: [] },
  10635. "hemisphereLightDirection" : { type: "fv", value: [] },
  10636. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10637. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10638. "pointLightColor" : { type: "fv", value: [] },
  10639. "pointLightPosition" : { type: "fv", value: [] },
  10640. "pointLightDistance" : { type: "fv1", value: [] },
  10641. "spotLightColor" : { type: "fv", value: [] },
  10642. "spotLightPosition" : { type: "fv", value: [] },
  10643. "spotLightDirection" : { type: "fv", value: [] },
  10644. "spotLightDistance" : { type: "fv1", value: [] },
  10645. "spotLightAngleCos" : { type: "fv1", value: [] },
  10646. "spotLightExponent" : { type: "fv1", value: [] }
  10647. },
  10648. particle: {
  10649. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10650. "opacity" : { type: "f", value: 1.0 },
  10651. "size" : { type: "f", value: 1.0 },
  10652. "scale" : { type: "f", value: 1.0 },
  10653. "map" : { type: "t", value: null },
  10654. "fogDensity" : { type: "f", value: 0.00025 },
  10655. "fogNear" : { type: "f", value: 1 },
  10656. "fogFar" : { type: "f", value: 2000 },
  10657. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10658. },
  10659. shadowmap: {
  10660. "shadowMap": { type: "tv", value: [] },
  10661. "shadowMapSize": { type: "v2v", value: [] },
  10662. "shadowBias" : { type: "fv1", value: [] },
  10663. "shadowDarkness": { type: "fv1", value: [] },
  10664. "shadowMatrix" : { type: "m4v", value: [] }
  10665. }
  10666. };
  10667. THREE.ShaderLib = {
  10668. 'basic': {
  10669. uniforms: THREE.UniformsUtils.merge( [
  10670. THREE.UniformsLib[ "common" ],
  10671. THREE.UniformsLib[ "fog" ],
  10672. THREE.UniformsLib[ "shadowmap" ]
  10673. ] ),
  10674. vertexShader: [
  10675. THREE.ShaderChunk[ "map_pars_vertex" ],
  10676. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10677. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10678. THREE.ShaderChunk[ "color_pars_vertex" ],
  10679. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10680. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10681. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10682. "void main() {",
  10683. THREE.ShaderChunk[ "map_vertex" ],
  10684. THREE.ShaderChunk[ "lightmap_vertex" ],
  10685. THREE.ShaderChunk[ "color_vertex" ],
  10686. THREE.ShaderChunk[ "skinbase_vertex" ],
  10687. "#ifdef USE_ENVMAP",
  10688. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10689. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10690. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10691. "#endif",
  10692. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10693. THREE.ShaderChunk[ "skinning_vertex" ],
  10694. THREE.ShaderChunk[ "default_vertex" ],
  10695. THREE.ShaderChunk[ "worldpos_vertex" ],
  10696. THREE.ShaderChunk[ "envmap_vertex" ],
  10697. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10698. "}"
  10699. ].join("\n"),
  10700. fragmentShader: [
  10701. "uniform vec3 diffuse;",
  10702. "uniform float opacity;",
  10703. THREE.ShaderChunk[ "color_pars_fragment" ],
  10704. THREE.ShaderChunk[ "map_pars_fragment" ],
  10705. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10706. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10707. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10708. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10709. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10710. "void main() {",
  10711. "gl_FragColor = vec4( diffuse, opacity );",
  10712. THREE.ShaderChunk[ "map_fragment" ],
  10713. THREE.ShaderChunk[ "alphatest_fragment" ],
  10714. THREE.ShaderChunk[ "specularmap_fragment" ],
  10715. THREE.ShaderChunk[ "lightmap_fragment" ],
  10716. THREE.ShaderChunk[ "color_fragment" ],
  10717. THREE.ShaderChunk[ "envmap_fragment" ],
  10718. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10719. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10720. THREE.ShaderChunk[ "fog_fragment" ],
  10721. "}"
  10722. ].join("\n")
  10723. },
  10724. 'lambert': {
  10725. uniforms: THREE.UniformsUtils.merge( [
  10726. THREE.UniformsLib[ "common" ],
  10727. THREE.UniformsLib[ "fog" ],
  10728. THREE.UniformsLib[ "lights" ],
  10729. THREE.UniformsLib[ "shadowmap" ],
  10730. {
  10731. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10732. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10733. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10734. }
  10735. ] ),
  10736. vertexShader: [
  10737. "#define LAMBERT",
  10738. "varying vec3 vLightFront;",
  10739. "#ifdef DOUBLE_SIDED",
  10740. "varying vec3 vLightBack;",
  10741. "#endif",
  10742. THREE.ShaderChunk[ "map_pars_vertex" ],
  10743. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10744. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10745. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10746. THREE.ShaderChunk[ "color_pars_vertex" ],
  10747. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10748. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10749. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10750. "void main() {",
  10751. THREE.ShaderChunk[ "map_vertex" ],
  10752. THREE.ShaderChunk[ "lightmap_vertex" ],
  10753. THREE.ShaderChunk[ "color_vertex" ],
  10754. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10755. THREE.ShaderChunk[ "skinbase_vertex" ],
  10756. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10757. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10758. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10759. THREE.ShaderChunk[ "skinning_vertex" ],
  10760. THREE.ShaderChunk[ "default_vertex" ],
  10761. THREE.ShaderChunk[ "worldpos_vertex" ],
  10762. THREE.ShaderChunk[ "envmap_vertex" ],
  10763. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10764. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10765. "}"
  10766. ].join("\n"),
  10767. fragmentShader: [
  10768. "uniform float opacity;",
  10769. "varying vec3 vLightFront;",
  10770. "#ifdef DOUBLE_SIDED",
  10771. "varying vec3 vLightBack;",
  10772. "#endif",
  10773. THREE.ShaderChunk[ "color_pars_fragment" ],
  10774. THREE.ShaderChunk[ "map_pars_fragment" ],
  10775. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10776. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10777. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10778. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10779. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10780. "void main() {",
  10781. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10782. THREE.ShaderChunk[ "map_fragment" ],
  10783. THREE.ShaderChunk[ "alphatest_fragment" ],
  10784. THREE.ShaderChunk[ "specularmap_fragment" ],
  10785. "#ifdef DOUBLE_SIDED",
  10786. //"float isFront = float( gl_FrontFacing );",
  10787. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10788. "if ( gl_FrontFacing )",
  10789. "gl_FragColor.xyz *= vLightFront;",
  10790. "else",
  10791. "gl_FragColor.xyz *= vLightBack;",
  10792. "#else",
  10793. "gl_FragColor.xyz *= vLightFront;",
  10794. "#endif",
  10795. THREE.ShaderChunk[ "lightmap_fragment" ],
  10796. THREE.ShaderChunk[ "color_fragment" ],
  10797. THREE.ShaderChunk[ "envmap_fragment" ],
  10798. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10799. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10800. THREE.ShaderChunk[ "fog_fragment" ],
  10801. "}"
  10802. ].join("\n")
  10803. },
  10804. 'phong': {
  10805. uniforms: THREE.UniformsUtils.merge( [
  10806. THREE.UniformsLib[ "common" ],
  10807. THREE.UniformsLib[ "bump" ],
  10808. THREE.UniformsLib[ "normalmap" ],
  10809. THREE.UniformsLib[ "fog" ],
  10810. THREE.UniformsLib[ "lights" ],
  10811. THREE.UniformsLib[ "shadowmap" ],
  10812. {
  10813. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10814. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10815. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10816. "shininess": { type: "f", value: 30 },
  10817. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10818. }
  10819. ] ),
  10820. vertexShader: [
  10821. "#define PHONG",
  10822. "varying vec3 vViewPosition;",
  10823. "varying vec3 vNormal;",
  10824. THREE.ShaderChunk[ "map_pars_vertex" ],
  10825. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10826. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10827. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10828. THREE.ShaderChunk[ "color_pars_vertex" ],
  10829. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10830. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10831. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10832. "void main() {",
  10833. THREE.ShaderChunk[ "map_vertex" ],
  10834. THREE.ShaderChunk[ "lightmap_vertex" ],
  10835. THREE.ShaderChunk[ "color_vertex" ],
  10836. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10837. THREE.ShaderChunk[ "skinbase_vertex" ],
  10838. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10839. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10840. "vNormal = normalize( transformedNormal );",
  10841. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10842. THREE.ShaderChunk[ "skinning_vertex" ],
  10843. THREE.ShaderChunk[ "default_vertex" ],
  10844. "vViewPosition = -mvPosition.xyz;",
  10845. THREE.ShaderChunk[ "worldpos_vertex" ],
  10846. THREE.ShaderChunk[ "envmap_vertex" ],
  10847. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10848. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10849. "}"
  10850. ].join("\n"),
  10851. fragmentShader: [
  10852. "uniform vec3 diffuse;",
  10853. "uniform float opacity;",
  10854. "uniform vec3 ambient;",
  10855. "uniform vec3 emissive;",
  10856. "uniform vec3 specular;",
  10857. "uniform float shininess;",
  10858. THREE.ShaderChunk[ "color_pars_fragment" ],
  10859. THREE.ShaderChunk[ "map_pars_fragment" ],
  10860. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10861. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10862. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10863. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10864. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10865. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10866. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10867. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10868. "void main() {",
  10869. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10870. THREE.ShaderChunk[ "map_fragment" ],
  10871. THREE.ShaderChunk[ "alphatest_fragment" ],
  10872. THREE.ShaderChunk[ "specularmap_fragment" ],
  10873. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10874. THREE.ShaderChunk[ "lightmap_fragment" ],
  10875. THREE.ShaderChunk[ "color_fragment" ],
  10876. THREE.ShaderChunk[ "envmap_fragment" ],
  10877. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10878. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10879. THREE.ShaderChunk[ "fog_fragment" ],
  10880. "}"
  10881. ].join("\n")
  10882. },
  10883. 'particle_basic': {
  10884. uniforms: THREE.UniformsUtils.merge( [
  10885. THREE.UniformsLib[ "particle" ],
  10886. THREE.UniformsLib[ "shadowmap" ]
  10887. ] ),
  10888. vertexShader: [
  10889. "uniform float size;",
  10890. "uniform float scale;",
  10891. THREE.ShaderChunk[ "color_pars_vertex" ],
  10892. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10893. "void main() {",
  10894. THREE.ShaderChunk[ "color_vertex" ],
  10895. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10896. "#ifdef USE_SIZEATTENUATION",
  10897. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10898. "#else",
  10899. "gl_PointSize = size;",
  10900. "#endif",
  10901. "gl_Position = projectionMatrix * mvPosition;",
  10902. THREE.ShaderChunk[ "worldpos_vertex" ],
  10903. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10904. "}"
  10905. ].join("\n"),
  10906. fragmentShader: [
  10907. "uniform vec3 psColor;",
  10908. "uniform float opacity;",
  10909. THREE.ShaderChunk[ "color_pars_fragment" ],
  10910. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10911. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10912. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10913. "void main() {",
  10914. "gl_FragColor = vec4( psColor, opacity );",
  10915. THREE.ShaderChunk[ "map_particle_fragment" ],
  10916. THREE.ShaderChunk[ "alphatest_fragment" ],
  10917. THREE.ShaderChunk[ "color_fragment" ],
  10918. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10919. THREE.ShaderChunk[ "fog_fragment" ],
  10920. "}"
  10921. ].join("\n")
  10922. },
  10923. 'dashed': {
  10924. uniforms: THREE.UniformsUtils.merge( [
  10925. THREE.UniformsLib[ "common" ],
  10926. THREE.UniformsLib[ "fog" ],
  10927. {
  10928. "scale": { type: "f", value: 1 },
  10929. "dashSize": { type: "f", value: 1 },
  10930. "totalSize": { type: "f", value: 2 }
  10931. }
  10932. ] ),
  10933. vertexShader: [
  10934. "uniform float scale;",
  10935. "attribute float lineDistance;",
  10936. "varying float vLineDistance;",
  10937. THREE.ShaderChunk[ "color_pars_vertex" ],
  10938. "void main() {",
  10939. THREE.ShaderChunk[ "color_vertex" ],
  10940. "vLineDistance = scale * lineDistance;",
  10941. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10942. "gl_Position = projectionMatrix * mvPosition;",
  10943. "}"
  10944. ].join("\n"),
  10945. fragmentShader: [
  10946. "uniform vec3 diffuse;",
  10947. "uniform float opacity;",
  10948. "uniform float dashSize;",
  10949. "uniform float totalSize;",
  10950. "varying float vLineDistance;",
  10951. THREE.ShaderChunk[ "color_pars_fragment" ],
  10952. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10953. "void main() {",
  10954. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10955. "discard;",
  10956. "}",
  10957. "gl_FragColor = vec4( diffuse, opacity );",
  10958. THREE.ShaderChunk[ "color_fragment" ],
  10959. THREE.ShaderChunk[ "fog_fragment" ],
  10960. "}"
  10961. ].join("\n")
  10962. },
  10963. 'depth': {
  10964. uniforms: {
  10965. "mNear": { type: "f", value: 1.0 },
  10966. "mFar" : { type: "f", value: 2000.0 },
  10967. "opacity" : { type: "f", value: 1.0 }
  10968. },
  10969. vertexShader: [
  10970. "void main() {",
  10971. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10972. "}"
  10973. ].join("\n"),
  10974. fragmentShader: [
  10975. "uniform float mNear;",
  10976. "uniform float mFar;",
  10977. "uniform float opacity;",
  10978. "void main() {",
  10979. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10980. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10981. "gl_FragColor = vec4( vec3( color ), opacity );",
  10982. "}"
  10983. ].join("\n")
  10984. },
  10985. 'normal': {
  10986. uniforms: {
  10987. "opacity" : { type: "f", value: 1.0 }
  10988. },
  10989. vertexShader: [
  10990. "varying vec3 vNormal;",
  10991. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10992. "void main() {",
  10993. "vNormal = normalize( normalMatrix * normal );",
  10994. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10995. THREE.ShaderChunk[ "default_vertex" ],
  10996. "}"
  10997. ].join("\n"),
  10998. fragmentShader: [
  10999. "uniform float opacity;",
  11000. "varying vec3 vNormal;",
  11001. "void main() {",
  11002. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11003. "}"
  11004. ].join("\n")
  11005. },
  11006. /* -------------------------------------------------------------------------
  11007. // Normal map shader
  11008. // - Blinn-Phong
  11009. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11010. // - point and directional lights (use with "lights: true" material option)
  11011. ------------------------------------------------------------------------- */
  11012. 'normalmap' : {
  11013. uniforms: THREE.UniformsUtils.merge( [
  11014. THREE.UniformsLib[ "fog" ],
  11015. THREE.UniformsLib[ "lights" ],
  11016. THREE.UniformsLib[ "shadowmap" ],
  11017. {
  11018. "enableAO" : { type: "i", value: 0 },
  11019. "enableDiffuse" : { type: "i", value: 0 },
  11020. "enableSpecular" : { type: "i", value: 0 },
  11021. "enableReflection": { type: "i", value: 0 },
  11022. "enableDisplacement": { type: "i", value: 0 },
  11023. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11024. "tDiffuse" : { type: "t", value: null },
  11025. "tCube" : { type: "t", value: null },
  11026. "tNormal" : { type: "t", value: null },
  11027. "tSpecular" : { type: "t", value: null },
  11028. "tAO" : { type: "t", value: null },
  11029. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11030. "uDisplacementBias": { type: "f", value: 0.0 },
  11031. "uDisplacementScale": { type: "f", value: 1.0 },
  11032. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11033. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11034. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11035. "uShininess": { type: "f", value: 30 },
  11036. "uOpacity": { type: "f", value: 1 },
  11037. "useRefract": { type: "i", value: 0 },
  11038. "uRefractionRatio": { type: "f", value: 0.98 },
  11039. "uReflectivity": { type: "f", value: 0.5 },
  11040. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11041. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11042. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11043. }
  11044. ] ),
  11045. fragmentShader: [
  11046. "uniform vec3 uAmbientColor;",
  11047. "uniform vec3 uDiffuseColor;",
  11048. "uniform vec3 uSpecularColor;",
  11049. "uniform float uShininess;",
  11050. "uniform float uOpacity;",
  11051. "uniform bool enableDiffuse;",
  11052. "uniform bool enableSpecular;",
  11053. "uniform bool enableAO;",
  11054. "uniform bool enableReflection;",
  11055. "uniform sampler2D tDiffuse;",
  11056. "uniform sampler2D tNormal;",
  11057. "uniform sampler2D tSpecular;",
  11058. "uniform sampler2D tAO;",
  11059. "uniform samplerCube tCube;",
  11060. "uniform vec2 uNormalScale;",
  11061. "uniform bool useRefract;",
  11062. "uniform float uRefractionRatio;",
  11063. "uniform float uReflectivity;",
  11064. "varying vec3 vTangent;",
  11065. "varying vec3 vBinormal;",
  11066. "varying vec3 vNormal;",
  11067. "varying vec2 vUv;",
  11068. "uniform vec3 ambientLightColor;",
  11069. "#if MAX_DIR_LIGHTS > 0",
  11070. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11071. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11072. "#endif",
  11073. "#if MAX_HEMI_LIGHTS > 0",
  11074. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11075. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11076. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11077. "#endif",
  11078. "#if MAX_POINT_LIGHTS > 0",
  11079. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11080. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11081. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11082. "#endif",
  11083. "#if MAX_SPOT_LIGHTS > 0",
  11084. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11085. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11086. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11087. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11088. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11089. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11090. "#endif",
  11091. "#ifdef WRAP_AROUND",
  11092. "uniform vec3 wrapRGB;",
  11093. "#endif",
  11094. "varying vec3 vWorldPosition;",
  11095. "varying vec3 vViewPosition;",
  11096. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11097. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11098. "void main() {",
  11099. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11100. "vec3 specularTex = vec3( 1.0 );",
  11101. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11102. "normalTex.xy *= uNormalScale;",
  11103. "normalTex = normalize( normalTex );",
  11104. "if( enableDiffuse ) {",
  11105. "#ifdef GAMMA_INPUT",
  11106. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11107. "texelColor.xyz *= texelColor.xyz;",
  11108. "gl_FragColor = gl_FragColor * texelColor;",
  11109. "#else",
  11110. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11111. "#endif",
  11112. "}",
  11113. "if( enableAO ) {",
  11114. "#ifdef GAMMA_INPUT",
  11115. "vec4 aoColor = texture2D( tAO, vUv );",
  11116. "aoColor.xyz *= aoColor.xyz;",
  11117. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11118. "#else",
  11119. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11120. "#endif",
  11121. "}",
  11122. "if( enableSpecular )",
  11123. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11124. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11125. "vec3 finalNormal = tsb * normalTex;",
  11126. "#ifdef FLIP_SIDED",
  11127. "finalNormal = -finalNormal;",
  11128. "#endif",
  11129. "vec3 normal = normalize( finalNormal );",
  11130. "vec3 viewPosition = normalize( vViewPosition );",
  11131. // point lights
  11132. "#if MAX_POINT_LIGHTS > 0",
  11133. "vec3 pointDiffuse = vec3( 0.0 );",
  11134. "vec3 pointSpecular = vec3( 0.0 );",
  11135. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11136. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11137. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11138. "float pointDistance = 1.0;",
  11139. "if ( pointLightDistance[ i ] > 0.0 )",
  11140. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11141. "pointVector = normalize( pointVector );",
  11142. // diffuse
  11143. "#ifdef WRAP_AROUND",
  11144. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11145. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11146. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11147. "#else",
  11148. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11149. "#endif",
  11150. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11151. // specular
  11152. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11153. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11154. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11155. "#ifdef PHYSICALLY_BASED_SHADING",
  11156. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11157. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11158. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11159. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11160. "#else",
  11161. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11162. "#endif",
  11163. "}",
  11164. "#endif",
  11165. // spot lights
  11166. "#if MAX_SPOT_LIGHTS > 0",
  11167. "vec3 spotDiffuse = vec3( 0.0 );",
  11168. "vec3 spotSpecular = vec3( 0.0 );",
  11169. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11170. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11171. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11172. "float spotDistance = 1.0;",
  11173. "if ( spotLightDistance[ i ] > 0.0 )",
  11174. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11175. "spotVector = normalize( spotVector );",
  11176. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11177. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11178. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11179. // diffuse
  11180. "#ifdef WRAP_AROUND",
  11181. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11182. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11183. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11184. "#else",
  11185. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11186. "#endif",
  11187. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11188. // specular
  11189. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11190. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11191. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11192. "#ifdef PHYSICALLY_BASED_SHADING",
  11193. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11194. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11195. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11196. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11197. "#else",
  11198. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11199. "#endif",
  11200. "}",
  11201. "}",
  11202. "#endif",
  11203. // directional lights
  11204. "#if MAX_DIR_LIGHTS > 0",
  11205. "vec3 dirDiffuse = vec3( 0.0 );",
  11206. "vec3 dirSpecular = vec3( 0.0 );",
  11207. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11208. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11209. "vec3 dirVector = normalize( lDirection.xyz );",
  11210. // diffuse
  11211. "#ifdef WRAP_AROUND",
  11212. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11213. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11214. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11215. "#else",
  11216. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11217. "#endif",
  11218. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11219. // specular
  11220. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11221. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11222. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11223. "#ifdef PHYSICALLY_BASED_SHADING",
  11224. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11225. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11226. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11227. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11228. "#else",
  11229. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11230. "#endif",
  11231. "}",
  11232. "#endif",
  11233. // hemisphere lights
  11234. "#if MAX_HEMI_LIGHTS > 0",
  11235. "vec3 hemiDiffuse = vec3( 0.0 );",
  11236. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11237. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11238. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11239. "vec3 lVector = normalize( lDirection.xyz );",
  11240. // diffuse
  11241. "float dotProduct = dot( normal, lVector );",
  11242. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11243. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11244. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11245. // specular (sky light)
  11246. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11247. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11248. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11249. // specular (ground light)
  11250. "vec3 lVectorGround = -lVector;",
  11251. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11252. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11253. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11254. "#ifdef PHYSICALLY_BASED_SHADING",
  11255. "float dotProductGround = dot( normal, lVectorGround );",
  11256. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11257. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11258. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11259. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11260. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11261. "#else",
  11262. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11263. "#endif",
  11264. "}",
  11265. "#endif",
  11266. // all lights contribution summation
  11267. "vec3 totalDiffuse = vec3( 0.0 );",
  11268. "vec3 totalSpecular = vec3( 0.0 );",
  11269. "#if MAX_DIR_LIGHTS > 0",
  11270. "totalDiffuse += dirDiffuse;",
  11271. "totalSpecular += dirSpecular;",
  11272. "#endif",
  11273. "#if MAX_HEMI_LIGHTS > 0",
  11274. "totalDiffuse += hemiDiffuse;",
  11275. "totalSpecular += hemiSpecular;",
  11276. "#endif",
  11277. "#if MAX_POINT_LIGHTS > 0",
  11278. "totalDiffuse += pointDiffuse;",
  11279. "totalSpecular += pointSpecular;",
  11280. "#endif",
  11281. "#if MAX_SPOT_LIGHTS > 0",
  11282. "totalDiffuse += spotDiffuse;",
  11283. "totalSpecular += spotSpecular;",
  11284. "#endif",
  11285. "#ifdef METAL",
  11286. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11287. "#else",
  11288. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11289. "#endif",
  11290. "if ( enableReflection ) {",
  11291. "vec3 vReflect;",
  11292. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11293. "if ( useRefract ) {",
  11294. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11295. "} else {",
  11296. "vReflect = reflect( cameraToVertex, normal );",
  11297. "}",
  11298. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11299. "#ifdef GAMMA_INPUT",
  11300. "cubeColor.xyz *= cubeColor.xyz;",
  11301. "#endif",
  11302. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11303. "}",
  11304. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11305. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11306. THREE.ShaderChunk[ "fog_fragment" ],
  11307. "}"
  11308. ].join("\n"),
  11309. vertexShader: [
  11310. "attribute vec4 tangent;",
  11311. "uniform vec2 uOffset;",
  11312. "uniform vec2 uRepeat;",
  11313. "uniform bool enableDisplacement;",
  11314. "#ifdef VERTEX_TEXTURES",
  11315. "uniform sampler2D tDisplacement;",
  11316. "uniform float uDisplacementScale;",
  11317. "uniform float uDisplacementBias;",
  11318. "#endif",
  11319. "varying vec3 vTangent;",
  11320. "varying vec3 vBinormal;",
  11321. "varying vec3 vNormal;",
  11322. "varying vec2 vUv;",
  11323. "varying vec3 vWorldPosition;",
  11324. "varying vec3 vViewPosition;",
  11325. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11326. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11327. "void main() {",
  11328. THREE.ShaderChunk[ "skinbase_vertex" ],
  11329. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11330. // normal, tangent and binormal vectors
  11331. "#ifdef USE_SKINNING",
  11332. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11333. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11334. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11335. "#else",
  11336. "vNormal = normalize( normalMatrix * normal );",
  11337. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11338. "#endif",
  11339. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11340. "vUv = uv * uRepeat + uOffset;",
  11341. // displacement mapping
  11342. "vec3 displacedPosition;",
  11343. "#ifdef VERTEX_TEXTURES",
  11344. "if ( enableDisplacement ) {",
  11345. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11346. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11347. "displacedPosition = position + normalize( normal ) * df;",
  11348. "} else {",
  11349. "#ifdef USE_SKINNING",
  11350. "vec4 skinVertex = vec4( position, 1.0 );",
  11351. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11352. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11353. "displacedPosition = skinned.xyz;",
  11354. "#else",
  11355. "displacedPosition = position;",
  11356. "#endif",
  11357. "}",
  11358. "#else",
  11359. "#ifdef USE_SKINNING",
  11360. "vec4 skinVertex = vec4( position, 1.0 );",
  11361. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11362. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11363. "displacedPosition = skinned.xyz;",
  11364. "#else",
  11365. "displacedPosition = position;",
  11366. "#endif",
  11367. "#endif",
  11368. //
  11369. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11370. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11371. "gl_Position = projectionMatrix * mvPosition;",
  11372. //
  11373. "vWorldPosition = worldPosition.xyz;",
  11374. "vViewPosition = -mvPosition.xyz;",
  11375. // shadows
  11376. "#ifdef USE_SHADOWMAP",
  11377. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11378. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11379. "}",
  11380. "#endif",
  11381. "}"
  11382. ].join("\n")
  11383. },
  11384. /* -------------------------------------------------------------------------
  11385. // Cube map shader
  11386. ------------------------------------------------------------------------- */
  11387. 'cube': {
  11388. uniforms: { "tCube": { type: "t", value: null },
  11389. "tFlip": { type: "f", value: -1 } },
  11390. vertexShader: [
  11391. "varying vec3 vWorldPosition;",
  11392. "void main() {",
  11393. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11394. "vWorldPosition = worldPosition.xyz;",
  11395. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11396. "}"
  11397. ].join("\n"),
  11398. fragmentShader: [
  11399. "uniform samplerCube tCube;",
  11400. "uniform float tFlip;",
  11401. "varying vec3 vWorldPosition;",
  11402. "void main() {",
  11403. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11404. "}"
  11405. ].join("\n")
  11406. },
  11407. // Depth encoding into RGBA texture
  11408. // based on SpiderGL shadow map example
  11409. // http://spidergl.org/example.php?id=6
  11410. // originally from
  11411. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11412. // see also here:
  11413. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11414. 'depthRGBA': {
  11415. uniforms: {},
  11416. vertexShader: [
  11417. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11418. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11419. "void main() {",
  11420. THREE.ShaderChunk[ "skinbase_vertex" ],
  11421. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11422. THREE.ShaderChunk[ "skinning_vertex" ],
  11423. THREE.ShaderChunk[ "default_vertex" ],
  11424. "}"
  11425. ].join("\n"),
  11426. fragmentShader: [
  11427. "vec4 pack_depth( const in float depth ) {",
  11428. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11429. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11430. "vec4 res = fract( depth * bit_shift );",
  11431. "res -= res.xxyz * bit_mask;",
  11432. "return res;",
  11433. "}",
  11434. "void main() {",
  11435. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11436. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11437. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11438. //"gl_FragData[ 0 ] = pack_depth( z );",
  11439. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11440. "}"
  11441. ].join("\n")
  11442. }
  11443. };
  11444. /**
  11445. * @author supereggbert / http://www.paulbrunt.co.uk/
  11446. * @author mrdoob / http://mrdoob.com/
  11447. * @author alteredq / http://alteredqualia.com/
  11448. * @author szimek / https://github.com/szimek/
  11449. */
  11450. THREE.WebGLRenderer = function ( parameters ) {
  11451. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11452. parameters = parameters || {};
  11453. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11454. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11455. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  11456. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11457. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11458. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11459. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11460. _clearColor = new THREE.Color( 0x000000 ),
  11461. _clearAlpha = 0;
  11462. if ( parameters.clearColor !== undefined ) {
  11463. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11464. _clearColor.setHex( parameters.clearColor );
  11465. }
  11466. if ( parameters.clearAlpha !== undefined ) {
  11467. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11468. _clearAlpha = parameters.clearAlpha;
  11469. }
  11470. // public properties
  11471. this.domElement = _canvas;
  11472. this.context = null;
  11473. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11474. ? parameters.devicePixelRatio
  11475. : window.devicePixelRatio !== undefined
  11476. ? window.devicePixelRatio
  11477. : 1;
  11478. // clearing
  11479. this.autoClear = true;
  11480. this.autoClearColor = true;
  11481. this.autoClearDepth = true;
  11482. this.autoClearStencil = true;
  11483. // scene graph
  11484. this.sortObjects = true;
  11485. this.autoUpdateObjects = true;
  11486. // physically based shading
  11487. this.gammaInput = false;
  11488. this.gammaOutput = false;
  11489. this.physicallyBasedShading = false;
  11490. // shadow map
  11491. this.shadowMapEnabled = false;
  11492. this.shadowMapAutoUpdate = true;
  11493. this.shadowMapType = THREE.PCFShadowMap;
  11494. this.shadowMapCullFace = THREE.CullFaceFront;
  11495. this.shadowMapDebug = false;
  11496. this.shadowMapCascade = false;
  11497. // morphs
  11498. this.maxMorphTargets = 8;
  11499. this.maxMorphNormals = 4;
  11500. // flags
  11501. this.autoScaleCubemaps = true;
  11502. // custom render plugins
  11503. this.renderPluginsPre = [];
  11504. this.renderPluginsPost = [];
  11505. // info
  11506. this.info = {
  11507. memory: {
  11508. programs: 0,
  11509. geometries: 0,
  11510. textures: 0
  11511. },
  11512. render: {
  11513. calls: 0,
  11514. vertices: 0,
  11515. faces: 0,
  11516. points: 0
  11517. }
  11518. };
  11519. // internal properties
  11520. var _this = this,
  11521. _programs = [],
  11522. _programs_counter = 0,
  11523. // internal state cache
  11524. _currentProgram = null,
  11525. _currentFramebuffer = null,
  11526. _currentMaterialId = -1,
  11527. _currentGeometryGroupHash = null,
  11528. _currentCamera = null,
  11529. _geometryGroupCounter = 0,
  11530. _usedTextureUnits = 0,
  11531. // GL state cache
  11532. _oldDoubleSided = -1,
  11533. _oldFlipSided = -1,
  11534. _oldBlending = -1,
  11535. _oldBlendEquation = -1,
  11536. _oldBlendSrc = -1,
  11537. _oldBlendDst = -1,
  11538. _oldDepthTest = -1,
  11539. _oldDepthWrite = -1,
  11540. _oldPolygonOffset = null,
  11541. _oldPolygonOffsetFactor = null,
  11542. _oldPolygonOffsetUnits = null,
  11543. _oldLineWidth = null,
  11544. _viewportX = 0,
  11545. _viewportY = 0,
  11546. _viewportWidth = 0,
  11547. _viewportHeight = 0,
  11548. _currentWidth = 0,
  11549. _currentHeight = 0,
  11550. _enabledAttributes = {},
  11551. // frustum
  11552. _frustum = new THREE.Frustum(),
  11553. // camera matrices cache
  11554. _projScreenMatrix = new THREE.Matrix4(),
  11555. _projScreenMatrixPS = new THREE.Matrix4(),
  11556. _vector3 = new THREE.Vector3(),
  11557. // light arrays cache
  11558. _direction = new THREE.Vector3(),
  11559. _lightsNeedUpdate = true,
  11560. _lights = {
  11561. ambient: [ 0, 0, 0 ],
  11562. directional: { length: 0, colors: new Array(), positions: new Array() },
  11563. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11564. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11565. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11566. };
  11567. // initialize
  11568. var _gl;
  11569. var _glExtensionTextureFloat;
  11570. var _glExtensionTextureFloatLinear;
  11571. var _glExtensionStandardDerivatives;
  11572. var _glExtensionTextureFilterAnisotropic;
  11573. var _glExtensionCompressedTextureS3TC;
  11574. initGL();
  11575. setDefaultGLState();
  11576. this.context = _gl;
  11577. // GPU capabilities
  11578. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11579. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11580. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11581. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11582. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11583. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11584. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11585. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11586. //
  11587. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11588. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11589. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11590. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11591. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11592. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11593. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11594. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11595. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11596. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11597. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11598. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11599. // clamp precision to maximum available
  11600. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11601. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11602. if ( _precision === "highp" && ! highpAvailable ) {
  11603. if ( mediumpAvailable ) {
  11604. _precision = "mediump";
  11605. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11606. } else {
  11607. _precision = "lowp";
  11608. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11609. }
  11610. }
  11611. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11612. _precision = "lowp";
  11613. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11614. }
  11615. // API
  11616. this.getContext = function () {
  11617. return _gl;
  11618. };
  11619. this.supportsVertexTextures = function () {
  11620. return _supportsVertexTextures;
  11621. };
  11622. this.supportsFloatTextures = function () {
  11623. return _glExtensionTextureFloat;
  11624. };
  11625. this.supportsStandardDerivatives = function () {
  11626. return _glExtensionStandardDerivatives;
  11627. };
  11628. this.supportsCompressedTextureS3TC = function () {
  11629. return _glExtensionCompressedTextureS3TC;
  11630. };
  11631. this.getMaxAnisotropy = function () {
  11632. return _maxAnisotropy;
  11633. };
  11634. this.getPrecision = function () {
  11635. return _precision;
  11636. };
  11637. this.setSize = function ( width, height, updateStyle ) {
  11638. _canvas.width = width * this.devicePixelRatio;
  11639. _canvas.height = height * this.devicePixelRatio;
  11640. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11641. _canvas.style.width = width + 'px';
  11642. _canvas.style.height = height + 'px';
  11643. }
  11644. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11645. };
  11646. this.setViewport = function ( x, y, width, height ) {
  11647. _viewportX = x !== undefined ? x : 0;
  11648. _viewportY = y !== undefined ? y : 0;
  11649. _viewportWidth = width !== undefined ? width : _canvas.width;
  11650. _viewportHeight = height !== undefined ? height : _canvas.height;
  11651. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11652. };
  11653. this.setScissor = function ( x, y, width, height ) {
  11654. _gl.scissor( x, y, width, height );
  11655. };
  11656. this.enableScissorTest = function ( enable ) {
  11657. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11658. };
  11659. // Clearing
  11660. this.setClearColor = function ( color, alpha ) {
  11661. _clearColor.set( color );
  11662. _clearAlpha = alpha !== undefined ? alpha : 1;
  11663. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11664. };
  11665. this.setClearColorHex = function ( hex, alpha ) {
  11666. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11667. this.setClearColor( hex, alpha );
  11668. };
  11669. this.getClearColor = function () {
  11670. return _clearColor;
  11671. };
  11672. this.getClearAlpha = function () {
  11673. return _clearAlpha;
  11674. };
  11675. this.clear = function ( color, depth, stencil ) {
  11676. var bits = 0;
  11677. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11678. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11679. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11680. _gl.clear( bits );
  11681. };
  11682. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11683. this.setRenderTarget( renderTarget );
  11684. this.clear( color, depth, stencil );
  11685. };
  11686. // Plugins
  11687. this.addPostPlugin = function ( plugin ) {
  11688. plugin.init( this );
  11689. this.renderPluginsPost.push( plugin );
  11690. };
  11691. this.addPrePlugin = function ( plugin ) {
  11692. plugin.init( this );
  11693. this.renderPluginsPre.push( plugin );
  11694. };
  11695. // Rendering
  11696. this.updateShadowMap = function ( scene, camera ) {
  11697. _currentProgram = null;
  11698. _oldBlending = -1;
  11699. _oldDepthTest = -1;
  11700. _oldDepthWrite = -1;
  11701. _currentGeometryGroupHash = -1;
  11702. _currentMaterialId = -1;
  11703. _lightsNeedUpdate = true;
  11704. _oldDoubleSided = -1;
  11705. _oldFlipSided = -1;
  11706. this.shadowMapPlugin.update( scene, camera );
  11707. };
  11708. // Internal functions
  11709. // Buffer allocation
  11710. function createParticleBuffers ( geometry ) {
  11711. geometry.__webglVertexBuffer = _gl.createBuffer();
  11712. geometry.__webglColorBuffer = _gl.createBuffer();
  11713. _this.info.memory.geometries ++;
  11714. };
  11715. function createLineBuffers ( geometry ) {
  11716. geometry.__webglVertexBuffer = _gl.createBuffer();
  11717. geometry.__webglColorBuffer = _gl.createBuffer();
  11718. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11719. _this.info.memory.geometries ++;
  11720. };
  11721. function createRibbonBuffers ( geometry ) {
  11722. geometry.__webglVertexBuffer = _gl.createBuffer();
  11723. geometry.__webglColorBuffer = _gl.createBuffer();
  11724. geometry.__webglNormalBuffer = _gl.createBuffer();
  11725. _this.info.memory.geometries ++;
  11726. };
  11727. function createMeshBuffers ( geometryGroup ) {
  11728. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11729. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11730. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11731. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11732. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11733. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11734. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11735. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11736. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11737. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11738. var m, ml;
  11739. if ( geometryGroup.numMorphTargets ) {
  11740. geometryGroup.__webglMorphTargetsBuffers = [];
  11741. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11742. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11743. }
  11744. }
  11745. if ( geometryGroup.numMorphNormals ) {
  11746. geometryGroup.__webglMorphNormalsBuffers = [];
  11747. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11748. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11749. }
  11750. }
  11751. _this.info.memory.geometries ++;
  11752. };
  11753. // Events
  11754. var onGeometryDispose = function ( event ) {
  11755. var geometry = event.target;
  11756. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11757. deallocateGeometry( geometry );
  11758. _this.info.memory.geometries --;
  11759. };
  11760. var onTextureDispose = function ( event ) {
  11761. var texture = event.target;
  11762. texture.removeEventListener( 'dispose', onTextureDispose );
  11763. deallocateTexture( texture );
  11764. _this.info.memory.textures --;
  11765. };
  11766. var onRenderTargetDispose = function ( event ) {
  11767. var renderTarget = event.target;
  11768. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11769. deallocateRenderTarget( renderTarget );
  11770. _this.info.memory.textures --;
  11771. };
  11772. var onMaterialDispose = function ( event ) {
  11773. var material = event.target;
  11774. material.removeEventListener( 'dispose', onMaterialDispose );
  11775. deallocateMaterial( material );
  11776. };
  11777. // Buffer deallocation
  11778. var deallocateGeometry = function ( geometry ) {
  11779. geometry.__webglInit = undefined;
  11780. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11781. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11782. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11783. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11784. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11785. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11786. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11787. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11788. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11789. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11790. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11791. // geometry groups
  11792. if ( geometry.geometryGroups !== undefined ) {
  11793. for ( var g in geometry.geometryGroups ) {
  11794. var geometryGroup = geometry.geometryGroups[ g ];
  11795. if ( geometryGroup.numMorphTargets !== undefined ) {
  11796. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11797. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11798. }
  11799. }
  11800. if ( geometryGroup.numMorphNormals !== undefined ) {
  11801. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11802. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11803. }
  11804. }
  11805. deleteCustomAttributesBuffers( geometryGroup );
  11806. }
  11807. }
  11808. deleteCustomAttributesBuffers( geometry );
  11809. };
  11810. var deallocateTexture = function ( texture ) {
  11811. if ( texture.image && texture.image.__webglTextureCube ) {
  11812. // cube texture
  11813. _gl.deleteTexture( texture.image.__webglTextureCube );
  11814. } else {
  11815. // 2D texture
  11816. if ( ! texture.__webglInit ) return;
  11817. texture.__webglInit = false;
  11818. _gl.deleteTexture( texture.__webglTexture );
  11819. }
  11820. };
  11821. var deallocateRenderTarget = function ( renderTarget ) {
  11822. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11823. _gl.deleteTexture( renderTarget.__webglTexture );
  11824. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11825. for ( var i = 0; i < 6; i ++ ) {
  11826. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11827. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11828. }
  11829. } else {
  11830. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11831. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11832. }
  11833. };
  11834. var deallocateMaterial = function ( material ) {
  11835. var program = material.program;
  11836. if ( program === undefined ) return;
  11837. material.program = undefined;
  11838. // only deallocate GL program if this was the last use of shared program
  11839. // assumed there is only single copy of any program in the _programs list
  11840. // (that's how it's constructed)
  11841. var i, il, programInfo;
  11842. var deleteProgram = false;
  11843. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11844. programInfo = _programs[ i ];
  11845. if ( programInfo.program === program ) {
  11846. programInfo.usedTimes --;
  11847. if ( programInfo.usedTimes === 0 ) {
  11848. deleteProgram = true;
  11849. }
  11850. break;
  11851. }
  11852. }
  11853. if ( deleteProgram === true ) {
  11854. // avoid using array.splice, this is costlier than creating new array from scratch
  11855. var newPrograms = [];
  11856. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11857. programInfo = _programs[ i ];
  11858. if ( programInfo.program !== program ) {
  11859. newPrograms.push( programInfo );
  11860. }
  11861. }
  11862. _programs = newPrograms;
  11863. _gl.deleteProgram( program );
  11864. _this.info.memory.programs --;
  11865. }
  11866. };
  11867. //
  11868. function deleteCustomAttributesBuffers( geometry ) {
  11869. if ( geometry.__webglCustomAttributesList ) {
  11870. for ( var id in geometry.__webglCustomAttributesList ) {
  11871. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11872. }
  11873. }
  11874. };
  11875. // Buffer initialization
  11876. function initCustomAttributes ( geometry, object ) {
  11877. var nvertices = geometry.vertices.length;
  11878. var material = object.material;
  11879. if ( material.attributes ) {
  11880. if ( geometry.__webglCustomAttributesList === undefined ) {
  11881. geometry.__webglCustomAttributesList = [];
  11882. }
  11883. for ( var a in material.attributes ) {
  11884. var attribute = material.attributes[ a ];
  11885. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11886. attribute.__webglInitialized = true;
  11887. var size = 1; // "f" and "i"
  11888. if ( attribute.type === "v2" ) size = 2;
  11889. else if ( attribute.type === "v3" ) size = 3;
  11890. else if ( attribute.type === "v4" ) size = 4;
  11891. else if ( attribute.type === "c" ) size = 3;
  11892. attribute.size = size;
  11893. attribute.array = new Float32Array( nvertices * size );
  11894. attribute.buffer = _gl.createBuffer();
  11895. attribute.buffer.belongsToAttribute = a;
  11896. attribute.needsUpdate = true;
  11897. }
  11898. geometry.__webglCustomAttributesList.push( attribute );
  11899. }
  11900. }
  11901. };
  11902. function initParticleBuffers ( geometry, object ) {
  11903. var nvertices = geometry.vertices.length;
  11904. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11905. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11906. geometry.__sortArray = [];
  11907. geometry.__webglParticleCount = nvertices;
  11908. initCustomAttributes ( geometry, object );
  11909. };
  11910. function initLineBuffers ( geometry, object ) {
  11911. var nvertices = geometry.vertices.length;
  11912. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11913. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11914. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11915. geometry.__webglLineCount = nvertices;
  11916. initCustomAttributes ( geometry, object );
  11917. };
  11918. function initRibbonBuffers ( geometry, object ) {
  11919. var nvertices = geometry.vertices.length;
  11920. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11921. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11922. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11923. geometry.__webglVertexCount = nvertices;
  11924. initCustomAttributes ( geometry, object );
  11925. };
  11926. function initMeshBuffers ( geometryGroup, object ) {
  11927. var geometry = object.geometry,
  11928. faces3 = geometryGroup.faces3,
  11929. faces4 = geometryGroup.faces4,
  11930. nvertices = faces3.length * 3 + faces4.length * 4,
  11931. ntris = faces3.length * 1 + faces4.length * 2,
  11932. nlines = faces3.length * 3 + faces4.length * 4,
  11933. material = getBufferMaterial( object, geometryGroup ),
  11934. uvType = bufferGuessUVType( material ),
  11935. normalType = bufferGuessNormalType( material ),
  11936. vertexColorType = bufferGuessVertexColorType( material );
  11937. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11938. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11939. if ( normalType ) {
  11940. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11941. }
  11942. if ( geometry.hasTangents ) {
  11943. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11944. }
  11945. if ( vertexColorType ) {
  11946. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11947. }
  11948. if ( uvType ) {
  11949. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11950. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11951. }
  11952. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11953. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11954. }
  11955. }
  11956. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11957. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11958. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11959. }
  11960. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11961. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11962. var m, ml;
  11963. if ( geometryGroup.numMorphTargets ) {
  11964. geometryGroup.__morphTargetsArrays = [];
  11965. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11966. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11967. }
  11968. }
  11969. if ( geometryGroup.numMorphNormals ) {
  11970. geometryGroup.__morphNormalsArrays = [];
  11971. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11972. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11973. }
  11974. }
  11975. geometryGroup.__webglFaceCount = ntris * 3;
  11976. geometryGroup.__webglLineCount = nlines * 2;
  11977. // custom attributes
  11978. if ( material.attributes ) {
  11979. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11980. geometryGroup.__webglCustomAttributesList = [];
  11981. }
  11982. for ( var a in material.attributes ) {
  11983. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11984. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11985. var originalAttribute = material.attributes[ a ];
  11986. var attribute = {};
  11987. for ( var property in originalAttribute ) {
  11988. attribute[ property ] = originalAttribute[ property ];
  11989. }
  11990. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11991. attribute.__webglInitialized = true;
  11992. var size = 1; // "f" and "i"
  11993. if( attribute.type === "v2" ) size = 2;
  11994. else if( attribute.type === "v3" ) size = 3;
  11995. else if( attribute.type === "v4" ) size = 4;
  11996. else if( attribute.type === "c" ) size = 3;
  11997. attribute.size = size;
  11998. attribute.array = new Float32Array( nvertices * size );
  11999. attribute.buffer = _gl.createBuffer();
  12000. attribute.buffer.belongsToAttribute = a;
  12001. originalAttribute.needsUpdate = true;
  12002. attribute.__original = originalAttribute;
  12003. }
  12004. geometryGroup.__webglCustomAttributesList.push( attribute );
  12005. }
  12006. }
  12007. geometryGroup.__inittedArrays = true;
  12008. };
  12009. function getBufferMaterial( object, geometryGroup ) {
  12010. return object.material instanceof THREE.MeshFaceMaterial
  12011. ? object.material.materials[ geometryGroup.materialIndex ]
  12012. : object.material;
  12013. };
  12014. function materialNeedsSmoothNormals ( material ) {
  12015. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12016. };
  12017. function bufferGuessNormalType ( material ) {
  12018. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12019. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12020. return false;
  12021. }
  12022. if ( materialNeedsSmoothNormals( material ) ) {
  12023. return THREE.SmoothShading;
  12024. } else {
  12025. return THREE.FlatShading;
  12026. }
  12027. };
  12028. function bufferGuessVertexColorType( material ) {
  12029. if ( material.vertexColors ) {
  12030. return material.vertexColors;
  12031. }
  12032. return false;
  12033. };
  12034. function bufferGuessUVType( material ) {
  12035. // material must use some texture to require uvs
  12036. if ( material.map ||
  12037. material.lightMap ||
  12038. material.bumpMap ||
  12039. material.normalMap ||
  12040. material.specularMap ||
  12041. material instanceof THREE.ShaderMaterial ) {
  12042. return true;
  12043. }
  12044. return false;
  12045. };
  12046. //
  12047. function initDirectBuffers( geometry ) {
  12048. var a, attribute, type;
  12049. for ( a in geometry.attributes ) {
  12050. if ( a === "index" ) {
  12051. type = _gl.ELEMENT_ARRAY_BUFFER;
  12052. } else {
  12053. type = _gl.ARRAY_BUFFER;
  12054. }
  12055. attribute = geometry.attributes[ a ];
  12056. if ( attribute.numItems === undefined ) {
  12057. attribute.numItems = attribute.array.length;
  12058. }
  12059. attribute.buffer = _gl.createBuffer();
  12060. _gl.bindBuffer( type, attribute.buffer );
  12061. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12062. }
  12063. };
  12064. // Buffer setting
  12065. function setParticleBuffers ( geometry, hint, object ) {
  12066. var v, c, vertex, offset, index, color,
  12067. vertices = geometry.vertices,
  12068. vl = vertices.length,
  12069. colors = geometry.colors,
  12070. cl = colors.length,
  12071. vertexArray = geometry.__vertexArray,
  12072. colorArray = geometry.__colorArray,
  12073. sortArray = geometry.__sortArray,
  12074. dirtyVertices = geometry.verticesNeedUpdate,
  12075. dirtyElements = geometry.elementsNeedUpdate,
  12076. dirtyColors = geometry.colorsNeedUpdate,
  12077. customAttributes = geometry.__webglCustomAttributesList,
  12078. i, il,
  12079. a, ca, cal, value,
  12080. customAttribute;
  12081. if ( object.sortParticles ) {
  12082. _projScreenMatrixPS.copy( _projScreenMatrix );
  12083. _projScreenMatrixPS.multiply( object.matrixWorld );
  12084. for ( v = 0; v < vl; v ++ ) {
  12085. vertex = vertices[ v ];
  12086. _vector3.copy( vertex );
  12087. _vector3.applyProjection( _projScreenMatrixPS );
  12088. sortArray[ v ] = [ _vector3.z, v ];
  12089. }
  12090. sortArray.sort( numericalSort );
  12091. for ( v = 0; v < vl; v ++ ) {
  12092. vertex = vertices[ sortArray[v][1] ];
  12093. offset = v * 3;
  12094. vertexArray[ offset ] = vertex.x;
  12095. vertexArray[ offset + 1 ] = vertex.y;
  12096. vertexArray[ offset + 2 ] = vertex.z;
  12097. }
  12098. for ( c = 0; c < cl; c ++ ) {
  12099. offset = c * 3;
  12100. color = colors[ sortArray[c][1] ];
  12101. colorArray[ offset ] = color.r;
  12102. colorArray[ offset + 1 ] = color.g;
  12103. colorArray[ offset + 2 ] = color.b;
  12104. }
  12105. if ( customAttributes ) {
  12106. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12107. customAttribute = customAttributes[ i ];
  12108. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12109. offset = 0;
  12110. cal = customAttribute.value.length;
  12111. if ( customAttribute.size === 1 ) {
  12112. for ( ca = 0; ca < cal; ca ++ ) {
  12113. index = sortArray[ ca ][ 1 ];
  12114. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12115. }
  12116. } else if ( customAttribute.size === 2 ) {
  12117. for ( ca = 0; ca < cal; ca ++ ) {
  12118. index = sortArray[ ca ][ 1 ];
  12119. value = customAttribute.value[ index ];
  12120. customAttribute.array[ offset ] = value.x;
  12121. customAttribute.array[ offset + 1 ] = value.y;
  12122. offset += 2;
  12123. }
  12124. } else if ( customAttribute.size === 3 ) {
  12125. if ( customAttribute.type === "c" ) {
  12126. for ( ca = 0; ca < cal; ca ++ ) {
  12127. index = sortArray[ ca ][ 1 ];
  12128. value = customAttribute.value[ index ];
  12129. customAttribute.array[ offset ] = value.r;
  12130. customAttribute.array[ offset + 1 ] = value.g;
  12131. customAttribute.array[ offset + 2 ] = value.b;
  12132. offset += 3;
  12133. }
  12134. } else {
  12135. for ( ca = 0; ca < cal; ca ++ ) {
  12136. index = sortArray[ ca ][ 1 ];
  12137. value = customAttribute.value[ index ];
  12138. customAttribute.array[ offset ] = value.x;
  12139. customAttribute.array[ offset + 1 ] = value.y;
  12140. customAttribute.array[ offset + 2 ] = value.z;
  12141. offset += 3;
  12142. }
  12143. }
  12144. } else if ( customAttribute.size === 4 ) {
  12145. for ( ca = 0; ca < cal; ca ++ ) {
  12146. index = sortArray[ ca ][ 1 ];
  12147. value = customAttribute.value[ index ];
  12148. customAttribute.array[ offset ] = value.x;
  12149. customAttribute.array[ offset + 1 ] = value.y;
  12150. customAttribute.array[ offset + 2 ] = value.z;
  12151. customAttribute.array[ offset + 3 ] = value.w;
  12152. offset += 4;
  12153. }
  12154. }
  12155. }
  12156. }
  12157. } else {
  12158. if ( dirtyVertices ) {
  12159. for ( v = 0; v < vl; v ++ ) {
  12160. vertex = vertices[ v ];
  12161. offset = v * 3;
  12162. vertexArray[ offset ] = vertex.x;
  12163. vertexArray[ offset + 1 ] = vertex.y;
  12164. vertexArray[ offset + 2 ] = vertex.z;
  12165. }
  12166. }
  12167. if ( dirtyColors ) {
  12168. for ( c = 0; c < cl; c ++ ) {
  12169. color = colors[ c ];
  12170. offset = c * 3;
  12171. colorArray[ offset ] = color.r;
  12172. colorArray[ offset + 1 ] = color.g;
  12173. colorArray[ offset + 2 ] = color.b;
  12174. }
  12175. }
  12176. if ( customAttributes ) {
  12177. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12178. customAttribute = customAttributes[ i ];
  12179. if ( customAttribute.needsUpdate &&
  12180. ( customAttribute.boundTo === undefined ||
  12181. customAttribute.boundTo === "vertices") ) {
  12182. cal = customAttribute.value.length;
  12183. offset = 0;
  12184. if ( customAttribute.size === 1 ) {
  12185. for ( ca = 0; ca < cal; ca ++ ) {
  12186. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12187. }
  12188. } else if ( customAttribute.size === 2 ) {
  12189. for ( ca = 0; ca < cal; ca ++ ) {
  12190. value = customAttribute.value[ ca ];
  12191. customAttribute.array[ offset ] = value.x;
  12192. customAttribute.array[ offset + 1 ] = value.y;
  12193. offset += 2;
  12194. }
  12195. } else if ( customAttribute.size === 3 ) {
  12196. if ( customAttribute.type === "c" ) {
  12197. for ( ca = 0; ca < cal; ca ++ ) {
  12198. value = customAttribute.value[ ca ];
  12199. customAttribute.array[ offset ] = value.r;
  12200. customAttribute.array[ offset + 1 ] = value.g;
  12201. customAttribute.array[ offset + 2 ] = value.b;
  12202. offset += 3;
  12203. }
  12204. } else {
  12205. for ( ca = 0; ca < cal; ca ++ ) {
  12206. value = customAttribute.value[ ca ];
  12207. customAttribute.array[ offset ] = value.x;
  12208. customAttribute.array[ offset + 1 ] = value.y;
  12209. customAttribute.array[ offset + 2 ] = value.z;
  12210. offset += 3;
  12211. }
  12212. }
  12213. } else if ( customAttribute.size === 4 ) {
  12214. for ( ca = 0; ca < cal; ca ++ ) {
  12215. value = customAttribute.value[ ca ];
  12216. customAttribute.array[ offset ] = value.x;
  12217. customAttribute.array[ offset + 1 ] = value.y;
  12218. customAttribute.array[ offset + 2 ] = value.z;
  12219. customAttribute.array[ offset + 3 ] = value.w;
  12220. offset += 4;
  12221. }
  12222. }
  12223. }
  12224. }
  12225. }
  12226. }
  12227. if ( dirtyVertices || object.sortParticles ) {
  12228. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12229. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12230. }
  12231. if ( dirtyColors || object.sortParticles ) {
  12232. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12233. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12234. }
  12235. if ( customAttributes ) {
  12236. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12237. customAttribute = customAttributes[ i ];
  12238. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12239. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12240. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12241. }
  12242. }
  12243. }
  12244. };
  12245. function setLineBuffers ( geometry, hint ) {
  12246. var v, c, d, vertex, offset, color,
  12247. vertices = geometry.vertices,
  12248. colors = geometry.colors,
  12249. lineDistances = geometry.lineDistances,
  12250. vl = vertices.length,
  12251. cl = colors.length,
  12252. dl = lineDistances.length,
  12253. vertexArray = geometry.__vertexArray,
  12254. colorArray = geometry.__colorArray,
  12255. lineDistanceArray = geometry.__lineDistanceArray,
  12256. dirtyVertices = geometry.verticesNeedUpdate,
  12257. dirtyColors = geometry.colorsNeedUpdate,
  12258. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12259. customAttributes = geometry.__webglCustomAttributesList,
  12260. i, il,
  12261. a, ca, cal, value,
  12262. customAttribute;
  12263. if ( dirtyVertices ) {
  12264. for ( v = 0; v < vl; v ++ ) {
  12265. vertex = vertices[ v ];
  12266. offset = v * 3;
  12267. vertexArray[ offset ] = vertex.x;
  12268. vertexArray[ offset + 1 ] = vertex.y;
  12269. vertexArray[ offset + 2 ] = vertex.z;
  12270. }
  12271. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12272. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12273. }
  12274. if ( dirtyColors ) {
  12275. for ( c = 0; c < cl; c ++ ) {
  12276. color = colors[ c ];
  12277. offset = c * 3;
  12278. colorArray[ offset ] = color.r;
  12279. colorArray[ offset + 1 ] = color.g;
  12280. colorArray[ offset + 2 ] = color.b;
  12281. }
  12282. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12283. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12284. }
  12285. if ( dirtyLineDistances ) {
  12286. for ( d = 0; d < dl; d ++ ) {
  12287. lineDistanceArray[ d ] = lineDistances[ d ];
  12288. }
  12289. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12290. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12291. }
  12292. if ( customAttributes ) {
  12293. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12294. customAttribute = customAttributes[ i ];
  12295. if ( customAttribute.needsUpdate &&
  12296. ( customAttribute.boundTo === undefined ||
  12297. customAttribute.boundTo === "vertices" ) ) {
  12298. offset = 0;
  12299. cal = customAttribute.value.length;
  12300. if ( customAttribute.size === 1 ) {
  12301. for ( ca = 0; ca < cal; ca ++ ) {
  12302. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12303. }
  12304. } else if ( customAttribute.size === 2 ) {
  12305. for ( ca = 0; ca < cal; ca ++ ) {
  12306. value = customAttribute.value[ ca ];
  12307. customAttribute.array[ offset ] = value.x;
  12308. customAttribute.array[ offset + 1 ] = value.y;
  12309. offset += 2;
  12310. }
  12311. } else if ( customAttribute.size === 3 ) {
  12312. if ( customAttribute.type === "c" ) {
  12313. for ( ca = 0; ca < cal; ca ++ ) {
  12314. value = customAttribute.value[ ca ];
  12315. customAttribute.array[ offset ] = value.r;
  12316. customAttribute.array[ offset + 1 ] = value.g;
  12317. customAttribute.array[ offset + 2 ] = value.b;
  12318. offset += 3;
  12319. }
  12320. } else {
  12321. for ( ca = 0; ca < cal; ca ++ ) {
  12322. value = customAttribute.value[ ca ];
  12323. customAttribute.array[ offset ] = value.x;
  12324. customAttribute.array[ offset + 1 ] = value.y;
  12325. customAttribute.array[ offset + 2 ] = value.z;
  12326. offset += 3;
  12327. }
  12328. }
  12329. } else if ( customAttribute.size === 4 ) {
  12330. for ( ca = 0; ca < cal; ca ++ ) {
  12331. value = customAttribute.value[ ca ];
  12332. customAttribute.array[ offset ] = value.x;
  12333. customAttribute.array[ offset + 1 ] = value.y;
  12334. customAttribute.array[ offset + 2 ] = value.z;
  12335. customAttribute.array[ offset + 3 ] = value.w;
  12336. offset += 4;
  12337. }
  12338. }
  12339. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12340. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12341. }
  12342. }
  12343. }
  12344. };
  12345. function setRibbonBuffers ( geometry, hint ) {
  12346. var v, c, n, vertex, offset, color, normal,
  12347. i, il, ca, cal, customAttribute, value,
  12348. vertices = geometry.vertices,
  12349. colors = geometry.colors,
  12350. normals = geometry.normals,
  12351. vl = vertices.length,
  12352. cl = colors.length,
  12353. nl = normals.length,
  12354. vertexArray = geometry.__vertexArray,
  12355. colorArray = geometry.__colorArray,
  12356. normalArray = geometry.__normalArray,
  12357. dirtyVertices = geometry.verticesNeedUpdate,
  12358. dirtyColors = geometry.colorsNeedUpdate,
  12359. dirtyNormals = geometry.normalsNeedUpdate,
  12360. customAttributes = geometry.__webglCustomAttributesList;
  12361. if ( dirtyVertices ) {
  12362. for ( v = 0; v < vl; v ++ ) {
  12363. vertex = vertices[ v ];
  12364. offset = v * 3;
  12365. vertexArray[ offset ] = vertex.x;
  12366. vertexArray[ offset + 1 ] = vertex.y;
  12367. vertexArray[ offset + 2 ] = vertex.z;
  12368. }
  12369. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12370. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12371. }
  12372. if ( dirtyColors ) {
  12373. for ( c = 0; c < cl; c ++ ) {
  12374. color = colors[ c ];
  12375. offset = c * 3;
  12376. colorArray[ offset ] = color.r;
  12377. colorArray[ offset + 1 ] = color.g;
  12378. colorArray[ offset + 2 ] = color.b;
  12379. }
  12380. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12381. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12382. }
  12383. if ( dirtyNormals ) {
  12384. for ( n = 0; n < nl; n ++ ) {
  12385. normal = normals[ n ];
  12386. offset = n * 3;
  12387. normalArray[ offset ] = normal.x;
  12388. normalArray[ offset + 1 ] = normal.y;
  12389. normalArray[ offset + 2 ] = normal.z;
  12390. }
  12391. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  12392. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12393. }
  12394. if ( customAttributes ) {
  12395. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12396. customAttribute = customAttributes[ i ];
  12397. if ( customAttribute.needsUpdate &&
  12398. ( customAttribute.boundTo === undefined ||
  12399. customAttribute.boundTo === "vertices" ) ) {
  12400. offset = 0;
  12401. cal = customAttribute.value.length;
  12402. if ( customAttribute.size === 1 ) {
  12403. for ( ca = 0; ca < cal; ca ++ ) {
  12404. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12405. }
  12406. } else if ( customAttribute.size === 2 ) {
  12407. for ( ca = 0; ca < cal; ca ++ ) {
  12408. value = customAttribute.value[ ca ];
  12409. customAttribute.array[ offset ] = value.x;
  12410. customAttribute.array[ offset + 1 ] = value.y;
  12411. offset += 2;
  12412. }
  12413. } else if ( customAttribute.size === 3 ) {
  12414. if ( customAttribute.type === "c" ) {
  12415. for ( ca = 0; ca < cal; ca ++ ) {
  12416. value = customAttribute.value[ ca ];
  12417. customAttribute.array[ offset ] = value.r;
  12418. customAttribute.array[ offset + 1 ] = value.g;
  12419. customAttribute.array[ offset + 2 ] = value.b;
  12420. offset += 3;
  12421. }
  12422. } else {
  12423. for ( ca = 0; ca < cal; ca ++ ) {
  12424. value = customAttribute.value[ ca ];
  12425. customAttribute.array[ offset ] = value.x;
  12426. customAttribute.array[ offset + 1 ] = value.y;
  12427. customAttribute.array[ offset + 2 ] = value.z;
  12428. offset += 3;
  12429. }
  12430. }
  12431. } else if ( customAttribute.size === 4 ) {
  12432. for ( ca = 0; ca < cal; ca ++ ) {
  12433. value = customAttribute.value[ ca ];
  12434. customAttribute.array[ offset ] = value.x;
  12435. customAttribute.array[ offset + 1 ] = value.y;
  12436. customAttribute.array[ offset + 2 ] = value.z;
  12437. customAttribute.array[ offset + 3 ] = value.w;
  12438. offset += 4;
  12439. }
  12440. }
  12441. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12442. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12443. }
  12444. }
  12445. }
  12446. };
  12447. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12448. if ( ! geometryGroup.__inittedArrays ) {
  12449. return;
  12450. }
  12451. var normalType = bufferGuessNormalType( material ),
  12452. vertexColorType = bufferGuessVertexColorType( material ),
  12453. uvType = bufferGuessUVType( material ),
  12454. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12455. var f, fl, fi, face,
  12456. vertexNormals, faceNormal, normal,
  12457. vertexColors, faceColor,
  12458. vertexTangents,
  12459. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12460. c1, c2, c3, c4,
  12461. sw1, sw2, sw3, sw4,
  12462. si1, si2, si3, si4,
  12463. sa1, sa2, sa3, sa4,
  12464. sb1, sb2, sb3, sb4,
  12465. m, ml, i, il,
  12466. vn, uvi, uv2i,
  12467. vk, vkl, vka,
  12468. nka, chf, faceVertexNormals,
  12469. a,
  12470. vertexIndex = 0,
  12471. offset = 0,
  12472. offset_uv = 0,
  12473. offset_uv2 = 0,
  12474. offset_face = 0,
  12475. offset_normal = 0,
  12476. offset_tangent = 0,
  12477. offset_line = 0,
  12478. offset_color = 0,
  12479. offset_skin = 0,
  12480. offset_morphTarget = 0,
  12481. offset_custom = 0,
  12482. offset_customSrc = 0,
  12483. value,
  12484. vertexArray = geometryGroup.__vertexArray,
  12485. uvArray = geometryGroup.__uvArray,
  12486. uv2Array = geometryGroup.__uv2Array,
  12487. normalArray = geometryGroup.__normalArray,
  12488. tangentArray = geometryGroup.__tangentArray,
  12489. colorArray = geometryGroup.__colorArray,
  12490. skinIndexArray = geometryGroup.__skinIndexArray,
  12491. skinWeightArray = geometryGroup.__skinWeightArray,
  12492. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12493. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12494. customAttributes = geometryGroup.__webglCustomAttributesList,
  12495. customAttribute,
  12496. faceArray = geometryGroup.__faceArray,
  12497. lineArray = geometryGroup.__lineArray,
  12498. geometry = object.geometry, // this is shared for all chunks
  12499. dirtyVertices = geometry.verticesNeedUpdate,
  12500. dirtyElements = geometry.elementsNeedUpdate,
  12501. dirtyUvs = geometry.uvsNeedUpdate,
  12502. dirtyNormals = geometry.normalsNeedUpdate,
  12503. dirtyTangents = geometry.tangentsNeedUpdate,
  12504. dirtyColors = geometry.colorsNeedUpdate,
  12505. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12506. vertices = geometry.vertices,
  12507. chunk_faces3 = geometryGroup.faces3,
  12508. chunk_faces4 = geometryGroup.faces4,
  12509. obj_faces = geometry.faces,
  12510. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12511. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12512. obj_colors = geometry.colors,
  12513. obj_skinIndices = geometry.skinIndices,
  12514. obj_skinWeights = geometry.skinWeights,
  12515. morphTargets = geometry.morphTargets,
  12516. morphNormals = geometry.morphNormals;
  12517. if ( dirtyVertices ) {
  12518. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12519. face = obj_faces[ chunk_faces3[ f ] ];
  12520. v1 = vertices[ face.a ];
  12521. v2 = vertices[ face.b ];
  12522. v3 = vertices[ face.c ];
  12523. vertexArray[ offset ] = v1.x;
  12524. vertexArray[ offset + 1 ] = v1.y;
  12525. vertexArray[ offset + 2 ] = v1.z;
  12526. vertexArray[ offset + 3 ] = v2.x;
  12527. vertexArray[ offset + 4 ] = v2.y;
  12528. vertexArray[ offset + 5 ] = v2.z;
  12529. vertexArray[ offset + 6 ] = v3.x;
  12530. vertexArray[ offset + 7 ] = v3.y;
  12531. vertexArray[ offset + 8 ] = v3.z;
  12532. offset += 9;
  12533. }
  12534. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12535. face = obj_faces[ chunk_faces4[ f ] ];
  12536. v1 = vertices[ face.a ];
  12537. v2 = vertices[ face.b ];
  12538. v3 = vertices[ face.c ];
  12539. v4 = vertices[ face.d ];
  12540. vertexArray[ offset ] = v1.x;
  12541. vertexArray[ offset + 1 ] = v1.y;
  12542. vertexArray[ offset + 2 ] = v1.z;
  12543. vertexArray[ offset + 3 ] = v2.x;
  12544. vertexArray[ offset + 4 ] = v2.y;
  12545. vertexArray[ offset + 5 ] = v2.z;
  12546. vertexArray[ offset + 6 ] = v3.x;
  12547. vertexArray[ offset + 7 ] = v3.y;
  12548. vertexArray[ offset + 8 ] = v3.z;
  12549. vertexArray[ offset + 9 ] = v4.x;
  12550. vertexArray[ offset + 10 ] = v4.y;
  12551. vertexArray[ offset + 11 ] = v4.z;
  12552. offset += 12;
  12553. }
  12554. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12555. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12556. }
  12557. if ( dirtyMorphTargets ) {
  12558. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12559. offset_morphTarget = 0;
  12560. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12561. chf = chunk_faces3[ f ];
  12562. face = obj_faces[ chf ];
  12563. // morph positions
  12564. v1 = morphTargets[ vk ].vertices[ face.a ];
  12565. v2 = morphTargets[ vk ].vertices[ face.b ];
  12566. v3 = morphTargets[ vk ].vertices[ face.c ];
  12567. vka = morphTargetsArrays[ vk ];
  12568. vka[ offset_morphTarget ] = v1.x;
  12569. vka[ offset_morphTarget + 1 ] = v1.y;
  12570. vka[ offset_morphTarget + 2 ] = v1.z;
  12571. vka[ offset_morphTarget + 3 ] = v2.x;
  12572. vka[ offset_morphTarget + 4 ] = v2.y;
  12573. vka[ offset_morphTarget + 5 ] = v2.z;
  12574. vka[ offset_morphTarget + 6 ] = v3.x;
  12575. vka[ offset_morphTarget + 7 ] = v3.y;
  12576. vka[ offset_morphTarget + 8 ] = v3.z;
  12577. // morph normals
  12578. if ( material.morphNormals ) {
  12579. if ( needsSmoothNormals ) {
  12580. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12581. n1 = faceVertexNormals.a;
  12582. n2 = faceVertexNormals.b;
  12583. n3 = faceVertexNormals.c;
  12584. } else {
  12585. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12586. n2 = n1;
  12587. n3 = n1;
  12588. }
  12589. nka = morphNormalsArrays[ vk ];
  12590. nka[ offset_morphTarget ] = n1.x;
  12591. nka[ offset_morphTarget + 1 ] = n1.y;
  12592. nka[ offset_morphTarget + 2 ] = n1.z;
  12593. nka[ offset_morphTarget + 3 ] = n2.x;
  12594. nka[ offset_morphTarget + 4 ] = n2.y;
  12595. nka[ offset_morphTarget + 5 ] = n2.z;
  12596. nka[ offset_morphTarget + 6 ] = n3.x;
  12597. nka[ offset_morphTarget + 7 ] = n3.y;
  12598. nka[ offset_morphTarget + 8 ] = n3.z;
  12599. }
  12600. //
  12601. offset_morphTarget += 9;
  12602. }
  12603. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12604. chf = chunk_faces4[ f ];
  12605. face = obj_faces[ chf ];
  12606. // morph positions
  12607. v1 = morphTargets[ vk ].vertices[ face.a ];
  12608. v2 = morphTargets[ vk ].vertices[ face.b ];
  12609. v3 = morphTargets[ vk ].vertices[ face.c ];
  12610. v4 = morphTargets[ vk ].vertices[ face.d ];
  12611. vka = morphTargetsArrays[ vk ];
  12612. vka[ offset_morphTarget ] = v1.x;
  12613. vka[ offset_morphTarget + 1 ] = v1.y;
  12614. vka[ offset_morphTarget + 2 ] = v1.z;
  12615. vka[ offset_morphTarget + 3 ] = v2.x;
  12616. vka[ offset_morphTarget + 4 ] = v2.y;
  12617. vka[ offset_morphTarget + 5 ] = v2.z;
  12618. vka[ offset_morphTarget + 6 ] = v3.x;
  12619. vka[ offset_morphTarget + 7 ] = v3.y;
  12620. vka[ offset_morphTarget + 8 ] = v3.z;
  12621. vka[ offset_morphTarget + 9 ] = v4.x;
  12622. vka[ offset_morphTarget + 10 ] = v4.y;
  12623. vka[ offset_morphTarget + 11 ] = v4.z;
  12624. // morph normals
  12625. if ( material.morphNormals ) {
  12626. if ( needsSmoothNormals ) {
  12627. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12628. n1 = faceVertexNormals.a;
  12629. n2 = faceVertexNormals.b;
  12630. n3 = faceVertexNormals.c;
  12631. n4 = faceVertexNormals.d;
  12632. } else {
  12633. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12634. n2 = n1;
  12635. n3 = n1;
  12636. n4 = n1;
  12637. }
  12638. nka = morphNormalsArrays[ vk ];
  12639. nka[ offset_morphTarget ] = n1.x;
  12640. nka[ offset_morphTarget + 1 ] = n1.y;
  12641. nka[ offset_morphTarget + 2 ] = n1.z;
  12642. nka[ offset_morphTarget + 3 ] = n2.x;
  12643. nka[ offset_morphTarget + 4 ] = n2.y;
  12644. nka[ offset_morphTarget + 5 ] = n2.z;
  12645. nka[ offset_morphTarget + 6 ] = n3.x;
  12646. nka[ offset_morphTarget + 7 ] = n3.y;
  12647. nka[ offset_morphTarget + 8 ] = n3.z;
  12648. nka[ offset_morphTarget + 9 ] = n4.x;
  12649. nka[ offset_morphTarget + 10 ] = n4.y;
  12650. nka[ offset_morphTarget + 11 ] = n4.z;
  12651. }
  12652. //
  12653. offset_morphTarget += 12;
  12654. }
  12655. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12656. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12657. if ( material.morphNormals ) {
  12658. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12659. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12660. }
  12661. }
  12662. }
  12663. if ( obj_skinWeights.length ) {
  12664. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12665. face = obj_faces[ chunk_faces3[ f ] ];
  12666. // weights
  12667. sw1 = obj_skinWeights[ face.a ];
  12668. sw2 = obj_skinWeights[ face.b ];
  12669. sw3 = obj_skinWeights[ face.c ];
  12670. skinWeightArray[ offset_skin ] = sw1.x;
  12671. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12672. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12673. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12674. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12675. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12676. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12677. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12678. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12679. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12680. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12681. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12682. // indices
  12683. si1 = obj_skinIndices[ face.a ];
  12684. si2 = obj_skinIndices[ face.b ];
  12685. si3 = obj_skinIndices[ face.c ];
  12686. skinIndexArray[ offset_skin ] = si1.x;
  12687. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12688. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12689. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12690. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12691. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12692. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12693. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12694. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12695. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12696. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12697. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12698. offset_skin += 12;
  12699. }
  12700. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12701. face = obj_faces[ chunk_faces4[ f ] ];
  12702. // weights
  12703. sw1 = obj_skinWeights[ face.a ];
  12704. sw2 = obj_skinWeights[ face.b ];
  12705. sw3 = obj_skinWeights[ face.c ];
  12706. sw4 = obj_skinWeights[ face.d ];
  12707. skinWeightArray[ offset_skin ] = sw1.x;
  12708. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12709. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12710. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12711. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12712. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12713. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12714. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12715. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12716. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12717. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12718. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12719. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  12720. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  12721. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  12722. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  12723. // indices
  12724. si1 = obj_skinIndices[ face.a ];
  12725. si2 = obj_skinIndices[ face.b ];
  12726. si3 = obj_skinIndices[ face.c ];
  12727. si4 = obj_skinIndices[ face.d ];
  12728. skinIndexArray[ offset_skin ] = si1.x;
  12729. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12730. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12731. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12732. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12733. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12734. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12735. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12736. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12737. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12738. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12739. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12740. skinIndexArray[ offset_skin + 12 ] = si4.x;
  12741. skinIndexArray[ offset_skin + 13 ] = si4.y;
  12742. skinIndexArray[ offset_skin + 14 ] = si4.z;
  12743. skinIndexArray[ offset_skin + 15 ] = si4.w;
  12744. offset_skin += 16;
  12745. }
  12746. if ( offset_skin > 0 ) {
  12747. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12748. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12749. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12750. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12751. }
  12752. }
  12753. if ( dirtyColors && vertexColorType ) {
  12754. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12755. face = obj_faces[ chunk_faces3[ f ] ];
  12756. vertexColors = face.vertexColors;
  12757. faceColor = face.color;
  12758. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12759. c1 = vertexColors[ 0 ];
  12760. c2 = vertexColors[ 1 ];
  12761. c3 = vertexColors[ 2 ];
  12762. } else {
  12763. c1 = faceColor;
  12764. c2 = faceColor;
  12765. c3 = faceColor;
  12766. }
  12767. colorArray[ offset_color ] = c1.r;
  12768. colorArray[ offset_color + 1 ] = c1.g;
  12769. colorArray[ offset_color + 2 ] = c1.b;
  12770. colorArray[ offset_color + 3 ] = c2.r;
  12771. colorArray[ offset_color + 4 ] = c2.g;
  12772. colorArray[ offset_color + 5 ] = c2.b;
  12773. colorArray[ offset_color + 6 ] = c3.r;
  12774. colorArray[ offset_color + 7 ] = c3.g;
  12775. colorArray[ offset_color + 8 ] = c3.b;
  12776. offset_color += 9;
  12777. }
  12778. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12779. face = obj_faces[ chunk_faces4[ f ] ];
  12780. vertexColors = face.vertexColors;
  12781. faceColor = face.color;
  12782. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12783. c1 = vertexColors[ 0 ];
  12784. c2 = vertexColors[ 1 ];
  12785. c3 = vertexColors[ 2 ];
  12786. c4 = vertexColors[ 3 ];
  12787. } else {
  12788. c1 = faceColor;
  12789. c2 = faceColor;
  12790. c3 = faceColor;
  12791. c4 = faceColor;
  12792. }
  12793. colorArray[ offset_color ] = c1.r;
  12794. colorArray[ offset_color + 1 ] = c1.g;
  12795. colorArray[ offset_color + 2 ] = c1.b;
  12796. colorArray[ offset_color + 3 ] = c2.r;
  12797. colorArray[ offset_color + 4 ] = c2.g;
  12798. colorArray[ offset_color + 5 ] = c2.b;
  12799. colorArray[ offset_color + 6 ] = c3.r;
  12800. colorArray[ offset_color + 7 ] = c3.g;
  12801. colorArray[ offset_color + 8 ] = c3.b;
  12802. colorArray[ offset_color + 9 ] = c4.r;
  12803. colorArray[ offset_color + 10 ] = c4.g;
  12804. colorArray[ offset_color + 11 ] = c4.b;
  12805. offset_color += 12;
  12806. }
  12807. if ( offset_color > 0 ) {
  12808. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12809. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12810. }
  12811. }
  12812. if ( dirtyTangents && geometry.hasTangents ) {
  12813. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12814. face = obj_faces[ chunk_faces3[ f ] ];
  12815. vertexTangents = face.vertexTangents;
  12816. t1 = vertexTangents[ 0 ];
  12817. t2 = vertexTangents[ 1 ];
  12818. t3 = vertexTangents[ 2 ];
  12819. tangentArray[ offset_tangent ] = t1.x;
  12820. tangentArray[ offset_tangent + 1 ] = t1.y;
  12821. tangentArray[ offset_tangent + 2 ] = t1.z;
  12822. tangentArray[ offset_tangent + 3 ] = t1.w;
  12823. tangentArray[ offset_tangent + 4 ] = t2.x;
  12824. tangentArray[ offset_tangent + 5 ] = t2.y;
  12825. tangentArray[ offset_tangent + 6 ] = t2.z;
  12826. tangentArray[ offset_tangent + 7 ] = t2.w;
  12827. tangentArray[ offset_tangent + 8 ] = t3.x;
  12828. tangentArray[ offset_tangent + 9 ] = t3.y;
  12829. tangentArray[ offset_tangent + 10 ] = t3.z;
  12830. tangentArray[ offset_tangent + 11 ] = t3.w;
  12831. offset_tangent += 12;
  12832. }
  12833. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12834. face = obj_faces[ chunk_faces4[ f ] ];
  12835. vertexTangents = face.vertexTangents;
  12836. t1 = vertexTangents[ 0 ];
  12837. t2 = vertexTangents[ 1 ];
  12838. t3 = vertexTangents[ 2 ];
  12839. t4 = vertexTangents[ 3 ];
  12840. tangentArray[ offset_tangent ] = t1.x;
  12841. tangentArray[ offset_tangent + 1 ] = t1.y;
  12842. tangentArray[ offset_tangent + 2 ] = t1.z;
  12843. tangentArray[ offset_tangent + 3 ] = t1.w;
  12844. tangentArray[ offset_tangent + 4 ] = t2.x;
  12845. tangentArray[ offset_tangent + 5 ] = t2.y;
  12846. tangentArray[ offset_tangent + 6 ] = t2.z;
  12847. tangentArray[ offset_tangent + 7 ] = t2.w;
  12848. tangentArray[ offset_tangent + 8 ] = t3.x;
  12849. tangentArray[ offset_tangent + 9 ] = t3.y;
  12850. tangentArray[ offset_tangent + 10 ] = t3.z;
  12851. tangentArray[ offset_tangent + 11 ] = t3.w;
  12852. tangentArray[ offset_tangent + 12 ] = t4.x;
  12853. tangentArray[ offset_tangent + 13 ] = t4.y;
  12854. tangentArray[ offset_tangent + 14 ] = t4.z;
  12855. tangentArray[ offset_tangent + 15 ] = t4.w;
  12856. offset_tangent += 16;
  12857. }
  12858. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12859. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12860. }
  12861. if ( dirtyNormals && normalType ) {
  12862. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12863. face = obj_faces[ chunk_faces3[ f ] ];
  12864. vertexNormals = face.vertexNormals;
  12865. faceNormal = face.normal;
  12866. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12867. for ( i = 0; i < 3; i ++ ) {
  12868. vn = vertexNormals[ i ];
  12869. normalArray[ offset_normal ] = vn.x;
  12870. normalArray[ offset_normal + 1 ] = vn.y;
  12871. normalArray[ offset_normal + 2 ] = vn.z;
  12872. offset_normal += 3;
  12873. }
  12874. } else {
  12875. for ( i = 0; i < 3; i ++ ) {
  12876. normalArray[ offset_normal ] = faceNormal.x;
  12877. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12878. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12879. offset_normal += 3;
  12880. }
  12881. }
  12882. }
  12883. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12884. face = obj_faces[ chunk_faces4[ f ] ];
  12885. vertexNormals = face.vertexNormals;
  12886. faceNormal = face.normal;
  12887. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12888. for ( i = 0; i < 4; i ++ ) {
  12889. vn = vertexNormals[ i ];
  12890. normalArray[ offset_normal ] = vn.x;
  12891. normalArray[ offset_normal + 1 ] = vn.y;
  12892. normalArray[ offset_normal + 2 ] = vn.z;
  12893. offset_normal += 3;
  12894. }
  12895. } else {
  12896. for ( i = 0; i < 4; i ++ ) {
  12897. normalArray[ offset_normal ] = faceNormal.x;
  12898. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12899. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12900. offset_normal += 3;
  12901. }
  12902. }
  12903. }
  12904. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12905. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12906. }
  12907. if ( dirtyUvs && obj_uvs && uvType ) {
  12908. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12909. fi = chunk_faces3[ f ];
  12910. uv = obj_uvs[ fi ];
  12911. if ( uv === undefined ) continue;
  12912. for ( i = 0; i < 3; i ++ ) {
  12913. uvi = uv[ i ];
  12914. uvArray[ offset_uv ] = uvi.x;
  12915. uvArray[ offset_uv + 1 ] = uvi.y;
  12916. offset_uv += 2;
  12917. }
  12918. }
  12919. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12920. fi = chunk_faces4[ f ];
  12921. uv = obj_uvs[ fi ];
  12922. if ( uv === undefined ) continue;
  12923. for ( i = 0; i < 4; i ++ ) {
  12924. uvi = uv[ i ];
  12925. uvArray[ offset_uv ] = uvi.x;
  12926. uvArray[ offset_uv + 1 ] = uvi.y;
  12927. offset_uv += 2;
  12928. }
  12929. }
  12930. if ( offset_uv > 0 ) {
  12931. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12932. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12933. }
  12934. }
  12935. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12936. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12937. fi = chunk_faces3[ f ];
  12938. uv2 = obj_uvs2[ fi ];
  12939. if ( uv2 === undefined ) continue;
  12940. for ( i = 0; i < 3; i ++ ) {
  12941. uv2i = uv2[ i ];
  12942. uv2Array[ offset_uv2 ] = uv2i.x;
  12943. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12944. offset_uv2 += 2;
  12945. }
  12946. }
  12947. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12948. fi = chunk_faces4[ f ];
  12949. uv2 = obj_uvs2[ fi ];
  12950. if ( uv2 === undefined ) continue;
  12951. for ( i = 0; i < 4; i ++ ) {
  12952. uv2i = uv2[ i ];
  12953. uv2Array[ offset_uv2 ] = uv2i.x;
  12954. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12955. offset_uv2 += 2;
  12956. }
  12957. }
  12958. if ( offset_uv2 > 0 ) {
  12959. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12960. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12961. }
  12962. }
  12963. if ( dirtyElements ) {
  12964. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12965. faceArray[ offset_face ] = vertexIndex;
  12966. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12967. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12968. offset_face += 3;
  12969. lineArray[ offset_line ] = vertexIndex;
  12970. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12971. lineArray[ offset_line + 2 ] = vertexIndex;
  12972. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12973. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12974. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12975. offset_line += 6;
  12976. vertexIndex += 3;
  12977. }
  12978. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12979. faceArray[ offset_face ] = vertexIndex;
  12980. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12981. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12982. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12983. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12984. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12985. offset_face += 6;
  12986. lineArray[ offset_line ] = vertexIndex;
  12987. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12988. lineArray[ offset_line + 2 ] = vertexIndex;
  12989. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12990. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12991. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12992. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12993. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12994. offset_line += 8;
  12995. vertexIndex += 4;
  12996. }
  12997. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12998. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12999. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13000. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13001. }
  13002. if ( customAttributes ) {
  13003. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13004. customAttribute = customAttributes[ i ];
  13005. if ( ! customAttribute.__original.needsUpdate ) continue;
  13006. offset_custom = 0;
  13007. offset_customSrc = 0;
  13008. if ( customAttribute.size === 1 ) {
  13009. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13010. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13011. face = obj_faces[ chunk_faces3[ f ] ];
  13012. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13013. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13014. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13015. offset_custom += 3;
  13016. }
  13017. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13018. face = obj_faces[ chunk_faces4[ f ] ];
  13019. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13020. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13021. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13022. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  13023. offset_custom += 4;
  13024. }
  13025. } else if ( customAttribute.boundTo === "faces" ) {
  13026. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13027. value = customAttribute.value[ chunk_faces3[ f ] ];
  13028. customAttribute.array[ offset_custom ] = value;
  13029. customAttribute.array[ offset_custom + 1 ] = value;
  13030. customAttribute.array[ offset_custom + 2 ] = value;
  13031. offset_custom += 3;
  13032. }
  13033. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13034. value = customAttribute.value[ chunk_faces4[ f ] ];
  13035. customAttribute.array[ offset_custom ] = value;
  13036. customAttribute.array[ offset_custom + 1 ] = value;
  13037. customAttribute.array[ offset_custom + 2 ] = value;
  13038. customAttribute.array[ offset_custom + 3 ] = value;
  13039. offset_custom += 4;
  13040. }
  13041. }
  13042. } else if ( customAttribute.size === 2 ) {
  13043. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13044. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13045. face = obj_faces[ chunk_faces3[ f ] ];
  13046. v1 = customAttribute.value[ face.a ];
  13047. v2 = customAttribute.value[ face.b ];
  13048. v3 = customAttribute.value[ face.c ];
  13049. customAttribute.array[ offset_custom ] = v1.x;
  13050. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13051. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13052. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13053. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13054. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13055. offset_custom += 6;
  13056. }
  13057. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13058. face = obj_faces[ chunk_faces4[ f ] ];
  13059. v1 = customAttribute.value[ face.a ];
  13060. v2 = customAttribute.value[ face.b ];
  13061. v3 = customAttribute.value[ face.c ];
  13062. v4 = customAttribute.value[ face.d ];
  13063. customAttribute.array[ offset_custom ] = v1.x;
  13064. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13065. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13066. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13067. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13068. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13069. customAttribute.array[ offset_custom + 6 ] = v4.x;
  13070. customAttribute.array[ offset_custom + 7 ] = v4.y;
  13071. offset_custom += 8;
  13072. }
  13073. } else if ( customAttribute.boundTo === "faces" ) {
  13074. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13075. value = customAttribute.value[ chunk_faces3[ f ] ];
  13076. v1 = value;
  13077. v2 = value;
  13078. v3 = value;
  13079. customAttribute.array[ offset_custom ] = v1.x;
  13080. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13081. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13082. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13083. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13084. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13085. offset_custom += 6;
  13086. }
  13087. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13088. value = customAttribute.value[ chunk_faces4[ f ] ];
  13089. v1 = value;
  13090. v2 = value;
  13091. v3 = value;
  13092. v4 = value;
  13093. customAttribute.array[ offset_custom ] = v1.x;
  13094. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13095. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13096. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13097. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13098. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13099. customAttribute.array[ offset_custom + 6 ] = v4.x;
  13100. customAttribute.array[ offset_custom + 7 ] = v4.y;
  13101. offset_custom += 8;
  13102. }
  13103. }
  13104. } else if ( customAttribute.size === 3 ) {
  13105. var pp;
  13106. if ( customAttribute.type === "c" ) {
  13107. pp = [ "r", "g", "b" ];
  13108. } else {
  13109. pp = [ "x", "y", "z" ];
  13110. }
  13111. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13112. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13113. face = obj_faces[ chunk_faces3[ f ] ];
  13114. v1 = customAttribute.value[ face.a ];
  13115. v2 = customAttribute.value[ face.b ];
  13116. v3 = customAttribute.value[ face.c ];
  13117. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13118. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13119. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13120. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13121. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13122. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13123. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13124. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13125. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13126. offset_custom += 9;
  13127. }
  13128. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13129. face = obj_faces[ chunk_faces4[ f ] ];
  13130. v1 = customAttribute.value[ face.a ];
  13131. v2 = customAttribute.value[ face.b ];
  13132. v3 = customAttribute.value[ face.c ];
  13133. v4 = customAttribute.value[ face.d ];
  13134. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13135. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13136. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13137. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13138. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13139. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13140. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13141. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13142. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13143. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13144. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13145. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13146. offset_custom += 12;
  13147. }
  13148. } else if ( customAttribute.boundTo === "faces" ) {
  13149. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13150. value = customAttribute.value[ chunk_faces3[ f ] ];
  13151. v1 = value;
  13152. v2 = value;
  13153. v3 = value;
  13154. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13155. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13156. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13157. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13158. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13159. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13160. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13161. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13162. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13163. offset_custom += 9;
  13164. }
  13165. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13166. value = customAttribute.value[ chunk_faces4[ f ] ];
  13167. v1 = value;
  13168. v2 = value;
  13169. v3 = value;
  13170. v4 = value;
  13171. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13172. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13173. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13174. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13175. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13176. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13177. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13178. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13179. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13180. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13181. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13182. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13183. offset_custom += 12;
  13184. }
  13185. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13186. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13187. value = customAttribute.value[ chunk_faces3[ f ] ];
  13188. v1 = value[ 0 ];
  13189. v2 = value[ 1 ];
  13190. v3 = value[ 2 ];
  13191. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13192. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13193. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13194. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13195. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13196. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13197. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13198. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13199. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13200. offset_custom += 9;
  13201. }
  13202. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13203. value = customAttribute.value[ chunk_faces4[ f ] ];
  13204. v1 = value[ 0 ];
  13205. v2 = value[ 1 ];
  13206. v3 = value[ 2 ];
  13207. v4 = value[ 3 ];
  13208. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13209. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13210. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13211. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13212. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13213. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13214. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13215. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13216. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13217. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13218. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13219. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13220. offset_custom += 12;
  13221. }
  13222. }
  13223. } else if ( customAttribute.size === 4 ) {
  13224. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13225. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13226. face = obj_faces[ chunk_faces3[ f ] ];
  13227. v1 = customAttribute.value[ face.a ];
  13228. v2 = customAttribute.value[ face.b ];
  13229. v3 = customAttribute.value[ face.c ];
  13230. customAttribute.array[ offset_custom ] = v1.x;
  13231. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13232. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13233. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13234. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13235. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13236. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13237. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13238. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13239. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13240. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13241. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13242. offset_custom += 12;
  13243. }
  13244. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13245. face = obj_faces[ chunk_faces4[ f ] ];
  13246. v1 = customAttribute.value[ face.a ];
  13247. v2 = customAttribute.value[ face.b ];
  13248. v3 = customAttribute.value[ face.c ];
  13249. v4 = customAttribute.value[ face.d ];
  13250. customAttribute.array[ offset_custom ] = v1.x;
  13251. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13252. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13253. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13254. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13255. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13256. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13257. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13258. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13259. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13260. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13261. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13262. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13263. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13264. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13265. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13266. offset_custom += 16;
  13267. }
  13268. } else if ( customAttribute.boundTo === "faces" ) {
  13269. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13270. value = customAttribute.value[ chunk_faces3[ f ] ];
  13271. v1 = value;
  13272. v2 = value;
  13273. v3 = value;
  13274. customAttribute.array[ offset_custom ] = v1.x;
  13275. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13276. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13277. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13278. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13279. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13280. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13281. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13282. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13283. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13284. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13285. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13286. offset_custom += 12;
  13287. }
  13288. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13289. value = customAttribute.value[ chunk_faces4[ f ] ];
  13290. v1 = value;
  13291. v2 = value;
  13292. v3 = value;
  13293. v4 = value;
  13294. customAttribute.array[ offset_custom ] = v1.x;
  13295. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13296. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13297. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13298. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13299. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13300. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13301. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13302. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13303. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13304. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13305. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13306. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13307. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13308. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13309. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13310. offset_custom += 16;
  13311. }
  13312. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13313. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13314. value = customAttribute.value[ chunk_faces3[ f ] ];
  13315. v1 = value[ 0 ];
  13316. v2 = value[ 1 ];
  13317. v3 = value[ 2 ];
  13318. customAttribute.array[ offset_custom ] = v1.x;
  13319. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13320. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13321. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13322. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13323. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13324. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13325. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13326. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13327. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13328. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13329. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13330. offset_custom += 12;
  13331. }
  13332. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13333. value = customAttribute.value[ chunk_faces4[ f ] ];
  13334. v1 = value[ 0 ];
  13335. v2 = value[ 1 ];
  13336. v3 = value[ 2 ];
  13337. v4 = value[ 3 ];
  13338. customAttribute.array[ offset_custom ] = v1.x;
  13339. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13340. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13341. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13342. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13343. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13344. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13345. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13346. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13347. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13348. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13349. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13350. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13351. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13352. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13353. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13354. offset_custom += 16;
  13355. }
  13356. }
  13357. }
  13358. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13359. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13360. }
  13361. }
  13362. if ( dispose ) {
  13363. delete geometryGroup.__inittedArrays;
  13364. delete geometryGroup.__colorArray;
  13365. delete geometryGroup.__normalArray;
  13366. delete geometryGroup.__tangentArray;
  13367. delete geometryGroup.__uvArray;
  13368. delete geometryGroup.__uv2Array;
  13369. delete geometryGroup.__faceArray;
  13370. delete geometryGroup.__vertexArray;
  13371. delete geometryGroup.__lineArray;
  13372. delete geometryGroup.__skinIndexArray;
  13373. delete geometryGroup.__skinWeightArray;
  13374. }
  13375. };
  13376. function setDirectBuffers ( geometry, hint, dispose ) {
  13377. var attributes = geometry.attributes;
  13378. var attributeName, attributeItem;
  13379. for ( attributeName in attributes ) {
  13380. attributeItem = attributes[ attributeName ];
  13381. if ( attributeItem.needsUpdate ) {
  13382. if ( attributeName === 'index' ) {
  13383. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13384. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13385. } else {
  13386. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13387. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13388. }
  13389. attributeItem.needsUpdate = false;
  13390. }
  13391. if ( dispose && ! attributeItem.dynamic ) {
  13392. attributeItem.array = null;
  13393. }
  13394. }
  13395. };
  13396. // Buffer rendering
  13397. this.renderBufferImmediate = function ( object, program, material ) {
  13398. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13399. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13400. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13401. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13402. if ( object.hasPositions ) {
  13403. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13404. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13405. _gl.enableVertexAttribArray( program.attributes.position );
  13406. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13407. }
  13408. if ( object.hasNormals ) {
  13409. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13410. if ( material.shading === THREE.FlatShading ) {
  13411. var nx, ny, nz,
  13412. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13413. normalArray,
  13414. i, il = object.count * 3;
  13415. for( i = 0; i < il; i += 9 ) {
  13416. normalArray = object.normalArray;
  13417. nax = normalArray[ i ];
  13418. nay = normalArray[ i + 1 ];
  13419. naz = normalArray[ i + 2 ];
  13420. nbx = normalArray[ i + 3 ];
  13421. nby = normalArray[ i + 4 ];
  13422. nbz = normalArray[ i + 5 ];
  13423. ncx = normalArray[ i + 6 ];
  13424. ncy = normalArray[ i + 7 ];
  13425. ncz = normalArray[ i + 8 ];
  13426. nx = ( nax + nbx + ncx ) / 3;
  13427. ny = ( nay + nby + ncy ) / 3;
  13428. nz = ( naz + nbz + ncz ) / 3;
  13429. normalArray[ i ] = nx;
  13430. normalArray[ i + 1 ] = ny;
  13431. normalArray[ i + 2 ] = nz;
  13432. normalArray[ i + 3 ] = nx;
  13433. normalArray[ i + 4 ] = ny;
  13434. normalArray[ i + 5 ] = nz;
  13435. normalArray[ i + 6 ] = nx;
  13436. normalArray[ i + 7 ] = ny;
  13437. normalArray[ i + 8 ] = nz;
  13438. }
  13439. }
  13440. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13441. _gl.enableVertexAttribArray( program.attributes.normal );
  13442. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13443. }
  13444. if ( object.hasUvs && material.map ) {
  13445. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13446. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13447. _gl.enableVertexAttribArray( program.attributes.uv );
  13448. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13449. }
  13450. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13451. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13452. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13453. _gl.enableVertexAttribArray( program.attributes.color );
  13454. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13455. }
  13456. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13457. object.count = 0;
  13458. };
  13459. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13460. if ( material.visible === false ) return;
  13461. var linewidth, a, attribute;
  13462. var attributeItem, attributeName, attributePointer, attributeSize;
  13463. var program = setProgram( camera, lights, fog, material, object );
  13464. var programAttributes = program.attributes;
  13465. var geometryAttributes = geometry.attributes;
  13466. var updateBuffers = false,
  13467. wireframeBit = material.wireframe ? 1 : 0,
  13468. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13469. if ( geometryHash !== _currentGeometryGroupHash ) {
  13470. _currentGeometryGroupHash = geometryHash;
  13471. updateBuffers = true;
  13472. }
  13473. if ( updateBuffers ) {
  13474. disableAttributes();
  13475. }
  13476. // render mesh
  13477. if ( object instanceof THREE.Mesh ) {
  13478. var index = geometryAttributes[ "index" ];
  13479. // indexed triangles
  13480. if ( index ) {
  13481. var offsets = geometry.offsets;
  13482. // if there is more than 1 chunk
  13483. // must set attribute pointers to use new offsets for each chunk
  13484. // even if geometry and materials didn't change
  13485. if ( offsets.length > 1 ) updateBuffers = true;
  13486. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13487. var startIndex = offsets[ i ].index;
  13488. if ( updateBuffers ) {
  13489. for ( attributeName in geometryAttributes ) {
  13490. if ( attributeName === 'index' ) continue;
  13491. attributePointer = programAttributes[ attributeName ];
  13492. attributeItem = geometryAttributes[ attributeName ];
  13493. attributeSize = attributeItem.itemSize;
  13494. if ( attributePointer >= 0 ) {
  13495. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13496. enableAttribute( attributePointer );
  13497. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13498. }
  13499. }
  13500. // indices
  13501. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13502. }
  13503. // render indexed triangles
  13504. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13505. _this.info.render.calls ++;
  13506. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13507. _this.info.render.faces += offsets[ i ].count / 3;
  13508. }
  13509. // non-indexed triangles
  13510. } else {
  13511. if ( updateBuffers ) {
  13512. for ( attributeName in geometryAttributes ) {
  13513. if ( attributeName === 'index') continue;
  13514. attributePointer = programAttributes[ attributeName ];
  13515. attributeItem = geometryAttributes[ attributeName ];
  13516. attributeSize = attributeItem.itemSize;
  13517. if ( attributePointer >= 0 ) {
  13518. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13519. enableAttribute( attributePointer );
  13520. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13521. }
  13522. }
  13523. }
  13524. var position = geometry.attributes[ "position" ];
  13525. // render non-indexed triangles
  13526. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13527. _this.info.render.calls ++;
  13528. _this.info.render.vertices += position.numItems / 3;
  13529. _this.info.render.faces += position.numItems / 3 / 3;
  13530. }
  13531. // render particles
  13532. } else if ( object instanceof THREE.ParticleSystem ) {
  13533. if ( updateBuffers ) {
  13534. for ( attributeName in geometryAttributes ) {
  13535. attributePointer = programAttributes[ attributeName ];
  13536. attributeItem = geometryAttributes[ attributeName ];
  13537. attributeSize = attributeItem.itemSize;
  13538. if ( attributePointer >= 0 ) {
  13539. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13540. enableAttribute( attributePointer );
  13541. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13542. }
  13543. }
  13544. var position = geometryAttributes[ "position" ];
  13545. // render particles
  13546. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13547. _this.info.render.calls ++;
  13548. _this.info.render.points += position.numItems / 3;
  13549. }
  13550. } else if ( object instanceof THREE.Line ) {
  13551. if ( updateBuffers ) {
  13552. for ( attributeName in geometryAttributes ) {
  13553. attributePointer = programAttributes[ attributeName ];
  13554. attributeItem = geometryAttributes[ attributeName ];
  13555. attributeSize = attributeItem.itemSize;
  13556. if ( attributePointer >= 0 ) {
  13557. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13558. enableAttribute( attributePointer );
  13559. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13560. }
  13561. }
  13562. // render lines
  13563. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13564. setLineWidth( material.linewidth );
  13565. var position = geometryAttributes[ "position" ];
  13566. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13567. _this.info.render.calls ++;
  13568. _this.info.render.points += position.numItems;
  13569. }
  13570. }
  13571. };
  13572. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13573. if ( material.visible === false ) return;
  13574. var linewidth, a, attribute, i, il;
  13575. var program = setProgram( camera, lights, fog, material, object );
  13576. var attributes = program.attributes;
  13577. var updateBuffers = false,
  13578. wireframeBit = material.wireframe ? 1 : 0,
  13579. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13580. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13581. _currentGeometryGroupHash = geometryGroupHash;
  13582. updateBuffers = true;
  13583. }
  13584. if ( updateBuffers ) {
  13585. disableAttributes();
  13586. }
  13587. // vertices
  13588. if ( !material.morphTargets && attributes.position >= 0 ) {
  13589. if ( updateBuffers ) {
  13590. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13591. enableAttribute( attributes.position );
  13592. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13593. }
  13594. } else {
  13595. if ( object.morphTargetBase ) {
  13596. setupMorphTargets( material, geometryGroup, object );
  13597. }
  13598. }
  13599. if ( updateBuffers ) {
  13600. // custom attributes
  13601. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13602. if ( geometryGroup.__webglCustomAttributesList ) {
  13603. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13604. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13605. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13606. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13607. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13608. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13609. }
  13610. }
  13611. }
  13612. // colors
  13613. if ( attributes.color >= 0 ) {
  13614. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13615. enableAttribute( attributes.color );
  13616. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13617. }
  13618. // normals
  13619. if ( attributes.normal >= 0 ) {
  13620. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13621. enableAttribute( attributes.normal );
  13622. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13623. }
  13624. // tangents
  13625. if ( attributes.tangent >= 0 ) {
  13626. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13627. enableAttribute( attributes.tangent );
  13628. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13629. }
  13630. // uvs
  13631. if ( attributes.uv >= 0 ) {
  13632. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13633. enableAttribute( attributes.uv );
  13634. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13635. }
  13636. if ( attributes.uv2 >= 0 ) {
  13637. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13638. enableAttribute( attributes.uv2 );
  13639. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13640. }
  13641. if ( material.skinning &&
  13642. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13643. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13644. enableAttribute( attributes.skinIndex );
  13645. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13646. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13647. enableAttribute( attributes.skinWeight );
  13648. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13649. }
  13650. // line distances
  13651. if ( attributes.lineDistance >= 0 ) {
  13652. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13653. enableAttribute( attributes.lineDistance );
  13654. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13655. }
  13656. }
  13657. // render mesh
  13658. if ( object instanceof THREE.Mesh ) {
  13659. // wireframe
  13660. if ( material.wireframe ) {
  13661. setLineWidth( material.wireframeLinewidth );
  13662. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13663. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13664. // triangles
  13665. } else {
  13666. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13667. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13668. }
  13669. _this.info.render.calls ++;
  13670. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13671. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13672. // render lines
  13673. } else if ( object instanceof THREE.Line ) {
  13674. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13675. setLineWidth( material.linewidth );
  13676. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13677. _this.info.render.calls ++;
  13678. // render particles
  13679. } else if ( object instanceof THREE.ParticleSystem ) {
  13680. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13681. _this.info.render.calls ++;
  13682. _this.info.render.points += geometryGroup.__webglParticleCount;
  13683. // render ribbon
  13684. } else if ( object instanceof THREE.Ribbon ) {
  13685. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13686. _this.info.render.calls ++;
  13687. }
  13688. };
  13689. function enableAttribute( attribute ) {
  13690. if ( ! _enabledAttributes[ attribute ] ) {
  13691. _gl.enableVertexAttribArray( attribute );
  13692. _enabledAttributes[ attribute ] = true;
  13693. }
  13694. };
  13695. function disableAttributes() {
  13696. for ( var attribute in _enabledAttributes ) {
  13697. if ( _enabledAttributes[ attribute ] ) {
  13698. _gl.disableVertexAttribArray( attribute );
  13699. _enabledAttributes[ attribute ] = false;
  13700. }
  13701. }
  13702. };
  13703. function setupMorphTargets ( material, geometryGroup, object ) {
  13704. // set base
  13705. var attributes = material.program.attributes;
  13706. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13707. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13708. enableAttribute( attributes.position );
  13709. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13710. } else if ( attributes.position >= 0 ) {
  13711. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13712. enableAttribute( attributes.position );
  13713. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13714. }
  13715. if ( object.morphTargetForcedOrder.length ) {
  13716. // set forced order
  13717. var m = 0;
  13718. var order = object.morphTargetForcedOrder;
  13719. var influences = object.morphTargetInfluences;
  13720. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13721. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13722. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13723. enableAttribute( attributes[ "morphTarget" + m ] );
  13724. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13725. }
  13726. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13727. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13728. enableAttribute( attributes[ "morphNormal" + m ] );
  13729. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13730. }
  13731. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13732. m ++;
  13733. }
  13734. } else {
  13735. // find the most influencing
  13736. var influence, activeInfluenceIndices = [];
  13737. var influences = object.morphTargetInfluences;
  13738. var i, il = influences.length;
  13739. for ( i = 0; i < il; i ++ ) {
  13740. influence = influences[ i ];
  13741. if ( influence > 0 ) {
  13742. activeInfluenceIndices.push( [ influence, i ] );
  13743. }
  13744. }
  13745. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13746. activeInfluenceIndices.sort( numericalSort );
  13747. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13748. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13749. activeInfluenceIndices.sort( numericalSort );
  13750. } else if ( activeInfluenceIndices.length === 0 ) {
  13751. activeInfluenceIndices.push( [ 0, 0 ] );
  13752. };
  13753. var influenceIndex, m = 0;
  13754. while ( m < material.numSupportedMorphTargets ) {
  13755. if ( activeInfluenceIndices[ m ] ) {
  13756. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13757. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13758. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13759. enableAttribute( attributes[ "morphTarget" + m ] );
  13760. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13761. }
  13762. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13763. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13764. enableAttribute( attributes[ "morphNormal" + m ] );
  13765. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13766. }
  13767. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13768. } else {
  13769. /*
  13770. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13771. if ( material.morphNormals ) {
  13772. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13773. }
  13774. */
  13775. object.__webglMorphTargetInfluences[ m ] = 0;
  13776. }
  13777. m ++;
  13778. }
  13779. }
  13780. // load updated influences uniform
  13781. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13782. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13783. }
  13784. };
  13785. // Sorting
  13786. function painterSortStable ( a, b ) {
  13787. if ( a.z !== b.z ) {
  13788. return b.z - a.z;
  13789. } else {
  13790. return a.id - b.id;
  13791. }
  13792. };
  13793. function numericalSort ( a, b ) {
  13794. return b[ 0 ] - a[ 0 ];
  13795. };
  13796. // Rendering
  13797. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13798. if ( camera instanceof THREE.Camera === false ) {
  13799. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13800. return;
  13801. }
  13802. var i, il,
  13803. webglObject, object,
  13804. renderList,
  13805. lights = scene.__lights,
  13806. fog = scene.fog;
  13807. // reset caching for this frame
  13808. _currentMaterialId = -1;
  13809. _lightsNeedUpdate = true;
  13810. // update scene graph
  13811. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13812. // update camera matrices and frustum
  13813. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13814. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13815. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13816. _frustum.setFromMatrix( _projScreenMatrix );
  13817. // update WebGL objects
  13818. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13819. // custom render plugins (pre pass)
  13820. renderPlugins( this.renderPluginsPre, scene, camera );
  13821. //
  13822. _this.info.render.calls = 0;
  13823. _this.info.render.vertices = 0;
  13824. _this.info.render.faces = 0;
  13825. _this.info.render.points = 0;
  13826. this.setRenderTarget( renderTarget );
  13827. if ( this.autoClear || forceClear ) {
  13828. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13829. }
  13830. // set matrices for regular objects (frustum culled)
  13831. renderList = scene.__webglObjects;
  13832. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13833. webglObject = renderList[ i ];
  13834. object = webglObject.object;
  13835. webglObject.id = i;
  13836. webglObject.render = false;
  13837. if ( object.visible ) {
  13838. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13839. setupMatrices( object, camera );
  13840. unrollBufferMaterial( webglObject );
  13841. webglObject.render = true;
  13842. if ( this.sortObjects === true ) {
  13843. if ( object.renderDepth !== null ) {
  13844. webglObject.z = object.renderDepth;
  13845. } else {
  13846. _vector3.getPositionFromMatrix( object.matrixWorld );
  13847. _vector3.applyProjection( _projScreenMatrix );
  13848. webglObject.z = _vector3.z;
  13849. }
  13850. }
  13851. }
  13852. }
  13853. }
  13854. if ( this.sortObjects ) {
  13855. renderList.sort( painterSortStable );
  13856. }
  13857. // set matrices for immediate objects
  13858. renderList = scene.__webglObjectsImmediate;
  13859. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13860. webglObject = renderList[ i ];
  13861. object = webglObject.object;
  13862. if ( object.visible ) {
  13863. setupMatrices( object, camera );
  13864. unrollImmediateBufferMaterial( webglObject );
  13865. }
  13866. }
  13867. if ( scene.overrideMaterial ) {
  13868. var material = scene.overrideMaterial;
  13869. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13870. this.setDepthTest( material.depthTest );
  13871. this.setDepthWrite( material.depthWrite );
  13872. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13873. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13874. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13875. } else {
  13876. var material = null;
  13877. // opaque pass (front-to-back order)
  13878. this.setBlending( THREE.NoBlending );
  13879. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13880. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13881. // transparent pass (back-to-front order)
  13882. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13883. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13884. }
  13885. // custom render plugins (post pass)
  13886. renderPlugins( this.renderPluginsPost, scene, camera );
  13887. // Generate mipmap if we're using any kind of mipmap filtering
  13888. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13889. updateRenderTargetMipmap( renderTarget );
  13890. }
  13891. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13892. this.setDepthTest( true );
  13893. this.setDepthWrite( true );
  13894. // _gl.finish();
  13895. };
  13896. function renderPlugins( plugins, scene, camera ) {
  13897. if ( ! plugins.length ) return;
  13898. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13899. // reset state for plugin (to start from clean slate)
  13900. _currentProgram = null;
  13901. _currentCamera = null;
  13902. _oldBlending = -1;
  13903. _oldDepthTest = -1;
  13904. _oldDepthWrite = -1;
  13905. _oldDoubleSided = -1;
  13906. _oldFlipSided = -1;
  13907. _currentGeometryGroupHash = -1;
  13908. _currentMaterialId = -1;
  13909. _lightsNeedUpdate = true;
  13910. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13911. // reset state after plugin (anything could have changed)
  13912. _currentProgram = null;
  13913. _currentCamera = null;
  13914. _oldBlending = -1;
  13915. _oldDepthTest = -1;
  13916. _oldDepthWrite = -1;
  13917. _oldDoubleSided = -1;
  13918. _oldFlipSided = -1;
  13919. _currentGeometryGroupHash = -1;
  13920. _currentMaterialId = -1;
  13921. _lightsNeedUpdate = true;
  13922. }
  13923. };
  13924. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13925. var webglObject, object, buffer, material, start, end, delta;
  13926. if ( reverse ) {
  13927. start = renderList.length - 1;
  13928. end = -1;
  13929. delta = -1;
  13930. } else {
  13931. start = 0;
  13932. end = renderList.length;
  13933. delta = 1;
  13934. }
  13935. for ( var i = start; i !== end; i += delta ) {
  13936. webglObject = renderList[ i ];
  13937. if ( webglObject.render ) {
  13938. object = webglObject.object;
  13939. buffer = webglObject.buffer;
  13940. if ( overrideMaterial ) {
  13941. material = overrideMaterial;
  13942. } else {
  13943. material = webglObject[ materialType ];
  13944. if ( ! material ) continue;
  13945. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13946. _this.setDepthTest( material.depthTest );
  13947. _this.setDepthWrite( material.depthWrite );
  13948. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13949. }
  13950. _this.setMaterialFaces( material );
  13951. if ( buffer instanceof THREE.BufferGeometry ) {
  13952. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13953. } else {
  13954. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13955. }
  13956. }
  13957. }
  13958. };
  13959. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13960. var webglObject, object, material, program;
  13961. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13962. webglObject = renderList[ i ];
  13963. object = webglObject.object;
  13964. if ( object.visible ) {
  13965. if ( overrideMaterial ) {
  13966. material = overrideMaterial;
  13967. } else {
  13968. material = webglObject[ materialType ];
  13969. if ( ! material ) continue;
  13970. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13971. _this.setDepthTest( material.depthTest );
  13972. _this.setDepthWrite( material.depthWrite );
  13973. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13974. }
  13975. _this.renderImmediateObject( camera, lights, fog, material, object );
  13976. }
  13977. }
  13978. };
  13979. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13980. var program = setProgram( camera, lights, fog, material, object );
  13981. _currentGeometryGroupHash = -1;
  13982. _this.setMaterialFaces( material );
  13983. if ( object.immediateRenderCallback ) {
  13984. object.immediateRenderCallback( program, _gl, _frustum );
  13985. } else {
  13986. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13987. }
  13988. };
  13989. function unrollImmediateBufferMaterial ( globject ) {
  13990. var object = globject.object,
  13991. material = object.material;
  13992. if ( material.transparent ) {
  13993. globject.transparent = material;
  13994. globject.opaque = null;
  13995. } else {
  13996. globject.opaque = material;
  13997. globject.transparent = null;
  13998. }
  13999. };
  14000. function unrollBufferMaterial ( globject ) {
  14001. var object = globject.object,
  14002. buffer = globject.buffer,
  14003. material, materialIndex, meshMaterial;
  14004. meshMaterial = object.material;
  14005. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  14006. materialIndex = buffer.materialIndex;
  14007. material = meshMaterial.materials[ materialIndex ];
  14008. if ( material.transparent ) {
  14009. globject.transparent = material;
  14010. globject.opaque = null;
  14011. } else {
  14012. globject.opaque = material;
  14013. globject.transparent = null;
  14014. }
  14015. } else {
  14016. material = meshMaterial;
  14017. if ( material ) {
  14018. if ( material.transparent ) {
  14019. globject.transparent = material;
  14020. globject.opaque = null;
  14021. } else {
  14022. globject.opaque = material;
  14023. globject.transparent = null;
  14024. }
  14025. }
  14026. }
  14027. };
  14028. // Geometry splitting
  14029. function sortFacesByMaterial ( geometry, material ) {
  14030. var f, fl, face, materialIndex, vertices,
  14031. groupHash, hash_map = {};
  14032. var numMorphTargets = geometry.morphTargets.length;
  14033. var numMorphNormals = geometry.morphNormals.length;
  14034. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  14035. geometry.geometryGroups = {};
  14036. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  14037. face = geometry.faces[ f ];
  14038. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  14039. if ( hash_map[ materialIndex ] === undefined ) {
  14040. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  14041. }
  14042. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14043. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14044. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14045. }
  14046. vertices = face instanceof THREE.Face3 ? 3 : 4;
  14047. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  14048. hash_map[ materialIndex ].counter += 1;
  14049. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14050. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14051. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14052. }
  14053. }
  14054. if ( face instanceof THREE.Face3 ) {
  14055. geometry.geometryGroups[ groupHash ].faces3.push( f );
  14056. } else {
  14057. geometry.geometryGroups[ groupHash ].faces4.push( f );
  14058. }
  14059. geometry.geometryGroups[ groupHash ].vertices += vertices;
  14060. }
  14061. geometry.geometryGroupsList = [];
  14062. for ( var g in geometry.geometryGroups ) {
  14063. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  14064. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  14065. }
  14066. };
  14067. // Objects refresh
  14068. this.initWebGLObjects = function ( scene ) {
  14069. if ( !scene.__webglObjects ) {
  14070. scene.__webglObjects = [];
  14071. scene.__webglObjectsImmediate = [];
  14072. scene.__webglSprites = [];
  14073. scene.__webglFlares = [];
  14074. }
  14075. while ( scene.__objectsAdded.length ) {
  14076. addObject( scene.__objectsAdded[ 0 ], scene );
  14077. scene.__objectsAdded.splice( 0, 1 );
  14078. }
  14079. while ( scene.__objectsRemoved.length ) {
  14080. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14081. scene.__objectsRemoved.splice( 0, 1 );
  14082. }
  14083. // update must be called after objects adding / removal
  14084. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14085. var object = scene.__webglObjects[ o ].object;
  14086. // TODO: Remove this hack (WebGLRenderer refactoring)
  14087. if ( object.__webglInit === undefined ) {
  14088. if ( object.__webglActive !== undefined ) {
  14089. removeObject( object, scene );
  14090. }
  14091. addObject( object, scene );
  14092. }
  14093. updateObject( object );
  14094. }
  14095. };
  14096. // Objects adding
  14097. function addObject( object, scene ) {
  14098. var g, geometry, material, geometryGroup;
  14099. if ( object.__webglInit === undefined ) {
  14100. object.__webglInit = true;
  14101. object._modelViewMatrix = new THREE.Matrix4();
  14102. object._normalMatrix = new THREE.Matrix3();
  14103. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  14104. object.geometry.__webglInit = true;
  14105. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  14106. }
  14107. geometry = object.geometry;
  14108. if ( geometry === undefined ) {
  14109. // fail silently for now
  14110. } else if ( geometry instanceof THREE.BufferGeometry ) {
  14111. initDirectBuffers( geometry );
  14112. } else if ( object instanceof THREE.Mesh ) {
  14113. material = object.material;
  14114. if ( geometry.geometryGroups === undefined ) {
  14115. sortFacesByMaterial( geometry, material );
  14116. }
  14117. // create separate VBOs per geometry chunk
  14118. for ( g in geometry.geometryGroups ) {
  14119. geometryGroup = geometry.geometryGroups[ g ];
  14120. // initialise VBO on the first access
  14121. if ( ! geometryGroup.__webglVertexBuffer ) {
  14122. createMeshBuffers( geometryGroup );
  14123. initMeshBuffers( geometryGroup, object );
  14124. geometry.verticesNeedUpdate = true;
  14125. geometry.morphTargetsNeedUpdate = true;
  14126. geometry.elementsNeedUpdate = true;
  14127. geometry.uvsNeedUpdate = true;
  14128. geometry.normalsNeedUpdate = true;
  14129. geometry.tangentsNeedUpdate = true;
  14130. geometry.colorsNeedUpdate = true;
  14131. }
  14132. }
  14133. } else if ( object instanceof THREE.Ribbon ) {
  14134. if ( ! geometry.__webglVertexBuffer ) {
  14135. createRibbonBuffers( geometry );
  14136. initRibbonBuffers( geometry, object );
  14137. geometry.verticesNeedUpdate = true;
  14138. geometry.colorsNeedUpdate = true;
  14139. geometry.normalsNeedUpdate = true;
  14140. }
  14141. } else if ( object instanceof THREE.Line ) {
  14142. if ( ! geometry.__webglVertexBuffer ) {
  14143. createLineBuffers( geometry );
  14144. initLineBuffers( geometry, object );
  14145. geometry.verticesNeedUpdate = true;
  14146. geometry.colorsNeedUpdate = true;
  14147. geometry.lineDistancesNeedUpdate = true;
  14148. }
  14149. } else if ( object instanceof THREE.ParticleSystem ) {
  14150. if ( ! geometry.__webglVertexBuffer ) {
  14151. createParticleBuffers( geometry );
  14152. initParticleBuffers( geometry, object );
  14153. geometry.verticesNeedUpdate = true;
  14154. geometry.colorsNeedUpdate = true;
  14155. }
  14156. }
  14157. }
  14158. if ( object.__webglActive === undefined ) {
  14159. if ( object instanceof THREE.Mesh ) {
  14160. geometry = object.geometry;
  14161. if ( geometry instanceof THREE.BufferGeometry ) {
  14162. addBuffer( scene.__webglObjects, geometry, object );
  14163. } else if ( geometry instanceof THREE.Geometry ) {
  14164. for ( g in geometry.geometryGroups ) {
  14165. geometryGroup = geometry.geometryGroups[ g ];
  14166. addBuffer( scene.__webglObjects, geometryGroup, object );
  14167. }
  14168. }
  14169. } else if ( object instanceof THREE.Ribbon ||
  14170. object instanceof THREE.Line ||
  14171. object instanceof THREE.ParticleSystem ) {
  14172. geometry = object.geometry;
  14173. addBuffer( scene.__webglObjects, geometry, object );
  14174. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14175. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14176. } else if ( object instanceof THREE.Sprite ) {
  14177. scene.__webglSprites.push( object );
  14178. } else if ( object instanceof THREE.LensFlare ) {
  14179. scene.__webglFlares.push( object );
  14180. }
  14181. object.__webglActive = true;
  14182. }
  14183. };
  14184. function addBuffer( objlist, buffer, object ) {
  14185. objlist.push(
  14186. {
  14187. id: null,
  14188. buffer: buffer,
  14189. object: object,
  14190. opaque: null,
  14191. transparent: null,
  14192. z: 0
  14193. }
  14194. );
  14195. };
  14196. function addBufferImmediate( objlist, object ) {
  14197. objlist.push(
  14198. {
  14199. id: null,
  14200. object: object,
  14201. opaque: null,
  14202. transparent: null,
  14203. z: 0
  14204. }
  14205. );
  14206. };
  14207. // Objects updates
  14208. function updateObject( object ) {
  14209. var geometry = object.geometry,
  14210. geometryGroup, customAttributesDirty, material;
  14211. if ( geometry instanceof THREE.BufferGeometry ) {
  14212. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  14213. } else if ( object instanceof THREE.Mesh ) {
  14214. // check all geometry groups
  14215. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14216. geometryGroup = geometry.geometryGroupsList[ i ];
  14217. material = getBufferMaterial( object, geometryGroup );
  14218. if ( geometry.buffersNeedUpdate ) {
  14219. initMeshBuffers( geometryGroup, object );
  14220. }
  14221. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14222. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14223. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14224. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14225. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14226. }
  14227. }
  14228. geometry.verticesNeedUpdate = false;
  14229. geometry.morphTargetsNeedUpdate = false;
  14230. geometry.elementsNeedUpdate = false;
  14231. geometry.uvsNeedUpdate = false;
  14232. geometry.normalsNeedUpdate = false;
  14233. geometry.colorsNeedUpdate = false;
  14234. geometry.tangentsNeedUpdate = false;
  14235. geometry.buffersNeedUpdate = false;
  14236. material.attributes && clearCustomAttributes( material );
  14237. } else if ( object instanceof THREE.Ribbon ) {
  14238. material = getBufferMaterial( object, geometry );
  14239. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14240. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  14241. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  14242. }
  14243. geometry.verticesNeedUpdate = false;
  14244. geometry.colorsNeedUpdate = false;
  14245. geometry.normalsNeedUpdate = false;
  14246. material.attributes && clearCustomAttributes( material );
  14247. } else if ( object instanceof THREE.Line ) {
  14248. material = getBufferMaterial( object, geometry );
  14249. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14250. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14251. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14252. }
  14253. geometry.verticesNeedUpdate = false;
  14254. geometry.colorsNeedUpdate = false;
  14255. geometry.lineDistancesNeedUpdate = false;
  14256. material.attributes && clearCustomAttributes( material );
  14257. } else if ( object instanceof THREE.ParticleSystem ) {
  14258. material = getBufferMaterial( object, geometry );
  14259. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14260. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14261. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14262. }
  14263. geometry.verticesNeedUpdate = false;
  14264. geometry.colorsNeedUpdate = false;
  14265. material.attributes && clearCustomAttributes( material );
  14266. }
  14267. };
  14268. // Objects updates - custom attributes check
  14269. function areCustomAttributesDirty( material ) {
  14270. for ( var a in material.attributes ) {
  14271. if ( material.attributes[ a ].needsUpdate ) return true;
  14272. }
  14273. return false;
  14274. };
  14275. function clearCustomAttributes( material ) {
  14276. for ( var a in material.attributes ) {
  14277. material.attributes[ a ].needsUpdate = false;
  14278. }
  14279. };
  14280. // Objects removal
  14281. function removeObject( object, scene ) {
  14282. if ( object instanceof THREE.Mesh ||
  14283. object instanceof THREE.ParticleSystem ||
  14284. object instanceof THREE.Ribbon ||
  14285. object instanceof THREE.Line ) {
  14286. removeInstances( scene.__webglObjects, object );
  14287. } else if ( object instanceof THREE.Sprite ) {
  14288. removeInstancesDirect( scene.__webglSprites, object );
  14289. } else if ( object instanceof THREE.LensFlare ) {
  14290. removeInstancesDirect( scene.__webglFlares, object );
  14291. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14292. removeInstances( scene.__webglObjectsImmediate, object );
  14293. }
  14294. delete object.__webglActive;
  14295. };
  14296. function removeInstances( objlist, object ) {
  14297. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14298. if ( objlist[ o ].object === object ) {
  14299. objlist.splice( o, 1 );
  14300. }
  14301. }
  14302. };
  14303. function removeInstancesDirect( objlist, object ) {
  14304. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14305. if ( objlist[ o ] === object ) {
  14306. objlist.splice( o, 1 );
  14307. }
  14308. }
  14309. };
  14310. // Materials
  14311. this.initMaterial = function ( material, lights, fog, object ) {
  14312. material.addEventListener( 'dispose', onMaterialDispose );
  14313. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14314. if ( material instanceof THREE.MeshDepthMaterial ) {
  14315. shaderID = 'depth';
  14316. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14317. shaderID = 'normal';
  14318. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14319. shaderID = 'basic';
  14320. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14321. shaderID = 'lambert';
  14322. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14323. shaderID = 'phong';
  14324. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14325. shaderID = 'basic';
  14326. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14327. shaderID = 'dashed';
  14328. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14329. shaderID = 'particle_basic';
  14330. }
  14331. if ( shaderID ) {
  14332. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14333. }
  14334. // heuristics to create shader parameters according to lights in the scene
  14335. // (not to blow over maxLights budget)
  14336. maxLightCount = allocateLights( lights );
  14337. maxShadows = allocateShadows( lights );
  14338. maxBones = allocateBones( object );
  14339. parameters = {
  14340. map: !!material.map,
  14341. envMap: !!material.envMap,
  14342. lightMap: !!material.lightMap,
  14343. bumpMap: !!material.bumpMap,
  14344. normalMap: !!material.normalMap,
  14345. specularMap: !!material.specularMap,
  14346. vertexColors: material.vertexColors,
  14347. fog: fog,
  14348. useFog: material.fog,
  14349. fogExp: fog instanceof THREE.FogExp2,
  14350. sizeAttenuation: material.sizeAttenuation,
  14351. skinning: material.skinning,
  14352. maxBones: maxBones,
  14353. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14354. boneTextureWidth: object && object.boneTextureWidth,
  14355. boneTextureHeight: object && object.boneTextureHeight,
  14356. morphTargets: material.morphTargets,
  14357. morphNormals: material.morphNormals,
  14358. maxMorphTargets: this.maxMorphTargets,
  14359. maxMorphNormals: this.maxMorphNormals,
  14360. maxDirLights: maxLightCount.directional,
  14361. maxPointLights: maxLightCount.point,
  14362. maxSpotLights: maxLightCount.spot,
  14363. maxHemiLights: maxLightCount.hemi,
  14364. maxShadows: maxShadows,
  14365. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  14366. shadowMapType: this.shadowMapType,
  14367. shadowMapDebug: this.shadowMapDebug,
  14368. shadowMapCascade: this.shadowMapCascade,
  14369. alphaTest: material.alphaTest,
  14370. metal: material.metal,
  14371. perPixel: material.perPixel,
  14372. wrapAround: material.wrapAround,
  14373. doubleSided: material.side === THREE.DoubleSide,
  14374. flipSided: material.side === THREE.BackSide
  14375. };
  14376. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  14377. var attributes = material.program.attributes;
  14378. if ( material.morphTargets ) {
  14379. material.numSupportedMorphTargets = 0;
  14380. var id, base = "morphTarget";
  14381. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14382. id = base + i;
  14383. if ( attributes[ id ] >= 0 ) {
  14384. material.numSupportedMorphTargets ++;
  14385. }
  14386. }
  14387. }
  14388. if ( material.morphNormals ) {
  14389. material.numSupportedMorphNormals = 0;
  14390. var id, base = "morphNormal";
  14391. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14392. id = base + i;
  14393. if ( attributes[ id ] >= 0 ) {
  14394. material.numSupportedMorphNormals ++;
  14395. }
  14396. }
  14397. }
  14398. material.uniformsList = [];
  14399. for ( u in material.uniforms ) {
  14400. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14401. }
  14402. };
  14403. function setMaterialShaders( material, shaders ) {
  14404. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14405. material.vertexShader = shaders.vertexShader;
  14406. material.fragmentShader = shaders.fragmentShader;
  14407. };
  14408. function setProgram( camera, lights, fog, material, object ) {
  14409. _usedTextureUnits = 0;
  14410. if ( material.needsUpdate ) {
  14411. if ( material.program ) deallocateMaterial( material );
  14412. _this.initMaterial( material, lights, fog, object );
  14413. material.needsUpdate = false;
  14414. }
  14415. if ( material.morphTargets ) {
  14416. if ( ! object.__webglMorphTargetInfluences ) {
  14417. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14418. }
  14419. }
  14420. var refreshMaterial = false;
  14421. var program = material.program,
  14422. p_uniforms = program.uniforms,
  14423. m_uniforms = material.uniforms;
  14424. if ( program !== _currentProgram ) {
  14425. _gl.useProgram( program );
  14426. _currentProgram = program;
  14427. refreshMaterial = true;
  14428. }
  14429. if ( material.id !== _currentMaterialId ) {
  14430. _currentMaterialId = material.id;
  14431. refreshMaterial = true;
  14432. }
  14433. if ( refreshMaterial || camera !== _currentCamera ) {
  14434. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14435. if ( camera !== _currentCamera ) _currentCamera = camera;
  14436. }
  14437. // skinning uniforms must be set even if material didn't change
  14438. // auto-setting of texture unit for bone texture must go before other textures
  14439. // not sure why, but otherwise weird things happen
  14440. if ( material.skinning ) {
  14441. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14442. if ( p_uniforms.boneTexture !== null ) {
  14443. var textureUnit = getTextureUnit();
  14444. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14445. _this.setTexture( object.boneTexture, textureUnit );
  14446. }
  14447. } else {
  14448. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14449. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14450. }
  14451. }
  14452. }
  14453. if ( refreshMaterial ) {
  14454. // refresh uniforms common to several materials
  14455. if ( fog && material.fog ) {
  14456. refreshUniformsFog( m_uniforms, fog );
  14457. }
  14458. if ( material instanceof THREE.MeshPhongMaterial ||
  14459. material instanceof THREE.MeshLambertMaterial ||
  14460. material.lights ) {
  14461. if ( _lightsNeedUpdate ) {
  14462. setupLights( program, lights );
  14463. _lightsNeedUpdate = false;
  14464. }
  14465. refreshUniformsLights( m_uniforms, _lights );
  14466. }
  14467. if ( material instanceof THREE.MeshBasicMaterial ||
  14468. material instanceof THREE.MeshLambertMaterial ||
  14469. material instanceof THREE.MeshPhongMaterial ) {
  14470. refreshUniformsCommon( m_uniforms, material );
  14471. }
  14472. // refresh single material specific uniforms
  14473. if ( material instanceof THREE.LineBasicMaterial ) {
  14474. refreshUniformsLine( m_uniforms, material );
  14475. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14476. refreshUniformsLine( m_uniforms, material );
  14477. refreshUniformsDash( m_uniforms, material );
  14478. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14479. refreshUniformsParticle( m_uniforms, material );
  14480. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14481. refreshUniformsPhong( m_uniforms, material );
  14482. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14483. refreshUniformsLambert( m_uniforms, material );
  14484. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14485. m_uniforms.mNear.value = camera.near;
  14486. m_uniforms.mFar.value = camera.far;
  14487. m_uniforms.opacity.value = material.opacity;
  14488. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14489. m_uniforms.opacity.value = material.opacity;
  14490. }
  14491. if ( object.receiveShadow && ! material._shadowPass ) {
  14492. refreshUniformsShadow( m_uniforms, lights );
  14493. }
  14494. // load common uniforms
  14495. loadUniformsGeneric( program, material.uniformsList );
  14496. // load material specific uniforms
  14497. // (shader material also gets them for the sake of genericity)
  14498. if ( material instanceof THREE.ShaderMaterial ||
  14499. material instanceof THREE.MeshPhongMaterial ||
  14500. material.envMap ) {
  14501. if ( p_uniforms.cameraPosition !== null ) {
  14502. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14503. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14504. }
  14505. }
  14506. if ( material instanceof THREE.MeshPhongMaterial ||
  14507. material instanceof THREE.MeshLambertMaterial ||
  14508. material instanceof THREE.ShaderMaterial ||
  14509. material.skinning ) {
  14510. if ( p_uniforms.viewMatrix !== null ) {
  14511. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14512. }
  14513. }
  14514. }
  14515. loadUniformsMatrices( p_uniforms, object );
  14516. if ( p_uniforms.modelMatrix !== null ) {
  14517. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14518. }
  14519. return program;
  14520. };
  14521. // Uniforms (refresh uniforms objects)
  14522. function refreshUniformsCommon ( uniforms, material ) {
  14523. uniforms.opacity.value = material.opacity;
  14524. if ( _this.gammaInput ) {
  14525. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14526. } else {
  14527. uniforms.diffuse.value = material.color;
  14528. }
  14529. uniforms.map.value = material.map;
  14530. uniforms.lightMap.value = material.lightMap;
  14531. uniforms.specularMap.value = material.specularMap;
  14532. if ( material.bumpMap ) {
  14533. uniforms.bumpMap.value = material.bumpMap;
  14534. uniforms.bumpScale.value = material.bumpScale;
  14535. }
  14536. if ( material.normalMap ) {
  14537. uniforms.normalMap.value = material.normalMap;
  14538. uniforms.normalScale.value.copy( material.normalScale );
  14539. }
  14540. // uv repeat and offset setting priorities
  14541. // 1. color map
  14542. // 2. specular map
  14543. // 3. normal map
  14544. // 4. bump map
  14545. var uvScaleMap;
  14546. if ( material.map ) {
  14547. uvScaleMap = material.map;
  14548. } else if ( material.specularMap ) {
  14549. uvScaleMap = material.specularMap;
  14550. } else if ( material.normalMap ) {
  14551. uvScaleMap = material.normalMap;
  14552. } else if ( material.bumpMap ) {
  14553. uvScaleMap = material.bumpMap;
  14554. }
  14555. if ( uvScaleMap !== undefined ) {
  14556. var offset = uvScaleMap.offset;
  14557. var repeat = uvScaleMap.repeat;
  14558. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14559. }
  14560. uniforms.envMap.value = material.envMap;
  14561. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14562. if ( _this.gammaInput ) {
  14563. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14564. uniforms.reflectivity.value = material.reflectivity;
  14565. } else {
  14566. uniforms.reflectivity.value = material.reflectivity;
  14567. }
  14568. uniforms.refractionRatio.value = material.refractionRatio;
  14569. uniforms.combine.value = material.combine;
  14570. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14571. };
  14572. function refreshUniformsLine ( uniforms, material ) {
  14573. uniforms.diffuse.value = material.color;
  14574. uniforms.opacity.value = material.opacity;
  14575. };
  14576. function refreshUniformsDash ( uniforms, material ) {
  14577. uniforms.dashSize.value = material.dashSize;
  14578. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14579. uniforms.scale.value = material.scale;
  14580. };
  14581. function refreshUniformsParticle ( uniforms, material ) {
  14582. uniforms.psColor.value = material.color;
  14583. uniforms.opacity.value = material.opacity;
  14584. uniforms.size.value = material.size;
  14585. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14586. uniforms.map.value = material.map;
  14587. };
  14588. function refreshUniformsFog ( uniforms, fog ) {
  14589. uniforms.fogColor.value = fog.color;
  14590. if ( fog instanceof THREE.Fog ) {
  14591. uniforms.fogNear.value = fog.near;
  14592. uniforms.fogFar.value = fog.far;
  14593. } else if ( fog instanceof THREE.FogExp2 ) {
  14594. uniforms.fogDensity.value = fog.density;
  14595. }
  14596. };
  14597. function refreshUniformsPhong ( uniforms, material ) {
  14598. uniforms.shininess.value = material.shininess;
  14599. if ( _this.gammaInput ) {
  14600. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14601. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14602. uniforms.specular.value.copyGammaToLinear( material.specular );
  14603. } else {
  14604. uniforms.ambient.value = material.ambient;
  14605. uniforms.emissive.value = material.emissive;
  14606. uniforms.specular.value = material.specular;
  14607. }
  14608. if ( material.wrapAround ) {
  14609. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14610. }
  14611. };
  14612. function refreshUniformsLambert ( uniforms, material ) {
  14613. if ( _this.gammaInput ) {
  14614. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14615. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14616. } else {
  14617. uniforms.ambient.value = material.ambient;
  14618. uniforms.emissive.value = material.emissive;
  14619. }
  14620. if ( material.wrapAround ) {
  14621. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14622. }
  14623. };
  14624. function refreshUniformsLights ( uniforms, lights ) {
  14625. uniforms.ambientLightColor.value = lights.ambient;
  14626. uniforms.directionalLightColor.value = lights.directional.colors;
  14627. uniforms.directionalLightDirection.value = lights.directional.positions;
  14628. uniforms.pointLightColor.value = lights.point.colors;
  14629. uniforms.pointLightPosition.value = lights.point.positions;
  14630. uniforms.pointLightDistance.value = lights.point.distances;
  14631. uniforms.spotLightColor.value = lights.spot.colors;
  14632. uniforms.spotLightPosition.value = lights.spot.positions;
  14633. uniforms.spotLightDistance.value = lights.spot.distances;
  14634. uniforms.spotLightDirection.value = lights.spot.directions;
  14635. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14636. uniforms.spotLightExponent.value = lights.spot.exponents;
  14637. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14638. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14639. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14640. };
  14641. function refreshUniformsShadow ( uniforms, lights ) {
  14642. if ( uniforms.shadowMatrix ) {
  14643. var j = 0;
  14644. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14645. var light = lights[ i ];
  14646. if ( ! light.castShadow ) continue;
  14647. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14648. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14649. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14650. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14651. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14652. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14653. j ++;
  14654. }
  14655. }
  14656. }
  14657. };
  14658. // Uniforms (load to GPU)
  14659. function loadUniformsMatrices ( uniforms, object ) {
  14660. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14661. if ( uniforms.normalMatrix ) {
  14662. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14663. }
  14664. };
  14665. function getTextureUnit() {
  14666. var textureUnit = _usedTextureUnits;
  14667. if ( textureUnit >= _maxTextures ) {
  14668. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14669. }
  14670. _usedTextureUnits += 1;
  14671. return textureUnit;
  14672. };
  14673. function loadUniformsGeneric ( program, uniforms ) {
  14674. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14675. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14676. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14677. if ( !location ) continue;
  14678. uniform = uniforms[ j ][ 0 ];
  14679. type = uniform.type;
  14680. value = uniform.value;
  14681. if ( type === "i" ) { // single integer
  14682. _gl.uniform1i( location, value );
  14683. } else if ( type === "f" ) { // single float
  14684. _gl.uniform1f( location, value );
  14685. } else if ( type === "v2" ) { // single THREE.Vector2
  14686. _gl.uniform2f( location, value.x, value.y );
  14687. } else if ( type === "v3" ) { // single THREE.Vector3
  14688. _gl.uniform3f( location, value.x, value.y, value.z );
  14689. } else if ( type === "v4" ) { // single THREE.Vector4
  14690. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14691. } else if ( type === "c" ) { // single THREE.Color
  14692. _gl.uniform3f( location, value.r, value.g, value.b );
  14693. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14694. _gl.uniform1iv( location, value );
  14695. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14696. _gl.uniform3iv( location, value );
  14697. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14698. _gl.uniform1fv( location, value );
  14699. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14700. _gl.uniform3fv( location, value );
  14701. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14702. if ( uniform._array === undefined ) {
  14703. uniform._array = new Float32Array( 2 * value.length );
  14704. }
  14705. for ( i = 0, il = value.length; i < il; i ++ ) {
  14706. offset = i * 2;
  14707. uniform._array[ offset ] = value[ i ].x;
  14708. uniform._array[ offset + 1 ] = value[ i ].y;
  14709. }
  14710. _gl.uniform2fv( location, uniform._array );
  14711. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14712. if ( uniform._array === undefined ) {
  14713. uniform._array = new Float32Array( 3 * value.length );
  14714. }
  14715. for ( i = 0, il = value.length; i < il; i ++ ) {
  14716. offset = i * 3;
  14717. uniform._array[ offset ] = value[ i ].x;
  14718. uniform._array[ offset + 1 ] = value[ i ].y;
  14719. uniform._array[ offset + 2 ] = value[ i ].z;
  14720. }
  14721. _gl.uniform3fv( location, uniform._array );
  14722. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14723. if ( uniform._array === undefined ) {
  14724. uniform._array = new Float32Array( 4 * value.length );
  14725. }
  14726. for ( i = 0, il = value.length; i < il; i ++ ) {
  14727. offset = i * 4;
  14728. uniform._array[ offset ] = value[ i ].x;
  14729. uniform._array[ offset + 1 ] = value[ i ].y;
  14730. uniform._array[ offset + 2 ] = value[ i ].z;
  14731. uniform._array[ offset + 3 ] = value[ i ].w;
  14732. }
  14733. _gl.uniform4fv( location, uniform._array );
  14734. } else if ( type === "m4") { // single THREE.Matrix4
  14735. if ( uniform._array === undefined ) {
  14736. uniform._array = new Float32Array( 16 );
  14737. }
  14738. value.flattenToArray( uniform._array );
  14739. _gl.uniformMatrix4fv( location, false, uniform._array );
  14740. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14741. if ( uniform._array === undefined ) {
  14742. uniform._array = new Float32Array( 16 * value.length );
  14743. }
  14744. for ( i = 0, il = value.length; i < il; i ++ ) {
  14745. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14746. }
  14747. _gl.uniformMatrix4fv( location, false, uniform._array );
  14748. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14749. texture = value;
  14750. textureUnit = getTextureUnit();
  14751. _gl.uniform1i( location, textureUnit );
  14752. if ( !texture ) continue;
  14753. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14754. setCubeTexture( texture, textureUnit );
  14755. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14756. setCubeTextureDynamic( texture, textureUnit );
  14757. } else {
  14758. _this.setTexture( texture, textureUnit );
  14759. }
  14760. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14761. if ( uniform._array === undefined ) {
  14762. uniform._array = [];
  14763. }
  14764. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14765. uniform._array[ i ] = getTextureUnit();
  14766. }
  14767. _gl.uniform1iv( location, uniform._array );
  14768. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14769. texture = uniform.value[ i ];
  14770. textureUnit = uniform._array[ i ];
  14771. if ( !texture ) continue;
  14772. _this.setTexture( texture, textureUnit );
  14773. }
  14774. }
  14775. }
  14776. };
  14777. function setupMatrices ( object, camera ) {
  14778. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14779. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14780. };
  14781. //
  14782. function setColorGamma( array, offset, color, intensitySq ) {
  14783. array[ offset ] = color.r * color.r * intensitySq;
  14784. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14785. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14786. };
  14787. function setColorLinear( array, offset, color, intensity ) {
  14788. array[ offset ] = color.r * intensity;
  14789. array[ offset + 1 ] = color.g * intensity;
  14790. array[ offset + 2 ] = color.b * intensity;
  14791. };
  14792. function setupLights ( program, lights ) {
  14793. var l, ll, light, n,
  14794. r = 0, g = 0, b = 0,
  14795. color, skyColor, groundColor,
  14796. intensity, intensitySq,
  14797. position,
  14798. distance,
  14799. zlights = _lights,
  14800. dirColors = zlights.directional.colors,
  14801. dirPositions = zlights.directional.positions,
  14802. pointColors = zlights.point.colors,
  14803. pointPositions = zlights.point.positions,
  14804. pointDistances = zlights.point.distances,
  14805. spotColors = zlights.spot.colors,
  14806. spotPositions = zlights.spot.positions,
  14807. spotDistances = zlights.spot.distances,
  14808. spotDirections = zlights.spot.directions,
  14809. spotAnglesCos = zlights.spot.anglesCos,
  14810. spotExponents = zlights.spot.exponents,
  14811. hemiSkyColors = zlights.hemi.skyColors,
  14812. hemiGroundColors = zlights.hemi.groundColors,
  14813. hemiPositions = zlights.hemi.positions,
  14814. dirLength = 0,
  14815. pointLength = 0,
  14816. spotLength = 0,
  14817. hemiLength = 0,
  14818. dirCount = 0,
  14819. pointCount = 0,
  14820. spotCount = 0,
  14821. hemiCount = 0,
  14822. dirOffset = 0,
  14823. pointOffset = 0,
  14824. spotOffset = 0,
  14825. hemiOffset = 0;
  14826. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14827. light = lights[ l ];
  14828. if ( light.onlyShadow ) continue;
  14829. color = light.color;
  14830. intensity = light.intensity;
  14831. distance = light.distance;
  14832. if ( light instanceof THREE.AmbientLight ) {
  14833. if ( ! light.visible ) continue;
  14834. if ( _this.gammaInput ) {
  14835. r += color.r * color.r;
  14836. g += color.g * color.g;
  14837. b += color.b * color.b;
  14838. } else {
  14839. r += color.r;
  14840. g += color.g;
  14841. b += color.b;
  14842. }
  14843. } else if ( light instanceof THREE.DirectionalLight ) {
  14844. dirCount += 1;
  14845. if ( ! light.visible ) continue;
  14846. _direction.getPositionFromMatrix( light.matrixWorld );
  14847. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14848. _direction.sub( _vector3 );
  14849. _direction.normalize();
  14850. // skip lights with undefined direction
  14851. // these create troubles in OpenGL (making pixel black)
  14852. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14853. dirOffset = dirLength * 3;
  14854. dirPositions[ dirOffset ] = _direction.x;
  14855. dirPositions[ dirOffset + 1 ] = _direction.y;
  14856. dirPositions[ dirOffset + 2 ] = _direction.z;
  14857. if ( _this.gammaInput ) {
  14858. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14859. } else {
  14860. setColorLinear( dirColors, dirOffset, color, intensity );
  14861. }
  14862. dirLength += 1;
  14863. } else if ( light instanceof THREE.PointLight ) {
  14864. pointCount += 1;
  14865. if ( ! light.visible ) continue;
  14866. pointOffset = pointLength * 3;
  14867. if ( _this.gammaInput ) {
  14868. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14869. } else {
  14870. setColorLinear( pointColors, pointOffset, color, intensity );
  14871. }
  14872. _vector3.getPositionFromMatrix( light.matrixWorld );
  14873. pointPositions[ pointOffset ] = _vector3.x;
  14874. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14875. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14876. pointDistances[ pointLength ] = distance;
  14877. pointLength += 1;
  14878. } else if ( light instanceof THREE.SpotLight ) {
  14879. spotCount += 1;
  14880. if ( ! light.visible ) continue;
  14881. spotOffset = spotLength * 3;
  14882. if ( _this.gammaInput ) {
  14883. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14884. } else {
  14885. setColorLinear( spotColors, spotOffset, color, intensity );
  14886. }
  14887. _vector3.getPositionFromMatrix( light.matrixWorld );
  14888. spotPositions[ spotOffset ] = _vector3.x;
  14889. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14890. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14891. spotDistances[ spotLength ] = distance;
  14892. _direction.copy( _vector3 );
  14893. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14894. _direction.sub( _vector3 );
  14895. _direction.normalize();
  14896. spotDirections[ spotOffset ] = _direction.x;
  14897. spotDirections[ spotOffset + 1 ] = _direction.y;
  14898. spotDirections[ spotOffset + 2 ] = _direction.z;
  14899. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14900. spotExponents[ spotLength ] = light.exponent;
  14901. spotLength += 1;
  14902. } else if ( light instanceof THREE.HemisphereLight ) {
  14903. hemiCount += 1;
  14904. if ( ! light.visible ) continue;
  14905. _direction.getPositionFromMatrix( light.matrixWorld );
  14906. _direction.normalize();
  14907. // skip lights with undefined direction
  14908. // these create troubles in OpenGL (making pixel black)
  14909. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14910. hemiOffset = hemiLength * 3;
  14911. hemiPositions[ hemiOffset ] = _direction.x;
  14912. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14913. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14914. skyColor = light.color;
  14915. groundColor = light.groundColor;
  14916. if ( _this.gammaInput ) {
  14917. intensitySq = intensity * intensity;
  14918. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14919. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14920. } else {
  14921. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14922. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14923. }
  14924. hemiLength += 1;
  14925. }
  14926. }
  14927. // null eventual remains from removed lights
  14928. // (this is to avoid if in shader)
  14929. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14930. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14931. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14932. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14933. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14934. zlights.directional.length = dirLength;
  14935. zlights.point.length = pointLength;
  14936. zlights.spot.length = spotLength;
  14937. zlights.hemi.length = hemiLength;
  14938. zlights.ambient[ 0 ] = r;
  14939. zlights.ambient[ 1 ] = g;
  14940. zlights.ambient[ 2 ] = b;
  14941. };
  14942. // GL state setting
  14943. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14944. if ( cullFace === THREE.CullFaceNone ) {
  14945. _gl.disable( _gl.CULL_FACE );
  14946. } else {
  14947. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14948. _gl.frontFace( _gl.CW );
  14949. } else {
  14950. _gl.frontFace( _gl.CCW );
  14951. }
  14952. if ( cullFace === THREE.CullFaceBack ) {
  14953. _gl.cullFace( _gl.BACK );
  14954. } else if ( cullFace === THREE.CullFaceFront ) {
  14955. _gl.cullFace( _gl.FRONT );
  14956. } else {
  14957. _gl.cullFace( _gl.FRONT_AND_BACK );
  14958. }
  14959. _gl.enable( _gl.CULL_FACE );
  14960. }
  14961. };
  14962. this.setMaterialFaces = function ( material ) {
  14963. var doubleSided = material.side === THREE.DoubleSide;
  14964. var flipSided = material.side === THREE.BackSide;
  14965. if ( _oldDoubleSided !== doubleSided ) {
  14966. if ( doubleSided ) {
  14967. _gl.disable( _gl.CULL_FACE );
  14968. } else {
  14969. _gl.enable( _gl.CULL_FACE );
  14970. }
  14971. _oldDoubleSided = doubleSided;
  14972. }
  14973. if ( _oldFlipSided !== flipSided ) {
  14974. if ( flipSided ) {
  14975. _gl.frontFace( _gl.CW );
  14976. } else {
  14977. _gl.frontFace( _gl.CCW );
  14978. }
  14979. _oldFlipSided = flipSided;
  14980. }
  14981. };
  14982. this.setDepthTest = function ( depthTest ) {
  14983. if ( _oldDepthTest !== depthTest ) {
  14984. if ( depthTest ) {
  14985. _gl.enable( _gl.DEPTH_TEST );
  14986. } else {
  14987. _gl.disable( _gl.DEPTH_TEST );
  14988. }
  14989. _oldDepthTest = depthTest;
  14990. }
  14991. };
  14992. this.setDepthWrite = function ( depthWrite ) {
  14993. if ( _oldDepthWrite !== depthWrite ) {
  14994. _gl.depthMask( depthWrite );
  14995. _oldDepthWrite = depthWrite;
  14996. }
  14997. };
  14998. function setLineWidth ( width ) {
  14999. if ( width !== _oldLineWidth ) {
  15000. _gl.lineWidth( width );
  15001. _oldLineWidth = width;
  15002. }
  15003. };
  15004. function setPolygonOffset ( polygonoffset, factor, units ) {
  15005. if ( _oldPolygonOffset !== polygonoffset ) {
  15006. if ( polygonoffset ) {
  15007. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15008. } else {
  15009. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15010. }
  15011. _oldPolygonOffset = polygonoffset;
  15012. }
  15013. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15014. _gl.polygonOffset( factor, units );
  15015. _oldPolygonOffsetFactor = factor;
  15016. _oldPolygonOffsetUnits = units;
  15017. }
  15018. };
  15019. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15020. if ( blending !== _oldBlending ) {
  15021. if ( blending === THREE.NoBlending ) {
  15022. _gl.disable( _gl.BLEND );
  15023. } else if ( blending === THREE.AdditiveBlending ) {
  15024. _gl.enable( _gl.BLEND );
  15025. _gl.blendEquation( _gl.FUNC_ADD );
  15026. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15027. } else if ( blending === THREE.SubtractiveBlending ) {
  15028. // TODO: Find blendFuncSeparate() combination
  15029. _gl.enable( _gl.BLEND );
  15030. _gl.blendEquation( _gl.FUNC_ADD );
  15031. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15032. } else if ( blending === THREE.MultiplyBlending ) {
  15033. // TODO: Find blendFuncSeparate() combination
  15034. _gl.enable( _gl.BLEND );
  15035. _gl.blendEquation( _gl.FUNC_ADD );
  15036. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15037. } else if ( blending === THREE.CustomBlending ) {
  15038. _gl.enable( _gl.BLEND );
  15039. } else {
  15040. _gl.enable( _gl.BLEND );
  15041. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15042. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15043. }
  15044. _oldBlending = blending;
  15045. }
  15046. if ( blending === THREE.CustomBlending ) {
  15047. if ( blendEquation !== _oldBlendEquation ) {
  15048. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15049. _oldBlendEquation = blendEquation;
  15050. }
  15051. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15052. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15053. _oldBlendSrc = blendSrc;
  15054. _oldBlendDst = blendDst;
  15055. }
  15056. } else {
  15057. _oldBlendEquation = null;
  15058. _oldBlendSrc = null;
  15059. _oldBlendDst = null;
  15060. }
  15061. };
  15062. // Defines
  15063. function generateDefines ( defines ) {
  15064. var value, chunk, chunks = [];
  15065. for ( var d in defines ) {
  15066. value = defines[ d ];
  15067. if ( value === false ) continue;
  15068. chunk = "#define " + d + " " + value;
  15069. chunks.push( chunk );
  15070. }
  15071. return chunks.join( "\n" );
  15072. };
  15073. // Shaders
  15074. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  15075. var p, pl, d, program, code;
  15076. var chunks = [];
  15077. // Generate code
  15078. if ( shaderID ) {
  15079. chunks.push( shaderID );
  15080. } else {
  15081. chunks.push( fragmentShader );
  15082. chunks.push( vertexShader );
  15083. }
  15084. for ( d in defines ) {
  15085. chunks.push( d );
  15086. chunks.push( defines[ d ] );
  15087. }
  15088. for ( p in parameters ) {
  15089. chunks.push( p );
  15090. chunks.push( parameters[ p ] );
  15091. }
  15092. code = chunks.join();
  15093. // Check if code has been already compiled
  15094. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  15095. var programInfo = _programs[ p ];
  15096. if ( programInfo.code === code ) {
  15097. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  15098. programInfo.usedTimes ++;
  15099. return programInfo.program;
  15100. }
  15101. }
  15102. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15103. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15104. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15105. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15106. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15107. }
  15108. // console.log( "building new program " );
  15109. //
  15110. var customDefines = generateDefines( defines );
  15111. //
  15112. program = _gl.createProgram();
  15113. var prefix_vertex = [
  15114. "precision " + _precision + " float;",
  15115. customDefines,
  15116. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15117. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15118. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15119. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15120. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15121. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15122. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15123. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15124. "#define MAX_SHADOWS " + parameters.maxShadows,
  15125. "#define MAX_BONES " + parameters.maxBones,
  15126. parameters.map ? "#define USE_MAP" : "",
  15127. parameters.envMap ? "#define USE_ENVMAP" : "",
  15128. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15129. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15130. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15131. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15132. parameters.vertexColors ? "#define USE_COLOR" : "",
  15133. parameters.skinning ? "#define USE_SKINNING" : "",
  15134. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15135. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  15136. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  15137. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15138. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15139. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15140. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15141. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15142. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15143. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15144. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15145. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15146. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15147. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15148. "uniform mat4 modelMatrix;",
  15149. "uniform mat4 modelViewMatrix;",
  15150. "uniform mat4 projectionMatrix;",
  15151. "uniform mat4 viewMatrix;",
  15152. "uniform mat3 normalMatrix;",
  15153. "uniform vec3 cameraPosition;",
  15154. "attribute vec3 position;",
  15155. "attribute vec3 normal;",
  15156. "attribute vec2 uv;",
  15157. "attribute vec2 uv2;",
  15158. "#ifdef USE_COLOR",
  15159. "attribute vec3 color;",
  15160. "#endif",
  15161. "#ifdef USE_MORPHTARGETS",
  15162. "attribute vec3 morphTarget0;",
  15163. "attribute vec3 morphTarget1;",
  15164. "attribute vec3 morphTarget2;",
  15165. "attribute vec3 morphTarget3;",
  15166. "#ifdef USE_MORPHNORMALS",
  15167. "attribute vec3 morphNormal0;",
  15168. "attribute vec3 morphNormal1;",
  15169. "attribute vec3 morphNormal2;",
  15170. "attribute vec3 morphNormal3;",
  15171. "#else",
  15172. "attribute vec3 morphTarget4;",
  15173. "attribute vec3 morphTarget5;",
  15174. "attribute vec3 morphTarget6;",
  15175. "attribute vec3 morphTarget7;",
  15176. "#endif",
  15177. "#endif",
  15178. "#ifdef USE_SKINNING",
  15179. "attribute vec4 skinIndex;",
  15180. "attribute vec4 skinWeight;",
  15181. "#endif",
  15182. ""
  15183. ].join("\n");
  15184. var prefix_fragment = [
  15185. "precision " + _precision + " float;",
  15186. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15187. customDefines,
  15188. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15189. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15190. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15191. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15192. "#define MAX_SHADOWS " + parameters.maxShadows,
  15193. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15194. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15195. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15196. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15197. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15198. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15199. parameters.map ? "#define USE_MAP" : "",
  15200. parameters.envMap ? "#define USE_ENVMAP" : "",
  15201. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15202. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15203. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15204. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15205. parameters.vertexColors ? "#define USE_COLOR" : "",
  15206. parameters.metal ? "#define METAL" : "",
  15207. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15208. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15209. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15210. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15211. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15212. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15213. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15214. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15215. "uniform mat4 viewMatrix;",
  15216. "uniform vec3 cameraPosition;",
  15217. ""
  15218. ].join("\n");
  15219. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15220. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15221. _gl.attachShader( program, glVertexShader );
  15222. _gl.attachShader( program, glFragmentShader );
  15223. _gl.linkProgram( program );
  15224. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  15225. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  15226. }
  15227. // clean up
  15228. _gl.deleteShader( glFragmentShader );
  15229. _gl.deleteShader( glVertexShader );
  15230. // console.log( prefix_fragment + fragmentShader );
  15231. // console.log( prefix_vertex + vertexShader );
  15232. program.uniforms = {};
  15233. program.attributes = {};
  15234. var identifiers, u, a, i;
  15235. // cache uniform locations
  15236. identifiers = [
  15237. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15238. 'morphTargetInfluences'
  15239. ];
  15240. if ( parameters.useVertexTexture ) {
  15241. identifiers.push( 'boneTexture' );
  15242. } else {
  15243. identifiers.push( 'boneGlobalMatrices' );
  15244. }
  15245. for ( u in uniforms ) {
  15246. identifiers.push( u );
  15247. }
  15248. cacheUniformLocations( program, identifiers );
  15249. // cache attributes locations
  15250. identifiers = [
  15251. "position", "normal", "uv", "uv2", "tangent", "color",
  15252. "skinIndex", "skinWeight", "lineDistance"
  15253. ];
  15254. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15255. identifiers.push( "morphTarget" + i );
  15256. }
  15257. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15258. identifiers.push( "morphNormal" + i );
  15259. }
  15260. for ( a in attributes ) {
  15261. identifiers.push( a );
  15262. }
  15263. cacheAttributeLocations( program, identifiers );
  15264. program.id = _programs_counter ++;
  15265. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15266. _this.info.memory.programs = _programs.length;
  15267. return program;
  15268. };
  15269. // Shader parameters cache
  15270. function cacheUniformLocations ( program, identifiers ) {
  15271. var i, l, id;
  15272. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15273. id = identifiers[ i ];
  15274. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15275. }
  15276. };
  15277. function cacheAttributeLocations ( program, identifiers ) {
  15278. var i, l, id;
  15279. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15280. id = identifiers[ i ];
  15281. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15282. }
  15283. };
  15284. function addLineNumbers ( string ) {
  15285. var chunks = string.split( "\n" );
  15286. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15287. // Chrome reports shader errors on lines
  15288. // starting counting from 1
  15289. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15290. }
  15291. return chunks.join( "\n" );
  15292. };
  15293. function getShader ( type, string ) {
  15294. var shader;
  15295. if ( type === "fragment" ) {
  15296. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15297. } else if ( type === "vertex" ) {
  15298. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15299. }
  15300. _gl.shaderSource( shader, string );
  15301. _gl.compileShader( shader );
  15302. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15303. console.error( _gl.getShaderInfoLog( shader ) );
  15304. console.error( addLineNumbers( string ) );
  15305. return null;
  15306. }
  15307. return shader;
  15308. };
  15309. // Textures
  15310. function isPowerOfTwo ( value ) {
  15311. return ( value & ( value - 1 ) ) === 0;
  15312. };
  15313. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15314. if ( isImagePowerOfTwo ) {
  15315. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15316. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15317. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15318. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15319. } else {
  15320. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15321. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15322. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15323. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15324. }
  15325. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15326. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15327. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15328. texture.__oldAnisotropy = texture.anisotropy;
  15329. }
  15330. }
  15331. };
  15332. this.setTexture = function ( texture, slot ) {
  15333. if ( texture.needsUpdate ) {
  15334. if ( ! texture.__webglInit ) {
  15335. texture.__webglInit = true;
  15336. texture.addEventListener( 'dispose', onTextureDispose );
  15337. texture.__webglTexture = _gl.createTexture();
  15338. _this.info.memory.textures ++;
  15339. }
  15340. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15341. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15342. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15343. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15344. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15345. var image = texture.image,
  15346. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15347. glFormat = paramThreeToGL( texture.format ),
  15348. glType = paramThreeToGL( texture.type );
  15349. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15350. var mipmap, mipmaps = texture.mipmaps;
  15351. if ( texture instanceof THREE.DataTexture ) {
  15352. // use manually created mipmaps if available
  15353. // if there are no manual mipmaps
  15354. // set 0 level mipmap and then use GL to generate other mipmap levels
  15355. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15356. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15357. mipmap = mipmaps[ i ];
  15358. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15359. }
  15360. texture.generateMipmaps = false;
  15361. } else {
  15362. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15363. }
  15364. } else if ( texture instanceof THREE.CompressedTexture ) {
  15365. // compressed textures can only use manually created mipmaps
  15366. // WebGL can't generate mipmaps for DDS textures
  15367. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15368. mipmap = mipmaps[ i ];
  15369. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15370. }
  15371. } else { // regular Texture (image, video, canvas)
  15372. // use manually created mipmaps if available
  15373. // if there are no manual mipmaps
  15374. // set 0 level mipmap and then use GL to generate other mipmap levels
  15375. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15376. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15377. mipmap = mipmaps[ i ];
  15378. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15379. }
  15380. texture.generateMipmaps = false;
  15381. } else {
  15382. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15383. }
  15384. }
  15385. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15386. texture.needsUpdate = false;
  15387. if ( texture.onUpdate ) texture.onUpdate();
  15388. } else {
  15389. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15390. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15391. }
  15392. };
  15393. function clampToMaxSize ( image, maxSize ) {
  15394. if ( image.width <= maxSize && image.height <= maxSize ) {
  15395. return image;
  15396. }
  15397. // Warning: Scaling through the canvas will only work with images that use
  15398. // premultiplied alpha.
  15399. var maxDimension = Math.max( image.width, image.height );
  15400. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15401. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15402. var canvas = document.createElement( 'canvas' );
  15403. canvas.width = newWidth;
  15404. canvas.height = newHeight;
  15405. var ctx = canvas.getContext( "2d" );
  15406. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15407. return canvas;
  15408. }
  15409. function setCubeTexture ( texture, slot ) {
  15410. if ( texture.image.length === 6 ) {
  15411. if ( texture.needsUpdate ) {
  15412. if ( ! texture.image.__webglTextureCube ) {
  15413. texture.addEventListener( 'dispose', onTextureDispose );
  15414. texture.image.__webglTextureCube = _gl.createTexture();
  15415. _this.info.memory.textures ++;
  15416. }
  15417. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15418. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15419. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15420. var isCompressed = texture instanceof THREE.CompressedTexture;
  15421. var cubeImage = [];
  15422. for ( var i = 0; i < 6; i ++ ) {
  15423. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15424. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15425. } else {
  15426. cubeImage[ i ] = texture.image[ i ];
  15427. }
  15428. }
  15429. var image = cubeImage[ 0 ],
  15430. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15431. glFormat = paramThreeToGL( texture.format ),
  15432. glType = paramThreeToGL( texture.type );
  15433. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15434. for ( var i = 0; i < 6; i ++ ) {
  15435. if ( isCompressed ) {
  15436. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15437. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15438. mipmap = mipmaps[ j ];
  15439. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15440. }
  15441. } else {
  15442. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15443. }
  15444. }
  15445. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15446. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15447. }
  15448. texture.needsUpdate = false;
  15449. if ( texture.onUpdate ) texture.onUpdate();
  15450. } else {
  15451. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15452. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15453. }
  15454. }
  15455. };
  15456. function setCubeTextureDynamic ( texture, slot ) {
  15457. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15458. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15459. };
  15460. // Render targets
  15461. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15462. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15463. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15464. };
  15465. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15466. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15467. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15468. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15469. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15470. /* For some reason this is not working. Defaulting to RGBA4.
  15471. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15472. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15473. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15474. */
  15475. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15476. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15477. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15478. } else {
  15479. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15480. }
  15481. };
  15482. this.setRenderTarget = function ( renderTarget ) {
  15483. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15484. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15485. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15486. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15487. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15488. renderTarget.__webglTexture = _gl.createTexture();
  15489. _this.info.memory.textures ++;
  15490. // Setup texture, create render and frame buffers
  15491. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15492. glFormat = paramThreeToGL( renderTarget.format ),
  15493. glType = paramThreeToGL( renderTarget.type );
  15494. if ( isCube ) {
  15495. renderTarget.__webglFramebuffer = [];
  15496. renderTarget.__webglRenderbuffer = [];
  15497. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15498. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15499. for ( var i = 0; i < 6; i ++ ) {
  15500. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15501. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15502. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15503. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15504. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15505. }
  15506. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15507. } else {
  15508. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15509. if ( renderTarget.shareDepthFrom ) {
  15510. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15511. } else {
  15512. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15513. }
  15514. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15515. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15516. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15517. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15518. if ( renderTarget.shareDepthFrom ) {
  15519. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15520. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15521. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15522. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15523. }
  15524. } else {
  15525. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15526. }
  15527. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15528. }
  15529. // Release everything
  15530. if ( isCube ) {
  15531. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15532. } else {
  15533. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15534. }
  15535. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15536. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15537. }
  15538. var framebuffer, width, height, vx, vy;
  15539. if ( renderTarget ) {
  15540. if ( isCube ) {
  15541. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15542. } else {
  15543. framebuffer = renderTarget.__webglFramebuffer;
  15544. }
  15545. width = renderTarget.width;
  15546. height = renderTarget.height;
  15547. vx = 0;
  15548. vy = 0;
  15549. } else {
  15550. framebuffer = null;
  15551. width = _viewportWidth;
  15552. height = _viewportHeight;
  15553. vx = _viewportX;
  15554. vy = _viewportY;
  15555. }
  15556. if ( framebuffer !== _currentFramebuffer ) {
  15557. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15558. _gl.viewport( vx, vy, width, height );
  15559. _currentFramebuffer = framebuffer;
  15560. }
  15561. _currentWidth = width;
  15562. _currentHeight = height;
  15563. };
  15564. function updateRenderTargetMipmap ( renderTarget ) {
  15565. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15566. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15567. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15568. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15569. } else {
  15570. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15571. _gl.generateMipmap( _gl.TEXTURE_2D );
  15572. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15573. }
  15574. };
  15575. // Fallback filters for non-power-of-2 textures
  15576. function filterFallback ( f ) {
  15577. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15578. return _gl.NEAREST;
  15579. }
  15580. return _gl.LINEAR;
  15581. };
  15582. // Map three.js constants to WebGL constants
  15583. function paramThreeToGL ( p ) {
  15584. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15585. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15586. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15587. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15588. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15589. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15590. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15591. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15592. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15593. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15594. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15595. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15596. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15597. if ( p === THREE.ByteType ) return _gl.BYTE;
  15598. if ( p === THREE.ShortType ) return _gl.SHORT;
  15599. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15600. if ( p === THREE.IntType ) return _gl.INT;
  15601. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15602. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15603. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15604. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15605. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15606. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15607. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15608. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15609. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15610. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15611. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15612. if ( p === THREE.OneFactor ) return _gl.ONE;
  15613. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15614. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15615. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15616. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15617. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15618. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15619. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15620. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15621. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15622. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15623. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15624. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15625. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15626. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15627. }
  15628. return 0;
  15629. };
  15630. // Allocations
  15631. function allocateBones ( object ) {
  15632. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15633. return 1024;
  15634. } else {
  15635. // default for when object is not specified
  15636. // ( for example when prebuilding shader
  15637. // to be used with multiple objects )
  15638. //
  15639. // - leave some extra space for other uniforms
  15640. // - limit here is ANGLE's 254 max uniform vectors
  15641. // (up to 54 should be safe)
  15642. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15643. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15644. var maxBones = nVertexMatrices;
  15645. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15646. maxBones = Math.min( object.bones.length, maxBones );
  15647. if ( maxBones < object.bones.length ) {
  15648. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15649. }
  15650. }
  15651. return maxBones;
  15652. }
  15653. };
  15654. function allocateLights( lights ) {
  15655. var dirLights = 0;
  15656. var pointLights = 0;
  15657. var spotLights = 0;
  15658. var hemiLights = 0;
  15659. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15660. var light = lights[ l ];
  15661. if ( light.onlyShadow ) continue;
  15662. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15663. if ( light instanceof THREE.PointLight ) pointLights ++;
  15664. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15665. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15666. }
  15667. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15668. };
  15669. function allocateShadows( lights ) {
  15670. var maxShadows = 0;
  15671. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15672. var light = lights[ l ];
  15673. if ( ! light.castShadow ) continue;
  15674. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15675. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15676. }
  15677. return maxShadows;
  15678. };
  15679. // Initialization
  15680. function initGL() {
  15681. try {
  15682. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15683. throw 'Error creating WebGL context.';
  15684. }
  15685. } catch ( error ) {
  15686. console.error( error );
  15687. }
  15688. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15689. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15690. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15691. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15692. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15693. if ( ! _glExtensionTextureFloat ) {
  15694. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15695. }
  15696. if ( ! _glExtensionStandardDerivatives ) {
  15697. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15698. }
  15699. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15700. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15701. }
  15702. if ( ! _glExtensionCompressedTextureS3TC ) {
  15703. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15704. }
  15705. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15706. _gl.getShaderPrecisionFormat = function() {
  15707. return {
  15708. "rangeMin" : 1,
  15709. "rangeMax" : 1,
  15710. "precision" : 1
  15711. };
  15712. }
  15713. }
  15714. };
  15715. function setDefaultGLState () {
  15716. _gl.clearColor( 0, 0, 0, 1 );
  15717. _gl.clearDepth( 1 );
  15718. _gl.clearStencil( 0 );
  15719. _gl.enable( _gl.DEPTH_TEST );
  15720. _gl.depthFunc( _gl.LEQUAL );
  15721. _gl.frontFace( _gl.CCW );
  15722. _gl.cullFace( _gl.BACK );
  15723. _gl.enable( _gl.CULL_FACE );
  15724. _gl.enable( _gl.BLEND );
  15725. _gl.blendEquation( _gl.FUNC_ADD );
  15726. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15727. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15728. };
  15729. // default plugins (order is important)
  15730. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15731. this.addPrePlugin( this.shadowMapPlugin );
  15732. this.addPostPlugin( new THREE.SpritePlugin() );
  15733. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15734. };
  15735. /**
  15736. * @author szimek / https://github.com/szimek/
  15737. * @author alteredq / http://alteredqualia.com/
  15738. */
  15739. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15740. this.width = width;
  15741. this.height = height;
  15742. options = options || {};
  15743. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15744. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15745. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15746. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15747. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15748. this.offset = new THREE.Vector2( 0, 0 );
  15749. this.repeat = new THREE.Vector2( 1, 1 );
  15750. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15751. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15752. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15753. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15754. this.generateMipmaps = true;
  15755. this.shareDepthFrom = null;
  15756. };
  15757. THREE.WebGLRenderTarget.prototype = {
  15758. constructor: THREE.WebGLRenderTarget,
  15759. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  15760. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  15761. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  15762. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  15763. clone: function () {
  15764. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15765. tmp.wrapS = this.wrapS;
  15766. tmp.wrapT = this.wrapT;
  15767. tmp.magFilter = this.magFilter;
  15768. tmp.minFilter = this.minFilter;
  15769. tmp.anisotropy = this.anisotropy;
  15770. tmp.offset.copy( this.offset );
  15771. tmp.repeat.copy( this.repeat );
  15772. tmp.format = this.format;
  15773. tmp.type = this.type;
  15774. tmp.depthBuffer = this.depthBuffer;
  15775. tmp.stencilBuffer = this.stencilBuffer;
  15776. tmp.generateMipmaps = this.generateMipmaps;
  15777. tmp.shareDepthFrom = this.shareDepthFrom;
  15778. return tmp;
  15779. },
  15780. dispose: function () {
  15781. this.dispatchEvent( { type: 'dispose' } );
  15782. }
  15783. };
  15784. /**
  15785. * @author alteredq / http://alteredqualia.com
  15786. */
  15787. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15788. THREE.WebGLRenderTarget.call( this, width, height, options );
  15789. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15790. };
  15791. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15792. /**
  15793. * @author mrdoob / http://mrdoob.com/
  15794. */
  15795. THREE.RenderableVertex = function () {
  15796. this.positionWorld = new THREE.Vector3();
  15797. this.positionScreen = new THREE.Vector4();
  15798. this.visible = true;
  15799. };
  15800. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15801. this.positionWorld.copy( vertex.positionWorld );
  15802. this.positionScreen.copy( vertex.positionScreen );
  15803. };
  15804. /**
  15805. * @author mrdoob / http://mrdoob.com/
  15806. */
  15807. THREE.RenderableFace3 = function () {
  15808. this.v1 = new THREE.RenderableVertex();
  15809. this.v2 = new THREE.RenderableVertex();
  15810. this.v3 = new THREE.RenderableVertex();
  15811. this.centroidModel = new THREE.Vector3();
  15812. this.normalModel = new THREE.Vector3();
  15813. this.normalModelView = new THREE.Vector3();
  15814. this.vertexNormalsLength = 0;
  15815. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15816. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15817. this.color = null;
  15818. this.material = null;
  15819. this.uvs = [[]];
  15820. this.z = null;
  15821. };
  15822. /**
  15823. * @author mrdoob / http://mrdoob.com/
  15824. */
  15825. THREE.RenderableFace4 = function () {
  15826. this.v1 = new THREE.RenderableVertex();
  15827. this.v2 = new THREE.RenderableVertex();
  15828. this.v3 = new THREE.RenderableVertex();
  15829. this.v4 = new THREE.RenderableVertex();
  15830. this.centroidModel = new THREE.Vector3();
  15831. this.normalModel = new THREE.Vector3();
  15832. this.normalModelView = new THREE.Vector3();
  15833. this.vertexNormalsLength = 0;
  15834. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15835. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15836. this.color = null;
  15837. this.material = null;
  15838. this.uvs = [[]];
  15839. this.z = null;
  15840. };
  15841. /**
  15842. * @author mrdoob / http://mrdoob.com/
  15843. */
  15844. THREE.RenderableObject = function () {
  15845. this.object = null;
  15846. this.z = null;
  15847. };
  15848. /**
  15849. * @author mrdoob / http://mrdoob.com/
  15850. */
  15851. THREE.RenderableParticle = function () {
  15852. this.object = null;
  15853. this.x = null;
  15854. this.y = null;
  15855. this.z = null;
  15856. this.rotation = null;
  15857. this.scale = new THREE.Vector2();
  15858. this.material = null;
  15859. };
  15860. /**
  15861. * @author mrdoob / http://mrdoob.com/
  15862. */
  15863. THREE.RenderableLine = function () {
  15864. this.z = null;
  15865. this.v1 = new THREE.RenderableVertex();
  15866. this.v2 = new THREE.RenderableVertex();
  15867. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15868. this.material = null;
  15869. };
  15870. /**
  15871. * @author mrdoob / http://mrdoob.com/
  15872. * @author alteredq / http://alteredqualia.com/
  15873. */
  15874. THREE.GeometryUtils = {
  15875. // Merge two geometries or geometry and geometry from object (using object's transform)
  15876. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15877. var matrix, normalMatrix,
  15878. vertexOffset = geometry1.vertices.length,
  15879. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15880. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15881. vertices1 = geometry1.vertices,
  15882. vertices2 = geometry2.vertices,
  15883. faces1 = geometry1.faces,
  15884. faces2 = geometry2.faces,
  15885. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15886. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15887. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15888. if ( object2 instanceof THREE.Mesh ) {
  15889. object2.matrixAutoUpdate && object2.updateMatrix();
  15890. matrix = object2.matrix;
  15891. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15892. }
  15893. // vertices
  15894. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15895. var vertex = vertices2[ i ];
  15896. var vertexCopy = vertex.clone();
  15897. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15898. vertices1.push( vertexCopy );
  15899. }
  15900. // faces
  15901. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15902. var face = faces2[ i ], faceCopy, normal, color,
  15903. faceVertexNormals = face.vertexNormals,
  15904. faceVertexColors = face.vertexColors;
  15905. if ( face instanceof THREE.Face3 ) {
  15906. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15907. } else if ( face instanceof THREE.Face4 ) {
  15908. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15909. }
  15910. faceCopy.normal.copy( face.normal );
  15911. if ( normalMatrix ) {
  15912. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15913. }
  15914. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15915. normal = faceVertexNormals[ j ].clone();
  15916. if ( normalMatrix ) {
  15917. normal.applyMatrix3( normalMatrix ).normalize();
  15918. }
  15919. faceCopy.vertexNormals.push( normal );
  15920. }
  15921. faceCopy.color.copy( face.color );
  15922. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15923. color = faceVertexColors[ j ];
  15924. faceCopy.vertexColors.push( color.clone() );
  15925. }
  15926. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15927. faceCopy.centroid.copy( face.centroid );
  15928. if ( matrix ) {
  15929. faceCopy.centroid.applyMatrix4( matrix );
  15930. }
  15931. faces1.push( faceCopy );
  15932. }
  15933. // uvs
  15934. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15935. var uv = uvs2[ i ], uvCopy = [];
  15936. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15937. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15938. }
  15939. uvs1.push( uvCopy );
  15940. }
  15941. },
  15942. removeMaterials: function ( geometry, materialIndexArray ) {
  15943. var materialIndexMap = {};
  15944. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15945. materialIndexMap[ materialIndexArray[i] ] = true;
  15946. }
  15947. var face, newFaces = [];
  15948. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15949. face = geometry.faces[ i ];
  15950. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15951. }
  15952. geometry.faces = newFaces;
  15953. },
  15954. // Get random point in triangle (via barycentric coordinates)
  15955. // (uniform distribution)
  15956. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15957. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15958. var a, b, c,
  15959. point = new THREE.Vector3(),
  15960. tmp = THREE.GeometryUtils.__v1;
  15961. a = THREE.GeometryUtils.random();
  15962. b = THREE.GeometryUtils.random();
  15963. if ( ( a + b ) > 1 ) {
  15964. a = 1 - a;
  15965. b = 1 - b;
  15966. }
  15967. c = 1 - a - b;
  15968. point.copy( vectorA );
  15969. point.multiplyScalar( a );
  15970. tmp.copy( vectorB );
  15971. tmp.multiplyScalar( b );
  15972. point.add( tmp );
  15973. tmp.copy( vectorC );
  15974. tmp.multiplyScalar( c );
  15975. point.add( tmp );
  15976. return point;
  15977. },
  15978. // Get random point in face (triangle / quad)
  15979. // (uniform distribution)
  15980. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15981. var vA, vB, vC, vD;
  15982. if ( face instanceof THREE.Face3 ) {
  15983. vA = geometry.vertices[ face.a ];
  15984. vB = geometry.vertices[ face.b ];
  15985. vC = geometry.vertices[ face.c ];
  15986. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15987. } else if ( face instanceof THREE.Face4 ) {
  15988. vA = geometry.vertices[ face.a ];
  15989. vB = geometry.vertices[ face.b ];
  15990. vC = geometry.vertices[ face.c ];
  15991. vD = geometry.vertices[ face.d ];
  15992. var area1, area2;
  15993. if ( useCachedAreas ) {
  15994. if ( face._area1 && face._area2 ) {
  15995. area1 = face._area1;
  15996. area2 = face._area2;
  15997. } else {
  15998. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15999. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16000. face._area1 = area1;
  16001. face._area2 = area2;
  16002. }
  16003. } else {
  16004. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  16005. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16006. }
  16007. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  16008. if ( r < area1 ) {
  16009. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  16010. } else {
  16011. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  16012. }
  16013. }
  16014. },
  16015. // Get uniformly distributed random points in mesh
  16016. // - create array with cumulative sums of face areas
  16017. // - pick random number from 0 to total area
  16018. // - find corresponding place in area array by binary search
  16019. // - get random point in face
  16020. randomPointsInGeometry: function ( geometry, n ) {
  16021. var face, i,
  16022. faces = geometry.faces,
  16023. vertices = geometry.vertices,
  16024. il = faces.length,
  16025. totalArea = 0,
  16026. cumulativeAreas = [],
  16027. vA, vB, vC, vD;
  16028. // precompute face areas
  16029. for ( i = 0; i < il; i ++ ) {
  16030. face = faces[ i ];
  16031. if ( face instanceof THREE.Face3 ) {
  16032. vA = vertices[ face.a ];
  16033. vB = vertices[ face.b ];
  16034. vC = vertices[ face.c ];
  16035. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16036. } else if ( face instanceof THREE.Face4 ) {
  16037. vA = vertices[ face.a ];
  16038. vB = vertices[ face.b ];
  16039. vC = vertices[ face.c ];
  16040. vD = vertices[ face.d ];
  16041. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  16042. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16043. face._area = face._area1 + face._area2;
  16044. }
  16045. totalArea += face._area;
  16046. cumulativeAreas[ i ] = totalArea;
  16047. }
  16048. // binary search cumulative areas array
  16049. function binarySearchIndices( value ) {
  16050. function binarySearch( start, end ) {
  16051. // return closest larger index
  16052. // if exact number is not found
  16053. if ( end < start )
  16054. return start;
  16055. var mid = start + Math.floor( ( end - start ) / 2 );
  16056. if ( cumulativeAreas[ mid ] > value ) {
  16057. return binarySearch( start, mid - 1 );
  16058. } else if ( cumulativeAreas[ mid ] < value ) {
  16059. return binarySearch( mid + 1, end );
  16060. } else {
  16061. return mid;
  16062. }
  16063. }
  16064. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16065. return result;
  16066. }
  16067. // pick random face weighted by face area
  16068. var r, index,
  16069. result = [];
  16070. var stats = {};
  16071. for ( i = 0; i < n; i ++ ) {
  16072. r = THREE.GeometryUtils.random() * totalArea;
  16073. index = binarySearchIndices( r );
  16074. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16075. if ( ! stats[ index ] ) {
  16076. stats[ index ] = 1;
  16077. } else {
  16078. stats[ index ] += 1;
  16079. }
  16080. }
  16081. return result;
  16082. },
  16083. // Get triangle area (half of parallelogram)
  16084. // http://mathworld.wolfram.com/TriangleArea.html
  16085. triangleArea: function ( vectorA, vectorB, vectorC ) {
  16086. var tmp1 = THREE.GeometryUtils.__v1,
  16087. tmp2 = THREE.GeometryUtils.__v2;
  16088. tmp1.subVectors( vectorB, vectorA );
  16089. tmp2.subVectors( vectorC, vectorA );
  16090. tmp1.cross( tmp2 );
  16091. return 0.5 * tmp1.length();
  16092. },
  16093. // Center geometry so that 0,0,0 is in center of bounding box
  16094. center: function ( geometry ) {
  16095. geometry.computeBoundingBox();
  16096. var bb = geometry.boundingBox;
  16097. var offset = new THREE.Vector3();
  16098. offset.addVectors( bb.min, bb.max );
  16099. offset.multiplyScalar( -0.5 );
  16100. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16101. geometry.computeBoundingBox();
  16102. return offset;
  16103. },
  16104. // Normalize UVs to be from <0,1>
  16105. // (for now just the first set of UVs)
  16106. normalizeUVs: function ( geometry ) {
  16107. var uvSet = geometry.faceVertexUvs[ 0 ];
  16108. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  16109. var uvs = uvSet[ i ];
  16110. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  16111. // texture repeat
  16112. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  16113. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  16114. }
  16115. }
  16116. },
  16117. triangulateQuads: function ( geometry ) {
  16118. var i, il, j, jl;
  16119. var faces = [];
  16120. var faceUvs = [];
  16121. var faceVertexUvs = [];
  16122. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  16123. faceUvs[ i ] = [];
  16124. }
  16125. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  16126. faceVertexUvs[ i ] = [];
  16127. }
  16128. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16129. var face = geometry.faces[ i ];
  16130. if ( face instanceof THREE.Face4 ) {
  16131. var a = face.a;
  16132. var b = face.b;
  16133. var c = face.c;
  16134. var d = face.d;
  16135. var triA = new THREE.Face3();
  16136. var triB = new THREE.Face3();
  16137. triA.color.copy( face.color );
  16138. triB.color.copy( face.color );
  16139. triA.materialIndex = face.materialIndex;
  16140. triB.materialIndex = face.materialIndex;
  16141. triA.a = a;
  16142. triA.b = b;
  16143. triA.c = d;
  16144. triB.a = b;
  16145. triB.b = c;
  16146. triB.c = d;
  16147. if ( face.vertexColors.length === 4 ) {
  16148. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  16149. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  16150. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16151. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  16152. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  16153. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16154. }
  16155. faces.push( triA, triB );
  16156. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16157. if ( geometry.faceVertexUvs[ j ].length ) {
  16158. var uvs = geometry.faceVertexUvs[ j ][ i ];
  16159. var uvA = uvs[ 0 ];
  16160. var uvB = uvs[ 1 ];
  16161. var uvC = uvs[ 2 ];
  16162. var uvD = uvs[ 3 ];
  16163. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  16164. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  16165. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  16166. }
  16167. }
  16168. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16169. if ( geometry.faceUvs[ j ].length ) {
  16170. var faceUv = geometry.faceUvs[ j ][ i ];
  16171. faceUvs[ j ].push( faceUv, faceUv );
  16172. }
  16173. }
  16174. } else {
  16175. faces.push( face );
  16176. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16177. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  16178. }
  16179. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16180. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  16181. }
  16182. }
  16183. }
  16184. geometry.faces = faces;
  16185. geometry.faceUvs = faceUvs;
  16186. geometry.faceVertexUvs = faceVertexUvs;
  16187. geometry.computeCentroids();
  16188. geometry.computeFaceNormals();
  16189. geometry.computeVertexNormals();
  16190. if ( geometry.hasTangents ) geometry.computeTangents();
  16191. },
  16192. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  16193. var faces = geometry.faces;
  16194. var start = startFace || 0;
  16195. var end = endFace || faces.length - 1;
  16196. for ( var i = start; i <= end; i ++ ) {
  16197. faces[i].materialIndex = index;
  16198. }
  16199. }
  16200. };
  16201. THREE.GeometryUtils.random = THREE.Math.random16;
  16202. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  16203. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  16204. /**
  16205. * @author alteredq / http://alteredqualia.com/
  16206. * @author mrdoob / http://mrdoob.com/
  16207. */
  16208. THREE.ImageUtils = {
  16209. crossOrigin: 'anonymous',
  16210. loadTexture: function ( url, mapping, onLoad, onError ) {
  16211. var image = new Image();
  16212. var texture = new THREE.Texture( image, mapping );
  16213. var loader = new THREE.ImageLoader();
  16214. loader.crossOrigin = this.crossOrigin;
  16215. loader.load( url, function ( image ) {
  16216. texture.image = image;
  16217. texture.needsUpdate = true;
  16218. if ( onLoad ) onLoad( texture );
  16219. } );
  16220. texture.sourceFile = url;
  16221. return texture;
  16222. },
  16223. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16224. var texture = new THREE.CompressedTexture();
  16225. texture.mapping = mapping;
  16226. var request = new XMLHttpRequest();
  16227. request.onload = function () {
  16228. var buffer = request.response;
  16229. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16230. texture.format = dds.format;
  16231. texture.mipmaps = dds.mipmaps;
  16232. texture.image.width = dds.width;
  16233. texture.image.height = dds.height;
  16234. // gl.generateMipmap fails for compressed textures
  16235. // mipmaps must be embedded in the DDS file
  16236. // or texture filters must not use mipmapping
  16237. texture.generateMipmaps = false;
  16238. texture.needsUpdate = true;
  16239. if ( onLoad ) onLoad( texture );
  16240. }
  16241. request.onerror = onError;
  16242. request.open( 'GET', url, true );
  16243. request.responseType = "arraybuffer";
  16244. request.send( null );
  16245. return texture;
  16246. },
  16247. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16248. var images = [];
  16249. images.loadCount = 0;
  16250. var texture = new THREE.Texture();
  16251. texture.image = images;
  16252. if ( mapping !== undefined ) texture.mapping = mapping;
  16253. // no flipping needed for cube textures
  16254. texture.flipY = false;
  16255. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16256. var cubeImage = new Image();
  16257. images[ i ] = cubeImage;
  16258. cubeImage.onload = function () {
  16259. images.loadCount += 1;
  16260. if ( images.loadCount === 6 ) {
  16261. texture.needsUpdate = true;
  16262. if ( onLoad ) onLoad( texture );
  16263. }
  16264. };
  16265. cubeImage.onerror = onError;
  16266. cubeImage.crossOrigin = this.crossOrigin;
  16267. cubeImage.src = array[ i ];
  16268. }
  16269. return texture;
  16270. },
  16271. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16272. var images = [];
  16273. images.loadCount = 0;
  16274. var texture = new THREE.CompressedTexture();
  16275. texture.image = images;
  16276. if ( mapping !== undefined ) texture.mapping = mapping;
  16277. // no flipping for cube textures
  16278. // (also flipping doesn't work for compressed textures )
  16279. texture.flipY = false;
  16280. // can't generate mipmaps for compressed textures
  16281. // mips must be embedded in DDS files
  16282. texture.generateMipmaps = false;
  16283. var generateCubeFaceCallback = function ( rq, img ) {
  16284. return function () {
  16285. var buffer = rq.response;
  16286. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16287. img.format = dds.format;
  16288. img.mipmaps = dds.mipmaps;
  16289. img.width = dds.width;
  16290. img.height = dds.height;
  16291. images.loadCount += 1;
  16292. if ( images.loadCount === 6 ) {
  16293. texture.format = dds.format;
  16294. texture.needsUpdate = true;
  16295. if ( onLoad ) onLoad( texture );
  16296. }
  16297. }
  16298. }
  16299. // compressed cubemap textures as 6 separate DDS files
  16300. if ( array instanceof Array ) {
  16301. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16302. var cubeImage = {};
  16303. images[ i ] = cubeImage;
  16304. var request = new XMLHttpRequest();
  16305. request.onload = generateCubeFaceCallback( request, cubeImage );
  16306. request.onerror = onError;
  16307. var url = array[ i ];
  16308. request.open( 'GET', url, true );
  16309. request.responseType = "arraybuffer";
  16310. request.send( null );
  16311. }
  16312. // compressed cubemap texture stored in a single DDS file
  16313. } else {
  16314. var url = array;
  16315. var request = new XMLHttpRequest();
  16316. request.onload = function( ) {
  16317. var buffer = request.response;
  16318. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16319. if ( dds.isCubemap ) {
  16320. var faces = dds.mipmaps.length / dds.mipmapCount;
  16321. for ( var f = 0; f < faces; f ++ ) {
  16322. images[ f ] = { mipmaps : [] };
  16323. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16324. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16325. images[ f ].format = dds.format;
  16326. images[ f ].width = dds.width;
  16327. images[ f ].height = dds.height;
  16328. }
  16329. }
  16330. texture.format = dds.format;
  16331. texture.needsUpdate = true;
  16332. if ( onLoad ) onLoad( texture );
  16333. }
  16334. }
  16335. request.onerror = onError;
  16336. request.open( 'GET', url, true );
  16337. request.responseType = "arraybuffer";
  16338. request.send( null );
  16339. }
  16340. return texture;
  16341. },
  16342. parseDDS: function ( buffer, loadMipmaps ) {
  16343. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16344. // Adapted from @toji's DDS utils
  16345. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16346. // All values and structures referenced from:
  16347. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16348. var DDS_MAGIC = 0x20534444;
  16349. var DDSD_CAPS = 0x1,
  16350. DDSD_HEIGHT = 0x2,
  16351. DDSD_WIDTH = 0x4,
  16352. DDSD_PITCH = 0x8,
  16353. DDSD_PIXELFORMAT = 0x1000,
  16354. DDSD_MIPMAPCOUNT = 0x20000,
  16355. DDSD_LINEARSIZE = 0x80000,
  16356. DDSD_DEPTH = 0x800000;
  16357. var DDSCAPS_COMPLEX = 0x8,
  16358. DDSCAPS_MIPMAP = 0x400000,
  16359. DDSCAPS_TEXTURE = 0x1000;
  16360. var DDSCAPS2_CUBEMAP = 0x200,
  16361. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16362. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16363. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16364. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16365. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16366. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16367. DDSCAPS2_VOLUME = 0x200000;
  16368. var DDPF_ALPHAPIXELS = 0x1,
  16369. DDPF_ALPHA = 0x2,
  16370. DDPF_FOURCC = 0x4,
  16371. DDPF_RGB = 0x40,
  16372. DDPF_YUV = 0x200,
  16373. DDPF_LUMINANCE = 0x20000;
  16374. function fourCCToInt32( value ) {
  16375. return value.charCodeAt(0) +
  16376. (value.charCodeAt(1) << 8) +
  16377. (value.charCodeAt(2) << 16) +
  16378. (value.charCodeAt(3) << 24);
  16379. }
  16380. function int32ToFourCC( value ) {
  16381. return String.fromCharCode(
  16382. value & 0xff,
  16383. (value >> 8) & 0xff,
  16384. (value >> 16) & 0xff,
  16385. (value >> 24) & 0xff
  16386. );
  16387. }
  16388. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16389. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16390. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16391. var headerLengthInt = 31; // The header length in 32 bit ints
  16392. // Offsets into the header array
  16393. var off_magic = 0;
  16394. var off_size = 1;
  16395. var off_flags = 2;
  16396. var off_height = 3;
  16397. var off_width = 4;
  16398. var off_mipmapCount = 7;
  16399. var off_pfFlags = 20;
  16400. var off_pfFourCC = 21;
  16401. var off_caps = 27;
  16402. var off_caps2 = 28;
  16403. var off_caps3 = 29;
  16404. var off_caps4 = 30;
  16405. // Parse header
  16406. var header = new Int32Array( buffer, 0, headerLengthInt );
  16407. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16408. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16409. return dds;
  16410. }
  16411. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16412. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16413. return dds;
  16414. }
  16415. var blockBytes;
  16416. var fourCC = header[ off_pfFourCC ];
  16417. switch ( fourCC ) {
  16418. case FOURCC_DXT1:
  16419. blockBytes = 8;
  16420. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16421. break;
  16422. case FOURCC_DXT3:
  16423. blockBytes = 16;
  16424. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16425. break;
  16426. case FOURCC_DXT5:
  16427. blockBytes = 16;
  16428. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16429. break;
  16430. default:
  16431. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16432. return dds;
  16433. }
  16434. dds.mipmapCount = 1;
  16435. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16436. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16437. }
  16438. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16439. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16440. dds.width = header[ off_width ];
  16441. dds.height = header[ off_height ];
  16442. var dataOffset = header[ off_size ] + 4;
  16443. // Extract mipmaps buffers
  16444. var width = dds.width;
  16445. var height = dds.height;
  16446. var faces = dds.isCubemap ? 6 : 1;
  16447. for ( var face = 0; face < faces; face ++ ) {
  16448. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16449. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16450. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16451. var mipmap = { "data": byteArray, "width": width, "height": height };
  16452. dds.mipmaps.push( mipmap );
  16453. dataOffset += dataLength;
  16454. width = Math.max( width * 0.5, 1 );
  16455. height = Math.max( height * 0.5, 1 );
  16456. }
  16457. width = dds.width;
  16458. height = dds.height;
  16459. }
  16460. return dds;
  16461. },
  16462. getNormalMap: function ( image, depth ) {
  16463. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16464. var cross = function ( a, b ) {
  16465. 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 ] ];
  16466. }
  16467. var subtract = function ( a, b ) {
  16468. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16469. }
  16470. var normalize = function ( a ) {
  16471. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16472. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16473. }
  16474. depth = depth | 1;
  16475. var width = image.width;
  16476. var height = image.height;
  16477. var canvas = document.createElement( 'canvas' );
  16478. canvas.width = width;
  16479. canvas.height = height;
  16480. var context = canvas.getContext( '2d' );
  16481. context.drawImage( image, 0, 0 );
  16482. var data = context.getImageData( 0, 0, width, height ).data;
  16483. var imageData = context.createImageData( width, height );
  16484. var output = imageData.data;
  16485. for ( var x = 0; x < width; x ++ ) {
  16486. for ( var y = 0; y < height; y ++ ) {
  16487. var ly = y - 1 < 0 ? 0 : y - 1;
  16488. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16489. var lx = x - 1 < 0 ? 0 : x - 1;
  16490. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16491. var points = [];
  16492. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16493. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16494. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16495. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16496. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16497. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16498. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16499. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16500. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16501. var normals = [];
  16502. var num_points = points.length;
  16503. for ( var i = 0; i < num_points; i ++ ) {
  16504. var v1 = points[ i ];
  16505. var v2 = points[ ( i + 1 ) % num_points ];
  16506. v1 = subtract( v1, origin );
  16507. v2 = subtract( v2, origin );
  16508. normals.push( normalize( cross( v1, v2 ) ) );
  16509. }
  16510. var normal = [ 0, 0, 0 ];
  16511. for ( var i = 0; i < normals.length; i ++ ) {
  16512. normal[ 0 ] += normals[ i ][ 0 ];
  16513. normal[ 1 ] += normals[ i ][ 1 ];
  16514. normal[ 2 ] += normals[ i ][ 2 ];
  16515. }
  16516. normal[ 0 ] /= normals.length;
  16517. normal[ 1 ] /= normals.length;
  16518. normal[ 2 ] /= normals.length;
  16519. var idx = ( y * width + x ) * 4;
  16520. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16521. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16522. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16523. output[ idx + 3 ] = 255;
  16524. }
  16525. }
  16526. context.putImageData( imageData, 0, 0 );
  16527. return canvas;
  16528. },
  16529. generateDataTexture: function ( width, height, color ) {
  16530. var size = width * height;
  16531. var data = new Uint8Array( 3 * size );
  16532. var r = Math.floor( color.r * 255 );
  16533. var g = Math.floor( color.g * 255 );
  16534. var b = Math.floor( color.b * 255 );
  16535. for ( var i = 0; i < size; i ++ ) {
  16536. data[ i * 3 ] = r;
  16537. data[ i * 3 + 1 ] = g;
  16538. data[ i * 3 + 2 ] = b;
  16539. }
  16540. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16541. texture.needsUpdate = true;
  16542. return texture;
  16543. }
  16544. };
  16545. /**
  16546. * @author alteredq / http://alteredqualia.com/
  16547. */
  16548. THREE.SceneUtils = {
  16549. createMultiMaterialObject: function ( geometry, materials ) {
  16550. var group = new THREE.Object3D();
  16551. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16552. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16553. }
  16554. return group;
  16555. },
  16556. detach : function ( child, parent, scene ) {
  16557. child.applyMatrix( parent.matrixWorld );
  16558. parent.remove( child );
  16559. scene.add( child );
  16560. },
  16561. attach: function ( child, scene, parent ) {
  16562. var matrixWorldInverse = new THREE.Matrix4();
  16563. matrixWorldInverse.getInverse( parent.matrixWorld );
  16564. child.applyMatrix( matrixWorldInverse );
  16565. scene.remove( child );
  16566. parent.add( child );
  16567. }
  16568. };
  16569. /**
  16570. * @author zz85 / http://www.lab4games.net/zz85/blog
  16571. * @author alteredq / http://alteredqualia.com/
  16572. *
  16573. * For Text operations in three.js (See TextGeometry)
  16574. *
  16575. * It uses techniques used in:
  16576. *
  16577. * typeface.js and canvastext
  16578. * For converting fonts and rendering with javascript
  16579. * http://typeface.neocracy.org
  16580. *
  16581. * Triangulation ported from AS3
  16582. * Simple Polygon Triangulation
  16583. * http://actionsnippet.com/?p=1462
  16584. *
  16585. * A Method to triangulate shapes with holes
  16586. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16587. *
  16588. */
  16589. THREE.FontUtils = {
  16590. faces : {},
  16591. // Just for now. face[weight][style]
  16592. face : "helvetiker",
  16593. weight: "normal",
  16594. style : "normal",
  16595. size : 150,
  16596. divisions : 10,
  16597. getFace : function() {
  16598. return this.faces[ this.face ][ this.weight ][ this.style ];
  16599. },
  16600. loadFace : function( data ) {
  16601. var family = data.familyName.toLowerCase();
  16602. var ThreeFont = this;
  16603. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16604. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16605. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16606. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16607. return data;
  16608. },
  16609. drawText : function( text ) {
  16610. var characterPts = [], allPts = [];
  16611. // RenderText
  16612. var i, p,
  16613. face = this.getFace(),
  16614. scale = this.size / face.resolution,
  16615. offset = 0,
  16616. chars = String( text ).split( '' ),
  16617. length = chars.length;
  16618. var fontPaths = [];
  16619. for ( i = 0; i < length; i ++ ) {
  16620. var path = new THREE.Path();
  16621. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16622. offset += ret.offset;
  16623. fontPaths.push( ret.path );
  16624. }
  16625. // get the width
  16626. var width = offset / 2;
  16627. //
  16628. // for ( p = 0; p < allPts.length; p++ ) {
  16629. //
  16630. // allPts[ p ].x -= width;
  16631. //
  16632. // }
  16633. //var extract = this.extractPoints( allPts, characterPts );
  16634. //extract.contour = allPts;
  16635. //extract.paths = fontPaths;
  16636. //extract.offset = width;
  16637. return { paths : fontPaths, offset : width };
  16638. },
  16639. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16640. var pts = [];
  16641. var i, i2, divisions,
  16642. outline, action, length,
  16643. scaleX, scaleY,
  16644. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16645. laste,
  16646. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16647. if ( !glyph ) return;
  16648. if ( glyph.o ) {
  16649. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16650. length = outline.length;
  16651. scaleX = scale;
  16652. scaleY = scale;
  16653. for ( i = 0; i < length; ) {
  16654. action = outline[ i ++ ];
  16655. //console.log( action );
  16656. switch( action ) {
  16657. case 'm':
  16658. // Move To
  16659. x = outline[ i++ ] * scaleX + offset;
  16660. y = outline[ i++ ] * scaleY;
  16661. path.moveTo( x, y );
  16662. break;
  16663. case 'l':
  16664. // Line To
  16665. x = outline[ i++ ] * scaleX + offset;
  16666. y = outline[ i++ ] * scaleY;
  16667. path.lineTo(x,y);
  16668. break;
  16669. case 'q':
  16670. // QuadraticCurveTo
  16671. cpx = outline[ i++ ] * scaleX + offset;
  16672. cpy = outline[ i++ ] * scaleY;
  16673. cpx1 = outline[ i++ ] * scaleX + offset;
  16674. cpy1 = outline[ i++ ] * scaleY;
  16675. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16676. laste = pts[ pts.length - 1 ];
  16677. if ( laste ) {
  16678. cpx0 = laste.x;
  16679. cpy0 = laste.y;
  16680. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16681. var t = i2 / divisions;
  16682. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16683. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16684. }
  16685. }
  16686. break;
  16687. case 'b':
  16688. // Cubic Bezier Curve
  16689. cpx = outline[ i++ ] * scaleX + offset;
  16690. cpy = outline[ i++ ] * scaleY;
  16691. cpx1 = outline[ i++ ] * scaleX + offset;
  16692. cpy1 = outline[ i++ ] * -scaleY;
  16693. cpx2 = outline[ i++ ] * scaleX + offset;
  16694. cpy2 = outline[ i++ ] * -scaleY;
  16695. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16696. laste = pts[ pts.length - 1 ];
  16697. if ( laste ) {
  16698. cpx0 = laste.x;
  16699. cpy0 = laste.y;
  16700. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16701. var t = i2 / divisions;
  16702. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16703. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16704. }
  16705. }
  16706. break;
  16707. }
  16708. }
  16709. }
  16710. return { offset: glyph.ha*scale, path:path};
  16711. }
  16712. };
  16713. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16714. // Parameters
  16715. parameters = parameters || {};
  16716. var size = parameters.size !== undefined ? parameters.size : 100;
  16717. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16718. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16719. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16720. var style = parameters.style !== undefined ? parameters.style : "normal";
  16721. THREE.FontUtils.size = size;
  16722. THREE.FontUtils.divisions = curveSegments;
  16723. THREE.FontUtils.face = font;
  16724. THREE.FontUtils.weight = weight;
  16725. THREE.FontUtils.style = style;
  16726. // Get a Font data json object
  16727. var data = THREE.FontUtils.drawText( text );
  16728. var paths = data.paths;
  16729. var shapes = [];
  16730. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16731. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16732. }
  16733. return shapes;
  16734. };
  16735. /**
  16736. * This code is a quick port of code written in C++ which was submitted to
  16737. * flipcode.com by John W. Ratcliff // July 22, 2000
  16738. * See original code and more information here:
  16739. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16740. *
  16741. * ported to actionscript by Zevan Rosser
  16742. * www.actionsnippet.com
  16743. *
  16744. * ported to javascript by Joshua Koo
  16745. * http://www.lab4games.net/zz85/blog
  16746. *
  16747. */
  16748. ( function( namespace ) {
  16749. var EPSILON = 0.0000000001;
  16750. // takes in an contour array and returns
  16751. var process = function( contour, indices ) {
  16752. var n = contour.length;
  16753. if ( n < 3 ) return null;
  16754. var result = [],
  16755. verts = [],
  16756. vertIndices = [];
  16757. /* we want a counter-clockwise polygon in verts */
  16758. var u, v, w;
  16759. if ( area( contour ) > 0.0 ) {
  16760. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16761. } else {
  16762. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16763. }
  16764. var nv = n;
  16765. /* remove nv - 2 vertices, creating 1 triangle every time */
  16766. var count = 2 * nv; /* error detection */
  16767. for( v = nv - 1; nv > 2; ) {
  16768. /* if we loop, it is probably a non-simple polygon */
  16769. if ( ( count-- ) <= 0 ) {
  16770. //** Triangulate: ERROR - probable bad polygon!
  16771. //throw ( "Warning, unable to triangulate polygon!" );
  16772. //return null;
  16773. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16774. console.log( "Warning, unable to triangulate polygon!" );
  16775. if ( indices ) return vertIndices;
  16776. return result;
  16777. }
  16778. /* three consecutive vertices in current polygon, <u,v,w> */
  16779. u = v; if ( nv <= u ) u = 0; /* previous */
  16780. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16781. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16782. if ( snip( contour, u, v, w, nv, verts ) ) {
  16783. var a, b, c, s, t;
  16784. /* true names of the vertices */
  16785. a = verts[ u ];
  16786. b = verts[ v ];
  16787. c = verts[ w ];
  16788. /* output Triangle */
  16789. result.push( [ contour[ a ],
  16790. contour[ b ],
  16791. contour[ c ] ] );
  16792. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16793. /* remove v from the remaining polygon */
  16794. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16795. verts[ s ] = verts[ t ];
  16796. }
  16797. nv--;
  16798. /* reset error detection counter */
  16799. count = 2 * nv;
  16800. }
  16801. }
  16802. if ( indices ) return vertIndices;
  16803. return result;
  16804. };
  16805. // calculate area of the contour polygon
  16806. var area = function ( contour ) {
  16807. var n = contour.length;
  16808. var a = 0.0;
  16809. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16810. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16811. }
  16812. return a * 0.5;
  16813. };
  16814. var snip = function ( contour, u, v, w, n, verts ) {
  16815. var p;
  16816. var ax, ay, bx, by;
  16817. var cx, cy, px, py;
  16818. ax = contour[ verts[ u ] ].x;
  16819. ay = contour[ verts[ u ] ].y;
  16820. bx = contour[ verts[ v ] ].x;
  16821. by = contour[ verts[ v ] ].y;
  16822. cx = contour[ verts[ w ] ].x;
  16823. cy = contour[ verts[ w ] ].y;
  16824. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16825. var aX, aY, bX, bY, cX, cY;
  16826. var apx, apy, bpx, bpy, cpx, cpy;
  16827. var cCROSSap, bCROSScp, aCROSSbp;
  16828. aX = cx - bx; aY = cy - by;
  16829. bX = ax - cx; bY = ay - cy;
  16830. cX = bx - ax; cY = by - ay;
  16831. for ( p = 0; p < n; p++ ) {
  16832. if( (p === u) || (p === v) || (p === w) ) continue;
  16833. px = contour[ verts[ p ] ].x
  16834. py = contour[ verts[ p ] ].y
  16835. apx = px - ax; apy = py - ay;
  16836. bpx = px - bx; bpy = py - by;
  16837. cpx = px - cx; cpy = py - cy;
  16838. // see if p is inside triangle abc
  16839. aCROSSbp = aX*bpy - aY*bpx;
  16840. cCROSSap = cX*apy - cY*apx;
  16841. bCROSScp = bX*cpy - bY*cpx;
  16842. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16843. }
  16844. return true;
  16845. };
  16846. namespace.Triangulate = process;
  16847. namespace.Triangulate.area = area;
  16848. return namespace;
  16849. })(THREE.FontUtils);
  16850. // To use the typeface.js face files, hook up the API
  16851. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16852. THREE.typeface_js = self._typeface_js;
  16853. /**
  16854. * @author zz85 / http://www.lab4games.net/zz85/blog
  16855. * Extensible curve object
  16856. *
  16857. * Some common of Curve methods
  16858. * .getPoint(t), getTangent(t)
  16859. * .getPointAt(u), getTagentAt(u)
  16860. * .getPoints(), .getSpacedPoints()
  16861. * .getLength()
  16862. * .updateArcLengths()
  16863. *
  16864. * This following classes subclasses THREE.Curve:
  16865. *
  16866. * -- 2d classes --
  16867. * THREE.LineCurve
  16868. * THREE.QuadraticBezierCurve
  16869. * THREE.CubicBezierCurve
  16870. * THREE.SplineCurve
  16871. * THREE.ArcCurve
  16872. * THREE.EllipseCurve
  16873. *
  16874. * -- 3d classes --
  16875. * THREE.LineCurve3
  16876. * THREE.QuadraticBezierCurve3
  16877. * THREE.CubicBezierCurve3
  16878. * THREE.SplineCurve3
  16879. * THREE.ClosedSplineCurve3
  16880. *
  16881. * A series of curves can be represented as a THREE.CurvePath
  16882. *
  16883. **/
  16884. /**************************************************************
  16885. * Abstract Curve base class
  16886. **************************************************************/
  16887. THREE.Curve = function () {
  16888. };
  16889. // Virtual base class method to overwrite and implement in subclasses
  16890. // - t [0 .. 1]
  16891. THREE.Curve.prototype.getPoint = function ( t ) {
  16892. console.log( "Warning, getPoint() not implemented!" );
  16893. return null;
  16894. };
  16895. // Get point at relative position in curve according to arc length
  16896. // - u [0 .. 1]
  16897. THREE.Curve.prototype.getPointAt = function ( u ) {
  16898. var t = this.getUtoTmapping( u );
  16899. return this.getPoint( t );
  16900. };
  16901. // Get sequence of points using getPoint( t )
  16902. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16903. if ( !divisions ) divisions = 5;
  16904. var d, pts = [];
  16905. for ( d = 0; d <= divisions; d ++ ) {
  16906. pts.push( this.getPoint( d / divisions ) );
  16907. }
  16908. return pts;
  16909. };
  16910. // Get sequence of points using getPointAt( u )
  16911. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16912. if ( !divisions ) divisions = 5;
  16913. var d, pts = [];
  16914. for ( d = 0; d <= divisions; d ++ ) {
  16915. pts.push( this.getPointAt( d / divisions ) );
  16916. }
  16917. return pts;
  16918. };
  16919. // Get total curve arc length
  16920. THREE.Curve.prototype.getLength = function () {
  16921. var lengths = this.getLengths();
  16922. return lengths[ lengths.length - 1 ];
  16923. };
  16924. // Get list of cumulative segment lengths
  16925. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16926. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16927. if ( this.cacheArcLengths
  16928. && ( this.cacheArcLengths.length == divisions + 1 )
  16929. && !this.needsUpdate) {
  16930. //console.log( "cached", this.cacheArcLengths );
  16931. return this.cacheArcLengths;
  16932. }
  16933. this.needsUpdate = false;
  16934. var cache = [];
  16935. var current, last = this.getPoint( 0 );
  16936. var p, sum = 0;
  16937. cache.push( 0 );
  16938. for ( p = 1; p <= divisions; p ++ ) {
  16939. current = this.getPoint ( p / divisions );
  16940. sum += current.distanceTo( last );
  16941. cache.push( sum );
  16942. last = current;
  16943. }
  16944. this.cacheArcLengths = cache;
  16945. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16946. };
  16947. THREE.Curve.prototype.updateArcLengths = function() {
  16948. this.needsUpdate = true;
  16949. this.getLengths();
  16950. };
  16951. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16952. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16953. var arcLengths = this.getLengths();
  16954. var i = 0, il = arcLengths.length;
  16955. var targetArcLength; // The targeted u distance value to get
  16956. if ( distance ) {
  16957. targetArcLength = distance;
  16958. } else {
  16959. targetArcLength = u * arcLengths[ il - 1 ];
  16960. }
  16961. //var time = Date.now();
  16962. // binary search for the index with largest value smaller than target u distance
  16963. var low = 0, high = il - 1, comparison;
  16964. while ( low <= high ) {
  16965. 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
  16966. comparison = arcLengths[ i ] - targetArcLength;
  16967. if ( comparison < 0 ) {
  16968. low = i + 1;
  16969. continue;
  16970. } else if ( comparison > 0 ) {
  16971. high = i - 1;
  16972. continue;
  16973. } else {
  16974. high = i;
  16975. break;
  16976. // DONE
  16977. }
  16978. }
  16979. i = high;
  16980. //console.log('b' , i, low, high, Date.now()- time);
  16981. if ( arcLengths[ i ] == targetArcLength ) {
  16982. var t = i / ( il - 1 );
  16983. return t;
  16984. }
  16985. // we could get finer grain at lengths, or use simple interpolatation between two points
  16986. var lengthBefore = arcLengths[ i ];
  16987. var lengthAfter = arcLengths[ i + 1 ];
  16988. var segmentLength = lengthAfter - lengthBefore;
  16989. // determine where we are between the 'before' and 'after' points
  16990. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16991. // add that fractional amount to t
  16992. var t = ( i + segmentFraction ) / ( il -1 );
  16993. return t;
  16994. };
  16995. // Returns a unit vector tangent at t
  16996. // In case any sub curve does not implement its tangent derivation,
  16997. // 2 points a small delta apart will be used to find its gradient
  16998. // which seems to give a reasonable approximation
  16999. THREE.Curve.prototype.getTangent = function( t ) {
  17000. var delta = 0.0001;
  17001. var t1 = t - delta;
  17002. var t2 = t + delta;
  17003. // Capping in case of danger
  17004. if ( t1 < 0 ) t1 = 0;
  17005. if ( t2 > 1 ) t2 = 1;
  17006. var pt1 = this.getPoint( t1 );
  17007. var pt2 = this.getPoint( t2 );
  17008. var vec = pt2.clone().sub(pt1);
  17009. return vec.normalize();
  17010. };
  17011. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17012. var t = this.getUtoTmapping( u );
  17013. return this.getTangent( t );
  17014. };
  17015. /**************************************************************
  17016. * Utils
  17017. **************************************************************/
  17018. THREE.Curve.Utils = {
  17019. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17020. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17021. },
  17022. // Puay Bing, thanks for helping with this derivative!
  17023. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17024. return -3 * p0 * (1 - t) * (1 - t) +
  17025. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17026. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17027. 3 * t * t * p3;
  17028. },
  17029. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17030. // To check if my formulas are correct
  17031. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17032. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17033. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17034. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17035. return h00 + h10 + h01 + h11;
  17036. },
  17037. // Catmull-Rom
  17038. interpolate: function( p0, p1, p2, p3, t ) {
  17039. var v0 = ( p2 - p0 ) * 0.5;
  17040. var v1 = ( p3 - p1 ) * 0.5;
  17041. var t2 = t * t;
  17042. var t3 = t * t2;
  17043. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17044. }
  17045. };
  17046. // TODO: Transformation for Curves?
  17047. /**************************************************************
  17048. * 3D Curves
  17049. **************************************************************/
  17050. // A Factory method for creating new curve subclasses
  17051. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17052. constructor.prototype = Object.create( THREE.Curve.prototype );
  17053. constructor.prototype.getPoint = getPointFunc;
  17054. return constructor;
  17055. };
  17056. /**
  17057. * @author zz85 / http://www.lab4games.net/zz85/blog
  17058. *
  17059. **/
  17060. /**************************************************************
  17061. * Curved Path - a curve path is simply a array of connected
  17062. * curves, but retains the api of a curve
  17063. **************************************************************/
  17064. THREE.CurvePath = function () {
  17065. this.curves = [];
  17066. this.bends = [];
  17067. this.autoClose = false; // Automatically closes the path
  17068. };
  17069. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17070. THREE.CurvePath.prototype.add = function ( curve ) {
  17071. this.curves.push( curve );
  17072. };
  17073. THREE.CurvePath.prototype.checkConnection = function() {
  17074. // TODO
  17075. // If the ending of curve is not connected to the starting
  17076. // or the next curve, then, this is not a real path
  17077. };
  17078. THREE.CurvePath.prototype.closePath = function() {
  17079. // TODO Test
  17080. // and verify for vector3 (needs to implement equals)
  17081. // Add a line curve if start and end of lines are not connected
  17082. var startPoint = this.curves[0].getPoint(0);
  17083. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17084. if (!startPoint.equals(endPoint)) {
  17085. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17086. }
  17087. };
  17088. // To get accurate point with reference to
  17089. // entire path distance at time t,
  17090. // following has to be done:
  17091. // 1. Length of each sub path have to be known
  17092. // 2. Locate and identify type of curve
  17093. // 3. Get t for the curve
  17094. // 4. Return curve.getPointAt(t')
  17095. THREE.CurvePath.prototype.getPoint = function( t ) {
  17096. var d = t * this.getLength();
  17097. var curveLengths = this.getCurveLengths();
  17098. var i = 0, diff, curve;
  17099. // To think about boundaries points.
  17100. while ( i < curveLengths.length ) {
  17101. if ( curveLengths[ i ] >= d ) {
  17102. diff = curveLengths[ i ] - d;
  17103. curve = this.curves[ i ];
  17104. var u = 1 - diff / curve.getLength();
  17105. return curve.getPointAt( u );
  17106. break;
  17107. }
  17108. i ++;
  17109. }
  17110. return null;
  17111. // loop where sum != 0, sum > d , sum+1 <d
  17112. };
  17113. /*
  17114. THREE.CurvePath.prototype.getTangent = function( t ) {
  17115. };*/
  17116. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17117. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17118. // getPoint() depends on getLength
  17119. THREE.CurvePath.prototype.getLength = function() {
  17120. var lens = this.getCurveLengths();
  17121. return lens[ lens.length - 1 ];
  17122. };
  17123. // Compute lengths and cache them
  17124. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17125. THREE.CurvePath.prototype.getCurveLengths = function() {
  17126. // We use cache values if curves and cache array are same length
  17127. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17128. return this.cacheLengths;
  17129. };
  17130. // Get length of subsurve
  17131. // Push sums into cached array
  17132. var lengths = [], sums = 0;
  17133. var i, il = this.curves.length;
  17134. for ( i = 0; i < il; i ++ ) {
  17135. sums += this.curves[ i ].getLength();
  17136. lengths.push( sums );
  17137. }
  17138. this.cacheLengths = lengths;
  17139. return lengths;
  17140. };
  17141. // Returns min and max coordinates, as well as centroid
  17142. THREE.CurvePath.prototype.getBoundingBox = function () {
  17143. var points = this.getPoints();
  17144. var maxX, maxY, maxZ;
  17145. var minX, minY, minZ;
  17146. maxX = maxY = Number.NEGATIVE_INFINITY;
  17147. minX = minY = Number.POSITIVE_INFINITY;
  17148. var p, i, il, sum;
  17149. var v3 = points[0] instanceof THREE.Vector3;
  17150. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17151. for ( i = 0, il = points.length; i < il; i ++ ) {
  17152. p = points[ i ];
  17153. if ( p.x > maxX ) maxX = p.x;
  17154. else if ( p.x < minX ) minX = p.x;
  17155. if ( p.y > maxY ) maxY = p.y;
  17156. else if ( p.y < minY ) minY = p.y;
  17157. if ( v3 ) {
  17158. if ( p.z > maxZ ) maxZ = p.z;
  17159. else if ( p.z < minZ ) minZ = p.z;
  17160. }
  17161. sum.add( p );
  17162. }
  17163. var ret = {
  17164. minX: minX,
  17165. minY: minY,
  17166. maxX: maxX,
  17167. maxY: maxY,
  17168. centroid: sum.divideScalar( il )
  17169. };
  17170. if ( v3 ) {
  17171. ret.maxZ = maxZ;
  17172. ret.minZ = minZ;
  17173. }
  17174. return ret;
  17175. };
  17176. /**************************************************************
  17177. * Create Geometries Helpers
  17178. **************************************************************/
  17179. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17180. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17181. var pts = this.getPoints( divisions, true );
  17182. return this.createGeometry( pts );
  17183. };
  17184. // Generate geometry from equidistance sampling along the path
  17185. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17186. var pts = this.getSpacedPoints( divisions, true );
  17187. return this.createGeometry( pts );
  17188. };
  17189. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17190. var geometry = new THREE.Geometry();
  17191. for ( var i = 0; i < points.length; i ++ ) {
  17192. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17193. }
  17194. return geometry;
  17195. };
  17196. /**************************************************************
  17197. * Bend / Wrap Helper Methods
  17198. **************************************************************/
  17199. // Wrap path / Bend modifiers?
  17200. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17201. this.bends.push( bendpath );
  17202. };
  17203. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17204. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17205. var i, il;
  17206. if ( !bends ) {
  17207. bends = this.bends;
  17208. }
  17209. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17210. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17211. }
  17212. return oldPts;
  17213. };
  17214. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17215. var oldPts = this.getSpacedPoints( segments );
  17216. var i, il;
  17217. if ( !bends ) {
  17218. bends = this.bends;
  17219. }
  17220. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17221. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17222. }
  17223. return oldPts;
  17224. };
  17225. // This returns getPoints() bend/wrapped around the contour of a path.
  17226. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17227. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17228. var bounds = this.getBoundingBox();
  17229. var i, il, p, oldX, oldY, xNorm;
  17230. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17231. p = oldPts[ i ];
  17232. oldX = p.x;
  17233. oldY = p.y;
  17234. xNorm = oldX / bounds.maxX;
  17235. // If using actual distance, for length > path, requires line extrusions
  17236. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17237. xNorm = path.getUtoTmapping( xNorm, oldX );
  17238. // check for out of bounds?
  17239. var pathPt = path.getPoint( xNorm );
  17240. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17241. p.x = pathPt.x + normal.x;
  17242. p.y = pathPt.y + normal.y;
  17243. }
  17244. return oldPts;
  17245. };
  17246. /**
  17247. * @author alteredq / http://alteredqualia.com/
  17248. */
  17249. THREE.Gyroscope = function () {
  17250. THREE.Object3D.call( this );
  17251. };
  17252. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17253. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17254. this.matrixAutoUpdate && this.updateMatrix();
  17255. // update matrixWorld
  17256. if ( this.matrixWorldNeedsUpdate || force ) {
  17257. if ( this.parent ) {
  17258. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17259. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17260. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17261. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17262. } else {
  17263. this.matrixWorld.copy( this.matrix );
  17264. }
  17265. this.matrixWorldNeedsUpdate = false;
  17266. force = true;
  17267. }
  17268. // update children
  17269. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17270. this.children[ i ].updateMatrixWorld( force );
  17271. }
  17272. };
  17273. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17274. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17275. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17276. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17277. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17278. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17279. /**
  17280. * @author zz85 / http://www.lab4games.net/zz85/blog
  17281. * Creates free form 2d path using series of points, lines or curves.
  17282. *
  17283. **/
  17284. THREE.Path = function ( points ) {
  17285. THREE.CurvePath.call(this);
  17286. this.actions = [];
  17287. if ( points ) {
  17288. this.fromPoints( points );
  17289. }
  17290. };
  17291. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17292. THREE.PathActions = {
  17293. MOVE_TO: 'moveTo',
  17294. LINE_TO: 'lineTo',
  17295. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17296. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17297. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17298. ARC: 'arc', // Circle
  17299. ELLIPSE: 'ellipse'
  17300. };
  17301. // TODO Clean up PATH API
  17302. // Create path using straight lines to connect all points
  17303. // - vectors: array of Vector2
  17304. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17305. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17306. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17307. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17308. };
  17309. };
  17310. // startPath() endPath()?
  17311. THREE.Path.prototype.moveTo = function ( x, y ) {
  17312. var args = Array.prototype.slice.call( arguments );
  17313. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17314. };
  17315. THREE.Path.prototype.lineTo = function ( x, y ) {
  17316. var args = Array.prototype.slice.call( arguments );
  17317. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17318. var x0 = lastargs[ lastargs.length - 2 ];
  17319. var y0 = lastargs[ lastargs.length - 1 ];
  17320. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17321. this.curves.push( curve );
  17322. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17323. };
  17324. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17325. var args = Array.prototype.slice.call( arguments );
  17326. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17327. var x0 = lastargs[ lastargs.length - 2 ];
  17328. var y0 = lastargs[ lastargs.length - 1 ];
  17329. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17330. new THREE.Vector2( aCPx, aCPy ),
  17331. new THREE.Vector2( aX, aY ) );
  17332. this.curves.push( curve );
  17333. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17334. };
  17335. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17336. aCP2x, aCP2y,
  17337. aX, aY ) {
  17338. var args = Array.prototype.slice.call( arguments );
  17339. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17340. var x0 = lastargs[ lastargs.length - 2 ];
  17341. var y0 = lastargs[ lastargs.length - 1 ];
  17342. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17343. new THREE.Vector2( aCP1x, aCP1y ),
  17344. new THREE.Vector2( aCP2x, aCP2y ),
  17345. new THREE.Vector2( aX, aY ) );
  17346. this.curves.push( curve );
  17347. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17348. };
  17349. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17350. var args = Array.prototype.slice.call( arguments );
  17351. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17352. var x0 = lastargs[ lastargs.length - 2 ];
  17353. var y0 = lastargs[ lastargs.length - 1 ];
  17354. //---
  17355. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17356. Array.prototype.push.apply( npts, pts );
  17357. var curve = new THREE.SplineCurve( npts );
  17358. this.curves.push( curve );
  17359. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17360. };
  17361. // FUTURE: Change the API or follow canvas API?
  17362. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17363. aStartAngle, aEndAngle, aClockwise ) {
  17364. var lastargs = this.actions[ this.actions.length - 1].args;
  17365. var x0 = lastargs[ lastargs.length - 2 ];
  17366. var y0 = lastargs[ lastargs.length - 1 ];
  17367. this.absarc(aX + x0, aY + y0, aRadius,
  17368. aStartAngle, aEndAngle, aClockwise );
  17369. };
  17370. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17371. aStartAngle, aEndAngle, aClockwise ) {
  17372. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17373. };
  17374. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17375. aStartAngle, aEndAngle, aClockwise ) {
  17376. var lastargs = this.actions[ this.actions.length - 1].args;
  17377. var x0 = lastargs[ lastargs.length - 2 ];
  17378. var y0 = lastargs[ lastargs.length - 1 ];
  17379. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17380. aStartAngle, aEndAngle, aClockwise );
  17381. };
  17382. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17383. aStartAngle, aEndAngle, aClockwise ) {
  17384. var args = Array.prototype.slice.call( arguments );
  17385. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17386. aStartAngle, aEndAngle, aClockwise );
  17387. this.curves.push( curve );
  17388. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17389. args.push(lastPoint.x);
  17390. args.push(lastPoint.y);
  17391. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17392. };
  17393. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17394. if ( ! divisions ) divisions = 40;
  17395. var points = [];
  17396. for ( var i = 0; i < divisions; i ++ ) {
  17397. points.push( this.getPoint( i / divisions ) );
  17398. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17399. }
  17400. // if ( closedPath ) {
  17401. //
  17402. // points.push( points[ 0 ] );
  17403. //
  17404. // }
  17405. return points;
  17406. };
  17407. /* Return an array of vectors based on contour of the path */
  17408. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17409. if (this.useSpacedPoints) {
  17410. console.log('tata');
  17411. return this.getSpacedPoints( divisions, closedPath );
  17412. }
  17413. divisions = divisions || 12;
  17414. var points = [];
  17415. var i, il, item, action, args;
  17416. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17417. laste, j,
  17418. t, tx, ty;
  17419. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17420. item = this.actions[ i ];
  17421. action = item.action;
  17422. args = item.args;
  17423. switch( action ) {
  17424. case THREE.PathActions.MOVE_TO:
  17425. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17426. break;
  17427. case THREE.PathActions.LINE_TO:
  17428. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17429. break;
  17430. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17431. cpx = args[ 2 ];
  17432. cpy = args[ 3 ];
  17433. cpx1 = args[ 0 ];
  17434. cpy1 = args[ 1 ];
  17435. if ( points.length > 0 ) {
  17436. laste = points[ points.length - 1 ];
  17437. cpx0 = laste.x;
  17438. cpy0 = laste.y;
  17439. } else {
  17440. laste = this.actions[ i - 1 ].args;
  17441. cpx0 = laste[ laste.length - 2 ];
  17442. cpy0 = laste[ laste.length - 1 ];
  17443. }
  17444. for ( j = 1; j <= divisions; j ++ ) {
  17445. t = j / divisions;
  17446. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17447. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17448. points.push( new THREE.Vector2( tx, ty ) );
  17449. }
  17450. break;
  17451. case THREE.PathActions.BEZIER_CURVE_TO:
  17452. cpx = args[ 4 ];
  17453. cpy = args[ 5 ];
  17454. cpx1 = args[ 0 ];
  17455. cpy1 = args[ 1 ];
  17456. cpx2 = args[ 2 ];
  17457. cpy2 = args[ 3 ];
  17458. if ( points.length > 0 ) {
  17459. laste = points[ points.length - 1 ];
  17460. cpx0 = laste.x;
  17461. cpy0 = laste.y;
  17462. } else {
  17463. laste = this.actions[ i - 1 ].args;
  17464. cpx0 = laste[ laste.length - 2 ];
  17465. cpy0 = laste[ laste.length - 1 ];
  17466. }
  17467. for ( j = 1; j <= divisions; j ++ ) {
  17468. t = j / divisions;
  17469. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17470. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17471. points.push( new THREE.Vector2( tx, ty ) );
  17472. }
  17473. break;
  17474. case THREE.PathActions.CSPLINE_THRU:
  17475. laste = this.actions[ i - 1 ].args;
  17476. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17477. var spts = [ last ];
  17478. var n = divisions * args[ 0 ].length;
  17479. spts = spts.concat( args[ 0 ] );
  17480. var spline = new THREE.SplineCurve( spts );
  17481. for ( j = 1; j <= n; j ++ ) {
  17482. points.push( spline.getPointAt( j / n ) ) ;
  17483. }
  17484. break;
  17485. case THREE.PathActions.ARC:
  17486. var aX = args[ 0 ], aY = args[ 1 ],
  17487. aRadius = args[ 2 ],
  17488. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17489. aClockwise = !!args[ 5 ];
  17490. var deltaAngle = aEndAngle - aStartAngle;
  17491. var angle;
  17492. var tdivisions = divisions * 2;
  17493. for ( j = 1; j <= tdivisions; j ++ ) {
  17494. t = j / tdivisions;
  17495. if ( ! aClockwise ) {
  17496. t = 1 - t;
  17497. }
  17498. angle = aStartAngle + t * deltaAngle;
  17499. tx = aX + aRadius * Math.cos( angle );
  17500. ty = aY + aRadius * Math.sin( angle );
  17501. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17502. points.push( new THREE.Vector2( tx, ty ) );
  17503. }
  17504. //console.log(points);
  17505. break;
  17506. case THREE.PathActions.ELLIPSE:
  17507. var aX = args[ 0 ], aY = args[ 1 ],
  17508. xRadius = args[ 2 ],
  17509. yRadius = args[ 3 ],
  17510. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17511. aClockwise = !!args[ 6 ];
  17512. var deltaAngle = aEndAngle - aStartAngle;
  17513. var angle;
  17514. var tdivisions = divisions * 2;
  17515. for ( j = 1; j <= tdivisions; j ++ ) {
  17516. t = j / tdivisions;
  17517. if ( ! aClockwise ) {
  17518. t = 1 - t;
  17519. }
  17520. angle = aStartAngle + t * deltaAngle;
  17521. tx = aX + xRadius * Math.cos( angle );
  17522. ty = aY + yRadius * Math.sin( angle );
  17523. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17524. points.push( new THREE.Vector2( tx, ty ) );
  17525. }
  17526. //console.log(points);
  17527. break;
  17528. } // end switch
  17529. }
  17530. // Normalize to remove the closing point by default.
  17531. var lastPoint = points[ points.length - 1];
  17532. var EPSILON = 0.0000000001;
  17533. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17534. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17535. points.splice( points.length - 1, 1);
  17536. if ( closedPath ) {
  17537. points.push( points[ 0 ] );
  17538. }
  17539. return points;
  17540. };
  17541. // Breaks path into shapes
  17542. THREE.Path.prototype.toShapes = function( isCCW ) {
  17543. var i, il, item, action, args;
  17544. var subPaths = [], lastPath = new THREE.Path();
  17545. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17546. item = this.actions[ i ];
  17547. args = item.args;
  17548. action = item.action;
  17549. if ( action == THREE.PathActions.MOVE_TO ) {
  17550. if ( lastPath.actions.length != 0 ) {
  17551. subPaths.push( lastPath );
  17552. lastPath = new THREE.Path();
  17553. }
  17554. }
  17555. lastPath[ action ].apply( lastPath, args );
  17556. }
  17557. if ( lastPath.actions.length != 0 ) {
  17558. subPaths.push( lastPath );
  17559. }
  17560. // console.log(subPaths);
  17561. if ( subPaths.length == 0 ) return [];
  17562. var solid, tmpPath, tmpShape, shapes = [];
  17563. if ( subPaths.length == 1) {
  17564. tmpPath = subPaths[0];
  17565. tmpShape = new THREE.Shape();
  17566. tmpShape.actions = tmpPath.actions;
  17567. tmpShape.curves = tmpPath.curves;
  17568. shapes.push( tmpShape );
  17569. return shapes;
  17570. }
  17571. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17572. holesFirst = isCCW ? !holesFirst : holesFirst;
  17573. // console.log("Holes first", holesFirst);
  17574. if ( holesFirst ) {
  17575. tmpShape = new THREE.Shape();
  17576. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17577. tmpPath = subPaths[ i ];
  17578. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17579. solid = isCCW ? !solid : solid;
  17580. if ( solid ) {
  17581. tmpShape.actions = tmpPath.actions;
  17582. tmpShape.curves = tmpPath.curves;
  17583. shapes.push( tmpShape );
  17584. tmpShape = new THREE.Shape();
  17585. //console.log('cw', i);
  17586. } else {
  17587. tmpShape.holes.push( tmpPath );
  17588. //console.log('ccw', i);
  17589. }
  17590. }
  17591. } else {
  17592. // Shapes first
  17593. tmpShape = undefined;
  17594. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17595. tmpPath = subPaths[ i ];
  17596. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17597. solid = isCCW ? !solid : solid;
  17598. if ( solid ) {
  17599. if ( tmpShape ) shapes.push( tmpShape );
  17600. tmpShape = new THREE.Shape();
  17601. tmpShape.actions = tmpPath.actions;
  17602. tmpShape.curves = tmpPath.curves;
  17603. } else {
  17604. tmpShape.holes.push( tmpPath );
  17605. }
  17606. }
  17607. shapes.push( tmpShape );
  17608. }
  17609. //console.log("shape", shapes);
  17610. return shapes;
  17611. };
  17612. /**
  17613. * @author zz85 / http://www.lab4games.net/zz85/blog
  17614. * Defines a 2d shape plane using paths.
  17615. **/
  17616. // STEP 1 Create a path.
  17617. // STEP 2 Turn path into shape.
  17618. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17619. // STEP 3a - Extract points from each shape, turn to vertices
  17620. // STEP 3b - Triangulate each shape, add faces.
  17621. THREE.Shape = function () {
  17622. THREE.Path.apply( this, arguments );
  17623. this.holes = [];
  17624. };
  17625. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17626. // Convenience method to return ExtrudeGeometry
  17627. THREE.Shape.prototype.extrude = function ( options ) {
  17628. var extruded = new THREE.ExtrudeGeometry( this, options );
  17629. return extruded;
  17630. };
  17631. // Convenience method to return ShapeGeometry
  17632. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17633. var geometry = new THREE.ShapeGeometry( this, options );
  17634. return geometry;
  17635. };
  17636. // Get points of holes
  17637. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17638. var i, il = this.holes.length, holesPts = [];
  17639. for ( i = 0; i < il; i ++ ) {
  17640. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17641. }
  17642. return holesPts;
  17643. };
  17644. // Get points of holes (spaced by regular distance)
  17645. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17646. var i, il = this.holes.length, holesPts = [];
  17647. for ( i = 0; i < il; i ++ ) {
  17648. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17649. }
  17650. return holesPts;
  17651. };
  17652. // Get points of shape and holes (keypoints based on segments parameter)
  17653. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17654. return {
  17655. shape: this.getTransformedPoints( divisions ),
  17656. holes: this.getPointsHoles( divisions )
  17657. };
  17658. };
  17659. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17660. if (this.useSpacedPoints) {
  17661. return this.extractAllSpacedPoints(divisions);
  17662. }
  17663. return this.extractAllPoints(divisions);
  17664. };
  17665. //
  17666. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17667. //
  17668. // return {
  17669. //
  17670. // shape: this.transform( bend, divisions ),
  17671. // holes: this.getPointsHoles( divisions, bend )
  17672. //
  17673. // };
  17674. //
  17675. // };
  17676. // Get points of shape and holes (spaced by regular distance)
  17677. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17678. return {
  17679. shape: this.getTransformedSpacedPoints( divisions ),
  17680. holes: this.getSpacedPointsHoles( divisions )
  17681. };
  17682. };
  17683. /**************************************************************
  17684. * Utils
  17685. **************************************************************/
  17686. THREE.Shape.Utils = {
  17687. /*
  17688. contour - array of vector2 for contour
  17689. holes - array of array of vector2
  17690. */
  17691. removeHoles: function ( contour, holes ) {
  17692. var shape = contour.concat(); // work on this shape
  17693. var allpoints = shape.concat();
  17694. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17695. var prevShapeVert, nextShapeVert,
  17696. prevHoleVert, nextHoleVert,
  17697. holeIndex, shapeIndex,
  17698. shapeId, shapeGroup,
  17699. h, h2,
  17700. hole, shortest, d,
  17701. p, pts1, pts2,
  17702. tmpShape1, tmpShape2,
  17703. tmpHole1, tmpHole2,
  17704. verts = [];
  17705. for ( h = 0; h < holes.length; h ++ ) {
  17706. hole = holes[ h ];
  17707. /*
  17708. shapeholes[ h ].concat(); // preserves original
  17709. holes.push( hole );
  17710. */
  17711. Array.prototype.push.apply( allpoints, hole );
  17712. shortest = Number.POSITIVE_INFINITY;
  17713. // Find the shortest pair of pts between shape and hole
  17714. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17715. // Using distanceToSquared() intead of distanceTo() should speed a little
  17716. // since running square roots operations are reduced.
  17717. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17718. pts1 = hole[ h2 ];
  17719. var dist = [];
  17720. for ( p = 0; p < shape.length; p++ ) {
  17721. pts2 = shape[ p ];
  17722. d = pts1.distanceToSquared( pts2 );
  17723. dist.push( d );
  17724. if ( d < shortest ) {
  17725. shortest = d;
  17726. holeIndex = h2;
  17727. shapeIndex = p;
  17728. }
  17729. }
  17730. }
  17731. //console.log("shortest", shortest, dist);
  17732. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17733. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17734. var areaapts = [
  17735. hole[ holeIndex ],
  17736. shape[ shapeIndex ],
  17737. shape[ prevShapeVert ]
  17738. ];
  17739. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17740. var areabpts = [
  17741. hole[ holeIndex ],
  17742. hole[ prevHoleVert ],
  17743. shape[ shapeIndex ]
  17744. ];
  17745. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17746. var shapeOffset = 1;
  17747. var holeOffset = -1;
  17748. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17749. shapeIndex += shapeOffset;
  17750. holeIndex += holeOffset;
  17751. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17752. shapeIndex %= shape.length;
  17753. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17754. holeIndex %= hole.length;
  17755. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17756. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17757. areaapts = [
  17758. hole[ holeIndex ],
  17759. shape[ shapeIndex ],
  17760. shape[ prevShapeVert ]
  17761. ];
  17762. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17763. areabpts = [
  17764. hole[ holeIndex ],
  17765. hole[ prevHoleVert ],
  17766. shape[ shapeIndex ]
  17767. ];
  17768. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17769. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17770. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17771. // In case areas are not correct.
  17772. //console.log("USE THIS");
  17773. shapeIndex = oldShapeIndex;
  17774. holeIndex = oldHoleIndex ;
  17775. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17776. shapeIndex %= shape.length;
  17777. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17778. holeIndex %= hole.length;
  17779. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17780. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17781. } else {
  17782. //console.log("USE THAT ")
  17783. }
  17784. tmpShape1 = shape.slice( 0, shapeIndex );
  17785. tmpShape2 = shape.slice( shapeIndex );
  17786. tmpHole1 = hole.slice( holeIndex );
  17787. tmpHole2 = hole.slice( 0, holeIndex );
  17788. // Should check orders here again?
  17789. var trianglea = [
  17790. hole[ holeIndex ],
  17791. shape[ shapeIndex ],
  17792. shape[ prevShapeVert ]
  17793. ];
  17794. var triangleb = [
  17795. hole[ holeIndex ] ,
  17796. hole[ prevHoleVert ],
  17797. shape[ shapeIndex ]
  17798. ];
  17799. verts.push( trianglea );
  17800. verts.push( triangleb );
  17801. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17802. }
  17803. return {
  17804. shape:shape, /* shape with no holes */
  17805. isolatedPts: verts, /* isolated faces */
  17806. allpoints: allpoints
  17807. }
  17808. },
  17809. triangulateShape: function ( contour, holes ) {
  17810. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17811. var shape = shapeWithoutHoles.shape,
  17812. allpoints = shapeWithoutHoles.allpoints,
  17813. isolatedPts = shapeWithoutHoles.isolatedPts;
  17814. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17815. // 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.
  17816. //console.log( "triangles",triangles, triangles.length );
  17817. //console.log( "allpoints",allpoints, allpoints.length );
  17818. var i, il, f, face,
  17819. key, index,
  17820. allPointsMap = {},
  17821. isolatedPointsMap = {};
  17822. // prepare all points map
  17823. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17824. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17825. if ( allPointsMap[ key ] !== undefined ) {
  17826. console.log( "Duplicate point", key );
  17827. }
  17828. allPointsMap[ key ] = i;
  17829. }
  17830. // check all face vertices against all points map
  17831. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17832. face = triangles[ i ];
  17833. for ( f = 0; f < 3; f ++ ) {
  17834. key = face[ f ].x + ":" + face[ f ].y;
  17835. index = allPointsMap[ key ];
  17836. if ( index !== undefined ) {
  17837. face[ f ] = index;
  17838. }
  17839. }
  17840. }
  17841. // check isolated points vertices against all points map
  17842. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17843. face = isolatedPts[ i ];
  17844. for ( f = 0; f < 3; f ++ ) {
  17845. key = face[ f ].x + ":" + face[ f ].y;
  17846. index = allPointsMap[ key ];
  17847. if ( index !== undefined ) {
  17848. face[ f ] = index;
  17849. }
  17850. }
  17851. }
  17852. return triangles.concat( isolatedPts );
  17853. }, // end triangulate shapes
  17854. /*
  17855. triangulate2 : function( pts, holes ) {
  17856. // For use with Poly2Tri.js
  17857. var allpts = pts.concat();
  17858. var shape = [];
  17859. for (var p in pts) {
  17860. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17861. }
  17862. var swctx = new js.poly2tri.SweepContext(shape);
  17863. for (var h in holes) {
  17864. var aHole = holes[h];
  17865. var newHole = []
  17866. for (i in aHole) {
  17867. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17868. allpts.push(aHole[i]);
  17869. }
  17870. swctx.AddHole(newHole);
  17871. }
  17872. var find;
  17873. var findIndexForPt = function (pt) {
  17874. find = new THREE.Vector2(pt.x, pt.y);
  17875. var p;
  17876. for (p=0, pl = allpts.length; p<pl; p++) {
  17877. if (allpts[p].equals(find)) return p;
  17878. }
  17879. return -1;
  17880. };
  17881. // triangulate
  17882. js.poly2tri.sweep.Triangulate(swctx);
  17883. var triangles = swctx.GetTriangles();
  17884. var tr ;
  17885. var facesPts = [];
  17886. for (var t in triangles) {
  17887. tr = triangles[t];
  17888. facesPts.push([
  17889. findIndexForPt(tr.GetPoint(0)),
  17890. findIndexForPt(tr.GetPoint(1)),
  17891. findIndexForPt(tr.GetPoint(2))
  17892. ]);
  17893. }
  17894. // console.log(facesPts);
  17895. // console.log("triangles", triangles.length, triangles);
  17896. // Returns array of faces with 3 element each
  17897. return facesPts;
  17898. },
  17899. */
  17900. isClockWise: function ( pts ) {
  17901. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17902. },
  17903. // Bezier Curves formulas obtained from
  17904. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17905. // Quad Bezier Functions
  17906. b2p0: function ( t, p ) {
  17907. var k = 1 - t;
  17908. return k * k * p;
  17909. },
  17910. b2p1: function ( t, p ) {
  17911. return 2 * ( 1 - t ) * t * p;
  17912. },
  17913. b2p2: function ( t, p ) {
  17914. return t * t * p;
  17915. },
  17916. b2: function ( t, p0, p1, p2 ) {
  17917. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17918. },
  17919. // Cubic Bezier Functions
  17920. b3p0: function ( t, p ) {
  17921. var k = 1 - t;
  17922. return k * k * k * p;
  17923. },
  17924. b3p1: function ( t, p ) {
  17925. var k = 1 - t;
  17926. return 3 * k * k * t * p;
  17927. },
  17928. b3p2: function ( t, p ) {
  17929. var k = 1 - t;
  17930. return 3 * k * t * t * p;
  17931. },
  17932. b3p3: function ( t, p ) {
  17933. return t * t * t * p;
  17934. },
  17935. b3: function ( t, p0, p1, p2, p3 ) {
  17936. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17937. }
  17938. };
  17939. /**************************************************************
  17940. * Line
  17941. **************************************************************/
  17942. THREE.LineCurve = function ( v1, v2 ) {
  17943. this.v1 = v1;
  17944. this.v2 = v2;
  17945. };
  17946. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17947. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17948. var point = this.v2.clone().sub(this.v1);
  17949. point.multiplyScalar( t ).add( this.v1 );
  17950. return point;
  17951. };
  17952. // Line curve is linear, so we can overwrite default getPointAt
  17953. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17954. return this.getPoint( u );
  17955. };
  17956. THREE.LineCurve.prototype.getTangent = function( t ) {
  17957. var tangent = this.v2.clone().sub(this.v1);
  17958. return tangent.normalize();
  17959. };
  17960. /**************************************************************
  17961. * Quadratic Bezier curve
  17962. **************************************************************/
  17963. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17964. this.v0 = v0;
  17965. this.v1 = v1;
  17966. this.v2 = v2;
  17967. };
  17968. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17969. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17970. var tx, ty;
  17971. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17972. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17973. return new THREE.Vector2( tx, ty );
  17974. };
  17975. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17976. var tx, ty;
  17977. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17978. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17979. // returns unit vector
  17980. var tangent = new THREE.Vector2( tx, ty );
  17981. tangent.normalize();
  17982. return tangent;
  17983. };
  17984. /**************************************************************
  17985. * Cubic Bezier curve
  17986. **************************************************************/
  17987. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17988. this.v0 = v0;
  17989. this.v1 = v1;
  17990. this.v2 = v2;
  17991. this.v3 = v3;
  17992. };
  17993. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17994. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17995. var tx, ty;
  17996. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17997. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17998. return new THREE.Vector2( tx, ty );
  17999. };
  18000. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18001. var tx, ty;
  18002. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18003. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18004. var tangent = new THREE.Vector2( tx, ty );
  18005. tangent.normalize();
  18006. return tangent;
  18007. };
  18008. /**************************************************************
  18009. * Spline curve
  18010. **************************************************************/
  18011. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18012. this.points = (points == undefined) ? [] : points;
  18013. };
  18014. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18015. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18016. var v = new THREE.Vector2();
  18017. var c = [];
  18018. var points = this.points, point, intPoint, weight;
  18019. point = ( points.length - 1 ) * t;
  18020. intPoint = Math.floor( point );
  18021. weight = point - intPoint;
  18022. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18023. c[ 1 ] = intPoint;
  18024. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18025. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18026. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18027. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18028. return v;
  18029. };
  18030. /**************************************************************
  18031. * Ellipse curve
  18032. **************************************************************/
  18033. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  18034. aStartAngle, aEndAngle,
  18035. aClockwise ) {
  18036. this.aX = aX;
  18037. this.aY = aY;
  18038. this.xRadius = xRadius;
  18039. this.yRadius = yRadius;
  18040. this.aStartAngle = aStartAngle;
  18041. this.aEndAngle = aEndAngle;
  18042. this.aClockwise = aClockwise;
  18043. };
  18044. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18045. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18046. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18047. if ( !this.aClockwise ) {
  18048. t = 1 - t;
  18049. }
  18050. var angle = this.aStartAngle + t * deltaAngle;
  18051. var tx = this.aX + this.xRadius * Math.cos( angle );
  18052. var ty = this.aY + this.yRadius * Math.sin( angle );
  18053. return new THREE.Vector2( tx, ty );
  18054. };
  18055. /**************************************************************
  18056. * Arc curve
  18057. **************************************************************/
  18058. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18059. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18060. };
  18061. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18062. /**************************************************************
  18063. * Line3D
  18064. **************************************************************/
  18065. THREE.LineCurve3 = THREE.Curve.create(
  18066. function ( v1, v2 ) {
  18067. this.v1 = v1;
  18068. this.v2 = v2;
  18069. },
  18070. function ( t ) {
  18071. var r = new THREE.Vector3();
  18072. r.subVectors( this.v2, this.v1 ); // diff
  18073. r.multiplyScalar( t );
  18074. r.add( this.v1 );
  18075. return r;
  18076. }
  18077. );
  18078. /**************************************************************
  18079. * Quadratic Bezier 3D curve
  18080. **************************************************************/
  18081. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18082. function ( v0, v1, v2 ) {
  18083. this.v0 = v0;
  18084. this.v1 = v1;
  18085. this.v2 = v2;
  18086. },
  18087. function ( t ) {
  18088. var tx, ty, tz;
  18089. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18090. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18091. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18092. return new THREE.Vector3( tx, ty, tz );
  18093. }
  18094. );
  18095. /**************************************************************
  18096. * Cubic Bezier 3D curve
  18097. **************************************************************/
  18098. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18099. function ( v0, v1, v2, v3 ) {
  18100. this.v0 = v0;
  18101. this.v1 = v1;
  18102. this.v2 = v2;
  18103. this.v3 = v3;
  18104. },
  18105. function ( t ) {
  18106. var tx, ty, tz;
  18107. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18108. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18109. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18110. return new THREE.Vector3( tx, ty, tz );
  18111. }
  18112. );
  18113. /**************************************************************
  18114. * Spline 3D curve
  18115. **************************************************************/
  18116. THREE.SplineCurve3 = THREE.Curve.create(
  18117. function ( points /* array of Vector3 */) {
  18118. this.points = (points == undefined) ? [] : points;
  18119. },
  18120. function ( t ) {
  18121. var v = new THREE.Vector3();
  18122. var c = [];
  18123. var points = this.points, point, intPoint, weight;
  18124. point = ( points.length - 1 ) * t;
  18125. intPoint = Math.floor( point );
  18126. weight = point - intPoint;
  18127. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18128. c[ 1 ] = intPoint;
  18129. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18130. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18131. var pt0 = points[ c[0] ],
  18132. pt1 = points[ c[1] ],
  18133. pt2 = points[ c[2] ],
  18134. pt3 = points[ c[3] ];
  18135. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18136. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18137. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18138. return v;
  18139. }
  18140. );
  18141. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18142. // var v = new THREE.Vector3();
  18143. // var c = [];
  18144. // var points = this.points, point, intPoint, weight;
  18145. // point = ( points.length - 1 ) * t;
  18146. // intPoint = Math.floor( point );
  18147. // weight = point - intPoint;
  18148. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18149. // c[ 1 ] = intPoint;
  18150. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18151. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18152. // var pt0 = points[ c[0] ],
  18153. // pt1 = points[ c[1] ],
  18154. // pt2 = points[ c[2] ],
  18155. // pt3 = points[ c[3] ];
  18156. // // t = weight;
  18157. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18158. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18159. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18160. // return v;
  18161. // }
  18162. /**************************************************************
  18163. * Closed Spline 3D curve
  18164. **************************************************************/
  18165. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18166. function ( points /* array of Vector3 */) {
  18167. this.points = (points == undefined) ? [] : points;
  18168. },
  18169. function ( t ) {
  18170. var v = new THREE.Vector3();
  18171. var c = [];
  18172. var points = this.points, point, intPoint, weight;
  18173. point = ( points.length - 0 ) * t;
  18174. // This needs to be from 0-length +1
  18175. intPoint = Math.floor( point );
  18176. weight = point - intPoint;
  18177. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18178. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18179. c[ 1 ] = ( intPoint ) % points.length;
  18180. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18181. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18182. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18183. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18184. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18185. return v;
  18186. }
  18187. );
  18188. /**
  18189. * @author mikael emtinger / http://gomo.se/
  18190. */
  18191. THREE.AnimationHandler = (function() {
  18192. var playing = [];
  18193. var library = {};
  18194. var that = {};
  18195. //--- update ---
  18196. that.update = function( deltaTimeMS ) {
  18197. for( var i = 0; i < playing.length; i ++ )
  18198. playing[ i ].update( deltaTimeMS );
  18199. };
  18200. //--- add ---
  18201. that.addToUpdate = function( animation ) {
  18202. if ( playing.indexOf( animation ) === -1 )
  18203. playing.push( animation );
  18204. };
  18205. //--- remove ---
  18206. that.removeFromUpdate = function( animation ) {
  18207. var index = playing.indexOf( animation );
  18208. if( index !== -1 )
  18209. playing.splice( index, 1 );
  18210. };
  18211. //--- add ---
  18212. that.add = function( data ) {
  18213. if ( library[ data.name ] !== undefined )
  18214. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18215. library[ data.name ] = data;
  18216. initData( data );
  18217. };
  18218. //--- get ---
  18219. that.get = function( name ) {
  18220. if ( typeof name === "string" ) {
  18221. if ( library[ name ] ) {
  18222. return library[ name ];
  18223. } else {
  18224. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18225. return null;
  18226. }
  18227. } else {
  18228. // todo: add simple tween library
  18229. }
  18230. };
  18231. //--- parse ---
  18232. that.parse = function( root ) {
  18233. // setup hierarchy
  18234. var hierarchy = [];
  18235. if ( root instanceof THREE.SkinnedMesh ) {
  18236. for( var b = 0; b < root.bones.length; b++ ) {
  18237. hierarchy.push( root.bones[ b ] );
  18238. }
  18239. } else {
  18240. parseRecurseHierarchy( root, hierarchy );
  18241. }
  18242. return hierarchy;
  18243. };
  18244. var parseRecurseHierarchy = function( root, hierarchy ) {
  18245. hierarchy.push( root );
  18246. for( var c = 0; c < root.children.length; c++ )
  18247. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18248. }
  18249. //--- init data ---
  18250. var initData = function( data ) {
  18251. if( data.initialized === true )
  18252. return;
  18253. // loop through all keys
  18254. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18255. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18256. // remove minus times
  18257. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18258. data.hierarchy[ h ].keys[ k ].time = 0;
  18259. // create quaternions
  18260. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18261. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18262. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18263. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18264. }
  18265. }
  18266. // prepare morph target keys
  18267. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18268. // get all used
  18269. var usedMorphTargets = {};
  18270. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18271. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18272. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18273. usedMorphTargets[ morphTargetName ] = -1;
  18274. }
  18275. }
  18276. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18277. // set all used on all frames
  18278. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18279. var influences = {};
  18280. for ( var morphTargetName in usedMorphTargets ) {
  18281. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18282. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18283. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18284. break;
  18285. }
  18286. }
  18287. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18288. influences[ morphTargetName ] = 0;
  18289. }
  18290. }
  18291. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18292. }
  18293. }
  18294. // remove all keys that are on the same time
  18295. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18296. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18297. data.hierarchy[ h ].keys.splice( k, 1 );
  18298. k --;
  18299. }
  18300. }
  18301. // set index
  18302. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18303. data.hierarchy[ h ].keys[ k ].index = k;
  18304. }
  18305. }
  18306. // JIT
  18307. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  18308. data.JIT = {};
  18309. data.JIT.hierarchy = [];
  18310. for( var h = 0; h < data.hierarchy.length; h ++ )
  18311. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  18312. // done
  18313. data.initialized = true;
  18314. };
  18315. // interpolation types
  18316. that.LINEAR = 0;
  18317. that.CATMULLROM = 1;
  18318. that.CATMULLROM_FORWARD = 2;
  18319. return that;
  18320. }());
  18321. /**
  18322. * @author mikael emtinger / http://gomo.se/
  18323. * @author mrdoob / http://mrdoob.com/
  18324. * @author alteredq / http://alteredqualia.com/
  18325. */
  18326. THREE.Animation = function ( root, name, interpolationType ) {
  18327. this.root = root;
  18328. this.data = THREE.AnimationHandler.get( name );
  18329. this.hierarchy = THREE.AnimationHandler.parse( root );
  18330. this.currentTime = 0;
  18331. this.timeScale = 1;
  18332. this.isPlaying = false;
  18333. this.isPaused = true;
  18334. this.loop = true;
  18335. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  18336. this.points = [];
  18337. this.target = new THREE.Vector3();
  18338. };
  18339. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  18340. if ( this.isPlaying === false ) {
  18341. this.isPlaying = true;
  18342. this.loop = loop !== undefined ? loop : true;
  18343. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18344. // reset key cache
  18345. var h, hl = this.hierarchy.length,
  18346. object;
  18347. for ( h = 0; h < hl; h ++ ) {
  18348. object = this.hierarchy[ h ];
  18349. object.matrixAutoUpdate = true;
  18350. if ( object.animationCache === undefined ) {
  18351. object.animationCache = {};
  18352. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18353. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18354. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18355. }
  18356. var prevKey = object.animationCache.prevKey;
  18357. var nextKey = object.animationCache.nextKey;
  18358. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18359. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18360. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18361. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18362. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18363. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18364. }
  18365. this.update( 0 );
  18366. }
  18367. this.isPaused = false;
  18368. THREE.AnimationHandler.addToUpdate( this );
  18369. };
  18370. THREE.Animation.prototype.pause = function() {
  18371. if ( this.isPaused === true ) {
  18372. THREE.AnimationHandler.addToUpdate( this );
  18373. } else {
  18374. THREE.AnimationHandler.removeFromUpdate( this );
  18375. }
  18376. this.isPaused = !this.isPaused;
  18377. };
  18378. THREE.Animation.prototype.stop = function() {
  18379. this.isPlaying = false;
  18380. this.isPaused = false;
  18381. THREE.AnimationHandler.removeFromUpdate( this );
  18382. };
  18383. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  18384. // early out
  18385. if ( this.isPlaying === false ) return;
  18386. // vars
  18387. var types = [ "pos", "rot", "scl" ];
  18388. var type;
  18389. var scale;
  18390. var vector;
  18391. var prevXYZ, nextXYZ;
  18392. var prevKey, nextKey;
  18393. var object;
  18394. var animationCache;
  18395. var frame;
  18396. var JIThierarchy = this.data.JIT.hierarchy;
  18397. var currentTime, unloopedCurrentTime;
  18398. var currentPoint, forwardPoint, angle;
  18399. this.currentTime += deltaTimeMS * this.timeScale;
  18400. unloopedCurrentTime = this.currentTime;
  18401. currentTime = this.currentTime = this.currentTime % this.data.length;
  18402. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18403. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18404. object = this.hierarchy[ h ];
  18405. animationCache = object.animationCache;
  18406. // loop through pos/rot/scl
  18407. for ( var t = 0; t < 3; t ++ ) {
  18408. // get keys
  18409. type = types[ t ];
  18410. prevKey = animationCache.prevKey[ type ];
  18411. nextKey = animationCache.nextKey[ type ];
  18412. // switch keys?
  18413. if ( nextKey.time <= unloopedCurrentTime ) {
  18414. // did we loop?
  18415. if ( currentTime < unloopedCurrentTime ) {
  18416. if ( this.loop ) {
  18417. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18418. nextKey = this.getNextKeyWith( type, h, 1 );
  18419. while( nextKey.time < currentTime ) {
  18420. prevKey = nextKey;
  18421. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18422. }
  18423. } else {
  18424. this.stop();
  18425. return;
  18426. }
  18427. } else {
  18428. do {
  18429. prevKey = nextKey;
  18430. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18431. } while( nextKey.time < currentTime )
  18432. }
  18433. animationCache.prevKey[ type ] = prevKey;
  18434. animationCache.nextKey[ type ] = nextKey;
  18435. }
  18436. object.matrixAutoUpdate = true;
  18437. object.matrixWorldNeedsUpdate = true;
  18438. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18439. prevXYZ = prevKey[ type ];
  18440. nextXYZ = nextKey[ type ];
  18441. // check scale error
  18442. if ( scale < 0 || scale > 1 ) {
  18443. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18444. scale = scale < 0 ? 0 : 1;
  18445. }
  18446. // interpolate
  18447. if ( type === "pos" ) {
  18448. vector = object.position;
  18449. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18450. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18451. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18452. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18453. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18454. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18455. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18456. this.points[ 1 ] = prevXYZ;
  18457. this.points[ 2 ] = nextXYZ;
  18458. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18459. scale = scale * 0.33 + 0.33;
  18460. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18461. vector.x = currentPoint[ 0 ];
  18462. vector.y = currentPoint[ 1 ];
  18463. vector.z = currentPoint[ 2 ];
  18464. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18465. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18466. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18467. this.target.sub( vector );
  18468. this.target.y = 0;
  18469. this.target.normalize();
  18470. angle = Math.atan2( this.target.x, this.target.z );
  18471. object.rotation.set( 0, angle, 0 );
  18472. }
  18473. }
  18474. } else if ( type === "rot" ) {
  18475. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18476. } else if ( type === "scl" ) {
  18477. vector = object.scale;
  18478. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18479. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18480. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18481. }
  18482. }
  18483. }
  18484. };
  18485. // Catmull-Rom spline
  18486. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18487. var c = [], v3 = [],
  18488. point, intPoint, weight, w2, w3,
  18489. pa, pb, pc, pd;
  18490. point = ( points.length - 1 ) * scale;
  18491. intPoint = Math.floor( point );
  18492. weight = point - intPoint;
  18493. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18494. c[ 1 ] = intPoint;
  18495. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18496. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18497. pa = points[ c[ 0 ] ];
  18498. pb = points[ c[ 1 ] ];
  18499. pc = points[ c[ 2 ] ];
  18500. pd = points[ c[ 3 ] ];
  18501. w2 = weight * weight;
  18502. w3 = weight * w2;
  18503. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18504. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18505. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18506. return v3;
  18507. };
  18508. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18509. var v0 = ( p2 - p0 ) * 0.5,
  18510. v1 = ( p3 - p1 ) * 0.5;
  18511. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18512. };
  18513. // Get next key with
  18514. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18515. var keys = this.data.hierarchy[ h ].keys;
  18516. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18517. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18518. key = key < keys.length - 1 ? key : keys.length - 1;
  18519. } else {
  18520. key = key % keys.length;
  18521. }
  18522. for ( ; key < keys.length; key++ ) {
  18523. if ( keys[ key ][ type ] !== undefined ) {
  18524. return keys[ key ];
  18525. }
  18526. }
  18527. return this.data.hierarchy[ h ].keys[ 0 ];
  18528. };
  18529. // Get previous key with
  18530. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18531. var keys = this.data.hierarchy[ h ].keys;
  18532. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18533. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18534. key = key > 0 ? key : 0;
  18535. } else {
  18536. key = key >= 0 ? key : key + keys.length;
  18537. }
  18538. for ( ; key >= 0; key -- ) {
  18539. if ( keys[ key ][ type ] !== undefined ) {
  18540. return keys[ key ];
  18541. }
  18542. }
  18543. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18544. };
  18545. /**
  18546. * @author mikael emtinger / http://gomo.se/
  18547. * @author mrdoob / http://mrdoob.com/
  18548. * @author alteredq / http://alteredqualia.com/
  18549. * @author khang duong
  18550. * @author erik kitson
  18551. */
  18552. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18553. this.root = root;
  18554. this.data = THREE.AnimationHandler.get( data );
  18555. this.hierarchy = THREE.AnimationHandler.parse( root );
  18556. this.currentTime = 0;
  18557. this.timeScale = 0.001;
  18558. this.isPlaying = false;
  18559. this.isPaused = true;
  18560. this.loop = true;
  18561. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18562. // initialize to first keyframes
  18563. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18564. var keys = this.data.hierarchy[h].keys,
  18565. sids = this.data.hierarchy[h].sids,
  18566. obj = this.hierarchy[h];
  18567. if ( keys.length && sids ) {
  18568. for ( var s = 0; s < sids.length; s++ ) {
  18569. var sid = sids[ s ],
  18570. next = this.getNextKeyWith( sid, h, 0 );
  18571. if ( next ) {
  18572. next.apply( sid );
  18573. }
  18574. }
  18575. obj.matrixAutoUpdate = false;
  18576. this.data.hierarchy[h].node.updateMatrix();
  18577. obj.matrixWorldNeedsUpdate = true;
  18578. }
  18579. }
  18580. };
  18581. // Play
  18582. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18583. if( !this.isPlaying ) {
  18584. this.isPlaying = true;
  18585. this.loop = loop !== undefined ? loop : true;
  18586. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18587. this.startTimeMs = startTimeMS;
  18588. this.startTime = 10000000;
  18589. this.endTime = -this.startTime;
  18590. // reset key cache
  18591. var h, hl = this.hierarchy.length,
  18592. object,
  18593. node;
  18594. for ( h = 0; h < hl; h++ ) {
  18595. object = this.hierarchy[ h ];
  18596. node = this.data.hierarchy[ h ];
  18597. if ( node.animationCache === undefined ) {
  18598. node.animationCache = {};
  18599. node.animationCache.prevKey = null;
  18600. node.animationCache.nextKey = null;
  18601. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18602. }
  18603. var keys = this.data.hierarchy[h].keys;
  18604. if (keys.length) {
  18605. node.animationCache.prevKey = keys[ 0 ];
  18606. node.animationCache.nextKey = keys[ 1 ];
  18607. this.startTime = Math.min( keys[0].time, this.startTime );
  18608. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18609. }
  18610. }
  18611. this.update( 0 );
  18612. }
  18613. this.isPaused = false;
  18614. THREE.AnimationHandler.addToUpdate( this );
  18615. };
  18616. // Pause
  18617. THREE.KeyFrameAnimation.prototype.pause = function() {
  18618. if( this.isPaused ) {
  18619. THREE.AnimationHandler.addToUpdate( this );
  18620. } else {
  18621. THREE.AnimationHandler.removeFromUpdate( this );
  18622. }
  18623. this.isPaused = !this.isPaused;
  18624. };
  18625. // Stop
  18626. THREE.KeyFrameAnimation.prototype.stop = function() {
  18627. this.isPlaying = false;
  18628. this.isPaused = false;
  18629. THREE.AnimationHandler.removeFromUpdate( this );
  18630. // reset JIT matrix and remove cache
  18631. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18632. var obj = this.hierarchy[ h ];
  18633. var node = this.data.hierarchy[ h ];
  18634. if ( node.animationCache !== undefined ) {
  18635. var original = node.animationCache.originalMatrix;
  18636. if( obj instanceof THREE.Bone ) {
  18637. original.copy( obj.skinMatrix );
  18638. obj.skinMatrix = original;
  18639. } else {
  18640. original.copy( obj.matrix );
  18641. obj.matrix = original;
  18642. }
  18643. delete node.animationCache;
  18644. }
  18645. }
  18646. };
  18647. // Update
  18648. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18649. // early out
  18650. if( !this.isPlaying ) return;
  18651. // vars
  18652. var prevKey, nextKey;
  18653. var object;
  18654. var node;
  18655. var frame;
  18656. var JIThierarchy = this.data.JIT.hierarchy;
  18657. var currentTime, unloopedCurrentTime;
  18658. var looped;
  18659. // update
  18660. this.currentTime += deltaTimeMS * this.timeScale;
  18661. unloopedCurrentTime = this.currentTime;
  18662. currentTime = this.currentTime = this.currentTime % this.data.length;
  18663. // if looped around, the current time should be based on the startTime
  18664. if ( currentTime < this.startTimeMs ) {
  18665. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18666. }
  18667. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18668. looped = currentTime < unloopedCurrentTime;
  18669. if ( looped && !this.loop ) {
  18670. // Set the animation to the last keyframes and stop
  18671. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18672. var keys = this.data.hierarchy[h].keys,
  18673. sids = this.data.hierarchy[h].sids,
  18674. end = keys.length-1,
  18675. obj = this.hierarchy[h];
  18676. if ( keys.length ) {
  18677. for ( var s = 0; s < sids.length; s++ ) {
  18678. var sid = sids[ s ],
  18679. prev = this.getPrevKeyWith( sid, h, end );
  18680. if ( prev ) {
  18681. prev.apply( sid );
  18682. }
  18683. }
  18684. this.data.hierarchy[h].node.updateMatrix();
  18685. obj.matrixWorldNeedsUpdate = true;
  18686. }
  18687. }
  18688. this.stop();
  18689. return;
  18690. }
  18691. // check pre-infinity
  18692. if ( currentTime < this.startTime ) {
  18693. return;
  18694. }
  18695. // update
  18696. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18697. object = this.hierarchy[ h ];
  18698. node = this.data.hierarchy[ h ];
  18699. var keys = node.keys,
  18700. animationCache = node.animationCache;
  18701. // use JIT?
  18702. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18703. if( object instanceof THREE.Bone ) {
  18704. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18705. object.matrixWorldNeedsUpdate = false;
  18706. } else {
  18707. object.matrix = JIThierarchy[ h ][ frame ];
  18708. object.matrixWorldNeedsUpdate = true;
  18709. }
  18710. // use interpolation
  18711. } else if ( keys.length ) {
  18712. // make sure so original matrix and not JIT matrix is set
  18713. if ( this.JITCompile && animationCache ) {
  18714. if( object instanceof THREE.Bone ) {
  18715. object.skinMatrix = animationCache.originalMatrix;
  18716. } else {
  18717. object.matrix = animationCache.originalMatrix;
  18718. }
  18719. }
  18720. prevKey = animationCache.prevKey;
  18721. nextKey = animationCache.nextKey;
  18722. if ( prevKey && nextKey ) {
  18723. // switch keys?
  18724. if ( nextKey.time <= unloopedCurrentTime ) {
  18725. // did we loop?
  18726. if ( looped && this.loop ) {
  18727. prevKey = keys[ 0 ];
  18728. nextKey = keys[ 1 ];
  18729. while ( nextKey.time < currentTime ) {
  18730. prevKey = nextKey;
  18731. nextKey = keys[ prevKey.index + 1 ];
  18732. }
  18733. } else if ( !looped ) {
  18734. var lastIndex = keys.length - 1;
  18735. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18736. prevKey = nextKey;
  18737. nextKey = keys[ prevKey.index + 1 ];
  18738. }
  18739. }
  18740. animationCache.prevKey = prevKey;
  18741. animationCache.nextKey = nextKey;
  18742. }
  18743. if(nextKey.time >= currentTime)
  18744. prevKey.interpolate( nextKey, currentTime );
  18745. else
  18746. prevKey.interpolate( nextKey, nextKey.time);
  18747. }
  18748. this.data.hierarchy[h].node.updateMatrix();
  18749. object.matrixWorldNeedsUpdate = true;
  18750. }
  18751. }
  18752. // update JIT?
  18753. if ( this.JITCompile ) {
  18754. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18755. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18756. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18757. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18758. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18759. } else {
  18760. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18761. }
  18762. }
  18763. }
  18764. }
  18765. };
  18766. // Get next key with
  18767. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18768. var keys = this.data.hierarchy[ h ].keys;
  18769. key = key % keys.length;
  18770. for ( ; key < keys.length; key++ ) {
  18771. if ( keys[ key ].hasTarget( sid ) ) {
  18772. return keys[ key ];
  18773. }
  18774. }
  18775. return keys[ 0 ];
  18776. };
  18777. // Get previous key with
  18778. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18779. var keys = this.data.hierarchy[ h ].keys;
  18780. key = key >= 0 ? key : key + keys.length;
  18781. for ( ; key >= 0; key-- ) {
  18782. if ( keys[ key ].hasTarget( sid ) ) {
  18783. return keys[ key ];
  18784. }
  18785. }
  18786. return keys[ keys.length - 1 ];
  18787. };
  18788. /**
  18789. * Camera for rendering cube maps
  18790. * - renders scene into axis-aligned cube
  18791. *
  18792. * @author alteredq / http://alteredqualia.com/
  18793. */
  18794. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18795. THREE.Object3D.call( this );
  18796. var fov = 90, aspect = 1;
  18797. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18798. cameraPX.up.set( 0, -1, 0 );
  18799. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18800. this.add( cameraPX );
  18801. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18802. cameraNX.up.set( 0, -1, 0 );
  18803. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18804. this.add( cameraNX );
  18805. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18806. cameraPY.up.set( 0, 0, 1 );
  18807. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18808. this.add( cameraPY );
  18809. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18810. cameraNY.up.set( 0, 0, -1 );
  18811. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18812. this.add( cameraNY );
  18813. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18814. cameraPZ.up.set( 0, -1, 0 );
  18815. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18816. this.add( cameraPZ );
  18817. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18818. cameraNZ.up.set( 0, -1, 0 );
  18819. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18820. this.add( cameraNZ );
  18821. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18822. this.updateCubeMap = function ( renderer, scene ) {
  18823. var renderTarget = this.renderTarget;
  18824. var generateMipmaps = renderTarget.generateMipmaps;
  18825. renderTarget.generateMipmaps = false;
  18826. renderTarget.activeCubeFace = 0;
  18827. renderer.render( scene, cameraPX, renderTarget );
  18828. renderTarget.activeCubeFace = 1;
  18829. renderer.render( scene, cameraNX, renderTarget );
  18830. renderTarget.activeCubeFace = 2;
  18831. renderer.render( scene, cameraPY, renderTarget );
  18832. renderTarget.activeCubeFace = 3;
  18833. renderer.render( scene, cameraNY, renderTarget );
  18834. renderTarget.activeCubeFace = 4;
  18835. renderer.render( scene, cameraPZ, renderTarget );
  18836. renderTarget.generateMipmaps = generateMipmaps;
  18837. renderTarget.activeCubeFace = 5;
  18838. renderer.render( scene, cameraNZ, renderTarget );
  18839. };
  18840. };
  18841. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18842. /*
  18843. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18844. *
  18845. * A general perpose camera, for setting FOV, Lens Focal Length,
  18846. * and switching between perspective and orthographic views easily.
  18847. * Use this only if you do not wish to manage
  18848. * both a Orthographic and Perspective Camera
  18849. *
  18850. */
  18851. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18852. THREE.Camera.call( this );
  18853. this.fov = fov;
  18854. this.left = -width / 2;
  18855. this.right = width / 2
  18856. this.top = height / 2;
  18857. this.bottom = -height / 2;
  18858. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18859. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18860. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18861. this.zoom = 1;
  18862. this.toPerspective();
  18863. var aspect = width/height;
  18864. };
  18865. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18866. THREE.CombinedCamera.prototype.toPerspective = function () {
  18867. // Switches to the Perspective Camera
  18868. this.near = this.cameraP.near;
  18869. this.far = this.cameraP.far;
  18870. this.cameraP.fov = this.fov / this.zoom ;
  18871. this.cameraP.updateProjectionMatrix();
  18872. this.projectionMatrix = this.cameraP.projectionMatrix;
  18873. this.inPerspectiveMode = true;
  18874. this.inOrthographicMode = false;
  18875. };
  18876. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18877. // Switches to the Orthographic camera estimating viewport from Perspective
  18878. var fov = this.fov;
  18879. var aspect = this.cameraP.aspect;
  18880. var near = this.cameraP.near;
  18881. var far = this.cameraP.far;
  18882. // The size that we set is the mid plane of the viewing frustum
  18883. var hyperfocus = ( near + far ) / 2;
  18884. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18885. var planeHeight = 2 * halfHeight;
  18886. var planeWidth = planeHeight * aspect;
  18887. var halfWidth = planeWidth / 2;
  18888. halfHeight /= this.zoom;
  18889. halfWidth /= this.zoom;
  18890. this.cameraO.left = -halfWidth;
  18891. this.cameraO.right = halfWidth;
  18892. this.cameraO.top = halfHeight;
  18893. this.cameraO.bottom = -halfHeight;
  18894. // this.cameraO.left = -farHalfWidth;
  18895. // this.cameraO.right = farHalfWidth;
  18896. // this.cameraO.top = farHalfHeight;
  18897. // this.cameraO.bottom = -farHalfHeight;
  18898. // this.cameraO.left = this.left / this.zoom;
  18899. // this.cameraO.right = this.right / this.zoom;
  18900. // this.cameraO.top = this.top / this.zoom;
  18901. // this.cameraO.bottom = this.bottom / this.zoom;
  18902. this.cameraO.updateProjectionMatrix();
  18903. this.near = this.cameraO.near;
  18904. this.far = this.cameraO.far;
  18905. this.projectionMatrix = this.cameraO.projectionMatrix;
  18906. this.inPerspectiveMode = false;
  18907. this.inOrthographicMode = true;
  18908. };
  18909. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18910. this.cameraP.aspect = width / height;
  18911. this.left = -width / 2;
  18912. this.right = width / 2
  18913. this.top = height / 2;
  18914. this.bottom = -height / 2;
  18915. };
  18916. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18917. this.fov = fov;
  18918. if ( this.inPerspectiveMode ) {
  18919. this.toPerspective();
  18920. } else {
  18921. this.toOrthographic();
  18922. }
  18923. };
  18924. // For mantaining similar API with PerspectiveCamera
  18925. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18926. if ( this.inPerspectiveMode ) {
  18927. this.toPerspective();
  18928. } else {
  18929. this.toPerspective();
  18930. this.toOrthographic();
  18931. }
  18932. };
  18933. /*
  18934. * Uses Focal Length (in mm) to estimate and set FOV
  18935. * 35mm (fullframe) camera is used if frame size is not specified;
  18936. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18937. */
  18938. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18939. if ( frameHeight === undefined ) frameHeight = 24;
  18940. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18941. this.setFov( fov );
  18942. return fov;
  18943. };
  18944. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18945. this.zoom = zoom;
  18946. if ( this.inPerspectiveMode ) {
  18947. this.toPerspective();
  18948. } else {
  18949. this.toOrthographic();
  18950. }
  18951. };
  18952. THREE.CombinedCamera.prototype.toFrontView = function() {
  18953. this.rotation.x = 0;
  18954. this.rotation.y = 0;
  18955. this.rotation.z = 0;
  18956. // should we be modifing the matrix instead?
  18957. this.rotationAutoUpdate = false;
  18958. };
  18959. THREE.CombinedCamera.prototype.toBackView = function() {
  18960. this.rotation.x = 0;
  18961. this.rotation.y = Math.PI;
  18962. this.rotation.z = 0;
  18963. this.rotationAutoUpdate = false;
  18964. };
  18965. THREE.CombinedCamera.prototype.toLeftView = function() {
  18966. this.rotation.x = 0;
  18967. this.rotation.y = - Math.PI / 2;
  18968. this.rotation.z = 0;
  18969. this.rotationAutoUpdate = false;
  18970. };
  18971. THREE.CombinedCamera.prototype.toRightView = function() {
  18972. this.rotation.x = 0;
  18973. this.rotation.y = Math.PI / 2;
  18974. this.rotation.z = 0;
  18975. this.rotationAutoUpdate = false;
  18976. };
  18977. THREE.CombinedCamera.prototype.toTopView = function() {
  18978. this.rotation.x = - Math.PI / 2;
  18979. this.rotation.y = 0;
  18980. this.rotation.z = 0;
  18981. this.rotationAutoUpdate = false;
  18982. };
  18983. THREE.CombinedCamera.prototype.toBottomView = function() {
  18984. this.rotation.x = Math.PI / 2;
  18985. this.rotation.y = 0;
  18986. this.rotation.z = 0;
  18987. this.rotationAutoUpdate = false;
  18988. };
  18989. /**
  18990. * @author hughes
  18991. */
  18992. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18993. THREE.Geometry.call( this );
  18994. radius = radius || 50;
  18995. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18996. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18997. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18998. var i, uvs = [],
  18999. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  19000. this.vertices.push(center);
  19001. uvs.push( centerUV );
  19002. for ( i = 0; i <= segments; i ++ ) {
  19003. var vertex = new THREE.Vector3();
  19004. var segment = thetaStart + i / segments * thetaLength;
  19005. vertex.x = radius * Math.cos( segment );
  19006. vertex.y = radius * Math.sin( segment );
  19007. this.vertices.push( vertex );
  19008. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  19009. }
  19010. var n = new THREE.Vector3( 0, 0, 1 );
  19011. for ( i = 1; i <= segments; i ++ ) {
  19012. var v1 = i;
  19013. var v2 = i + 1 ;
  19014. var v3 = 0;
  19015. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19016. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  19017. }
  19018. this.computeCentroids();
  19019. this.computeFaceNormals();
  19020. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19021. };
  19022. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19023. /**
  19024. * @author mrdoob / http://mrdoob.com/
  19025. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19026. */
  19027. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19028. THREE.Geometry.call( this );
  19029. var scope = this;
  19030. this.width = width;
  19031. this.height = height;
  19032. this.depth = depth;
  19033. this.widthSegments = widthSegments || 1;
  19034. this.heightSegments = heightSegments || 1;
  19035. this.depthSegments = depthSegments || 1;
  19036. var width_half = this.width / 2;
  19037. var height_half = this.height / 2;
  19038. var depth_half = this.depth / 2;
  19039. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  19040. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  19041. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  19042. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  19043. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  19044. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  19045. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19046. var w, ix, iy,
  19047. gridX = scope.widthSegments,
  19048. gridY = scope.heightSegments,
  19049. width_half = width / 2,
  19050. height_half = height / 2,
  19051. offset = scope.vertices.length;
  19052. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19053. w = 'z';
  19054. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19055. w = 'y';
  19056. gridY = scope.depthSegments;
  19057. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19058. w = 'x';
  19059. gridX = scope.depthSegments;
  19060. }
  19061. var gridX1 = gridX + 1,
  19062. gridY1 = gridY + 1,
  19063. segment_width = width / gridX,
  19064. segment_height = height / gridY,
  19065. normal = new THREE.Vector3();
  19066. normal[ w ] = depth > 0 ? 1 : - 1;
  19067. for ( iy = 0; iy < gridY1; iy ++ ) {
  19068. for ( ix = 0; ix < gridX1; ix ++ ) {
  19069. var vector = new THREE.Vector3();
  19070. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19071. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19072. vector[ w ] = depth;
  19073. scope.vertices.push( vector );
  19074. }
  19075. }
  19076. for ( iy = 0; iy < gridY; iy++ ) {
  19077. for ( ix = 0; ix < gridX; ix++ ) {
  19078. var a = ix + gridX1 * iy;
  19079. var b = ix + gridX1 * ( iy + 1 );
  19080. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19081. var d = ( ix + 1 ) + gridX1 * iy;
  19082. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  19083. face.normal.copy( normal );
  19084. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19085. face.materialIndex = materialIndex;
  19086. scope.faces.push( face );
  19087. scope.faceVertexUvs[ 0 ].push( [
  19088. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  19089. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  19090. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  19091. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  19092. ] );
  19093. }
  19094. }
  19095. }
  19096. this.computeCentroids();
  19097. this.mergeVertices();
  19098. };
  19099. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19100. /**
  19101. * @author mrdoob / http://mrdoob.com/
  19102. */
  19103. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19104. THREE.Geometry.call( this );
  19105. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19106. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19107. this.height = height = height !== undefined ? height : 100;
  19108. this.radialSegments = radialSegments = radialSegments || 8;
  19109. this.heightSegments = heightSegments = heightSegments || 1;
  19110. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  19111. var heightHalf = height / 2;
  19112. var x, y, vertices = [], uvs = [];
  19113. for ( y = 0; y <= heightSegments; y ++ ) {
  19114. var verticesRow = [];
  19115. var uvsRow = [];
  19116. var v = y / heightSegments;
  19117. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19118. for ( x = 0; x <= radialSegments; x ++ ) {
  19119. var u = x / radialSegments;
  19120. var vertex = new THREE.Vector3();
  19121. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19122. vertex.y = - v * height + heightHalf;
  19123. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19124. this.vertices.push( vertex );
  19125. verticesRow.push( this.vertices.length - 1 );
  19126. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19127. }
  19128. vertices.push( verticesRow );
  19129. uvs.push( uvsRow );
  19130. }
  19131. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19132. var na, nb;
  19133. for ( x = 0; x < radialSegments; x ++ ) {
  19134. if ( radiusTop !== 0 ) {
  19135. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19136. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19137. } else {
  19138. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19139. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19140. }
  19141. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19142. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19143. for ( y = 0; y < heightSegments; y ++ ) {
  19144. var v1 = vertices[ y ][ x ];
  19145. var v2 = vertices[ y + 1 ][ x ];
  19146. var v3 = vertices[ y + 1 ][ x + 1 ];
  19147. var v4 = vertices[ y ][ x + 1 ];
  19148. var n1 = na.clone();
  19149. var n2 = na.clone();
  19150. var n3 = nb.clone();
  19151. var n4 = nb.clone();
  19152. var uv1 = uvs[ y ][ x ].clone();
  19153. var uv2 = uvs[ y + 1 ][ x ].clone();
  19154. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19155. var uv4 = uvs[ y ][ x + 1 ].clone();
  19156. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19157. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19158. }
  19159. }
  19160. // top cap
  19161. if ( openEnded === false && radiusTop > 0 ) {
  19162. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19163. for ( x = 0; x < radialSegments; x ++ ) {
  19164. var v1 = vertices[ 0 ][ x ];
  19165. var v2 = vertices[ 0 ][ x + 1 ];
  19166. var v3 = this.vertices.length - 1;
  19167. var n1 = new THREE.Vector3( 0, 1, 0 );
  19168. var n2 = new THREE.Vector3( 0, 1, 0 );
  19169. var n3 = new THREE.Vector3( 0, 1, 0 );
  19170. var uv1 = uvs[ 0 ][ x ].clone();
  19171. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19172. var uv3 = new THREE.Vector2( uv2.u, 0 );
  19173. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19174. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19175. }
  19176. }
  19177. // bottom cap
  19178. if ( openEnded === false && radiusBottom > 0 ) {
  19179. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19180. for ( x = 0; x < radialSegments; x ++ ) {
  19181. var v1 = vertices[ y ][ x + 1 ];
  19182. var v2 = vertices[ y ][ x ];
  19183. var v3 = this.vertices.length - 1;
  19184. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19185. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19186. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19187. var uv1 = uvs[ y ][ x + 1 ].clone();
  19188. var uv2 = uvs[ y ][ x ].clone();
  19189. var uv3 = new THREE.Vector2( uv2.u, 1 );
  19190. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19191. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19192. }
  19193. }
  19194. this.computeCentroids();
  19195. this.computeFaceNormals();
  19196. }
  19197. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19198. /**
  19199. * @author zz85 / http://www.lab4games.net/zz85/blog
  19200. *
  19201. * Creates extruded geometry from a path shape.
  19202. *
  19203. * parameters = {
  19204. *
  19205. * size: <float>, // size of the text
  19206. * height: <float>, // thickness to extrude text
  19207. * curveSegments: <int>, // number of points on the curves
  19208. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19209. * amount: <int>, // Amount
  19210. *
  19211. * bevelEnabled: <bool>, // turn on bevel
  19212. * bevelThickness: <float>, // how deep into text bevel goes
  19213. * bevelSize: <float>, // how far from text outline is bevel
  19214. * bevelSegments: <int>, // number of bevel layers
  19215. *
  19216. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19217. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19218. *
  19219. * material: <int> // material index for front and back faces
  19220. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19221. * uvGenerator: <Object> // object that provides UV generator functions
  19222. *
  19223. * }
  19224. **/
  19225. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19226. if ( typeof( shapes ) === "undefined" ) {
  19227. shapes = [];
  19228. return;
  19229. }
  19230. THREE.Geometry.call( this );
  19231. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19232. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19233. this.addShapeList( shapes, options );
  19234. this.computeCentroids();
  19235. this.computeFaceNormals();
  19236. // can't really use automatic vertex normals
  19237. // as then front and back sides get smoothed too
  19238. // should do separate smoothing just for sides
  19239. //this.computeVertexNormals();
  19240. //console.log( "took", ( Date.now() - startTime ) );
  19241. };
  19242. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19243. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19244. var sl = shapes.length;
  19245. for ( var s = 0; s < sl; s ++ ) {
  19246. var shape = shapes[ s ];
  19247. this.addShape( shape, options );
  19248. }
  19249. };
  19250. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19251. var amount = options.amount !== undefined ? options.amount : 100;
  19252. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19253. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19254. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19255. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19256. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19257. var steps = options.steps !== undefined ? options.steps : 1;
  19258. var extrudePath = options.extrudePath;
  19259. var extrudePts, extrudeByPath = false;
  19260. var material = options.material;
  19261. var extrudeMaterial = options.extrudeMaterial;
  19262. // Use default WorldUVGenerator if no UV generators are specified.
  19263. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19264. var shapebb = this.shapebb;
  19265. //shapebb = shape.getBoundingBox();
  19266. var splineTube, binormal, normal, position2;
  19267. if ( extrudePath ) {
  19268. extrudePts = extrudePath.getSpacedPoints( steps );
  19269. extrudeByPath = true;
  19270. bevelEnabled = false; // bevels not supported for path extrusion
  19271. // SETUP TNB variables
  19272. // Reuse TNB from TubeGeomtry for now.
  19273. // TODO1 - have a .isClosed in spline?
  19274. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19275. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19276. binormal = new THREE.Vector3();
  19277. normal = new THREE.Vector3();
  19278. position2 = new THREE.Vector3();
  19279. }
  19280. // Safeguards if bevels are not enabled
  19281. if ( ! bevelEnabled ) {
  19282. bevelSegments = 0;
  19283. bevelThickness = 0;
  19284. bevelSize = 0;
  19285. }
  19286. // Variables initalization
  19287. var ahole, h, hl; // looping of holes
  19288. var scope = this;
  19289. var bevelPoints = [];
  19290. var shapesOffset = this.vertices.length;
  19291. var shapePoints = shape.extractPoints( curveSegments );
  19292. var vertices = shapePoints.shape;
  19293. var holes = shapePoints.holes;
  19294. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19295. if ( reverse ) {
  19296. vertices = vertices.reverse();
  19297. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19298. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19299. ahole = holes[ h ];
  19300. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19301. holes[ h ] = ahole.reverse();
  19302. }
  19303. }
  19304. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19305. }
  19306. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19307. /* Vertices */
  19308. var contour = vertices; // vertices has all points but contour has only points of circumference
  19309. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19310. ahole = holes[ h ];
  19311. vertices = vertices.concat( ahole );
  19312. }
  19313. function scalePt2 ( pt, vec, size ) {
  19314. if ( !vec ) console.log( "die" );
  19315. return vec.clone().multiplyScalar( size ).add( pt );
  19316. }
  19317. var b, bs, t, z,
  19318. vert, vlen = vertices.length,
  19319. face, flen = faces.length,
  19320. cont, clen = contour.length;
  19321. // Find directions for point movement
  19322. var RAD_TO_DEGREES = 180 / Math.PI;
  19323. function getBevelVec( pt_i, pt_j, pt_k ) {
  19324. // Algorithm 2
  19325. return getBevelVec2( pt_i, pt_j, pt_k );
  19326. }
  19327. function getBevelVec1( pt_i, pt_j, pt_k ) {
  19328. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  19329. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  19330. if ( anglea > angleb ) {
  19331. angleb += Math.PI * 2;
  19332. }
  19333. var anglec = ( anglea + angleb ) / 2;
  19334. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  19335. var x = - Math.cos( anglec );
  19336. var y = - Math.sin( anglec );
  19337. var vec = new THREE.Vector2( x, y ); //.normalize();
  19338. return vec;
  19339. }
  19340. function getBevelVec2( pt_i, pt_j, pt_k ) {
  19341. var a = THREE.ExtrudeGeometry.__v1,
  19342. b = THREE.ExtrudeGeometry.__v2,
  19343. v_hat = THREE.ExtrudeGeometry.__v3,
  19344. w_hat = THREE.ExtrudeGeometry.__v4,
  19345. p = THREE.ExtrudeGeometry.__v5,
  19346. q = THREE.ExtrudeGeometry.__v6,
  19347. v, w,
  19348. v_dot_w_hat, q_sub_p_dot_w_hat,
  19349. s, intersection;
  19350. // good reading for line-line intersection
  19351. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  19352. // define a as vector j->i
  19353. // define b as vectot k->i
  19354. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  19355. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  19356. // get unit vectors
  19357. v = a.normalize();
  19358. w = b.normalize();
  19359. // normals from pt i
  19360. v_hat.set( -v.y, v.x );
  19361. w_hat.set( w.y, -w.x );
  19362. // pts from i
  19363. p.copy( pt_i ).add( v_hat );
  19364. q.copy( pt_i ).add( w_hat );
  19365. if ( p.equals( q ) ) {
  19366. //console.log("Warning: lines are straight");
  19367. return w_hat.clone();
  19368. }
  19369. // Points from j, k. helps prevents points cross overover most of the time
  19370. p.copy( pt_j ).add( v_hat );
  19371. q.copy( pt_k ).add( w_hat );
  19372. v_dot_w_hat = v.dot( w_hat );
  19373. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  19374. // We should not reach these conditions
  19375. if ( v_dot_w_hat === 0 ) {
  19376. console.log( "Either infinite or no solutions!" );
  19377. if ( q_sub_p_dot_w_hat === 0 ) {
  19378. console.log( "Its finite solutions." );
  19379. } else {
  19380. console.log( "Too bad, no solutions." );
  19381. }
  19382. }
  19383. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19384. if ( s < 0 ) {
  19385. // in case of emergecy, revert to algorithm 1.
  19386. return getBevelVec1( pt_i, pt_j, pt_k );
  19387. }
  19388. intersection = v.multiplyScalar( s ).add( p );
  19389. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19390. }
  19391. var contourMovements = [];
  19392. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19393. if ( j === il ) j = 0;
  19394. if ( k === il ) k = 0;
  19395. // (j)---(i)---(k)
  19396. // console.log('i,j,k', i, j , k)
  19397. var pt_i = contour[ i ];
  19398. var pt_j = contour[ j ];
  19399. var pt_k = contour[ k ];
  19400. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19401. }
  19402. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19403. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19404. ahole = holes[ h ];
  19405. oneHoleMovements = [];
  19406. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19407. if ( j === il ) j = 0;
  19408. if ( k === il ) k = 0;
  19409. // (j)---(i)---(k)
  19410. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19411. }
  19412. holesMovements.push( oneHoleMovements );
  19413. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19414. }
  19415. // Loop bevelSegments, 1 for the front, 1 for the back
  19416. for ( b = 0; b < bevelSegments; b ++ ) {
  19417. //for ( b = bevelSegments; b > 0; b -- ) {
  19418. t = b / bevelSegments;
  19419. z = bevelThickness * ( 1 - t );
  19420. //z = bevelThickness * t;
  19421. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19422. //bs = bevelSize * t ; // linear
  19423. // contract shape
  19424. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19425. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19426. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19427. v( vert.x, vert.y, - z );
  19428. }
  19429. // expand holes
  19430. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19431. ahole = holes[ h ];
  19432. oneHoleMovements = holesMovements[ h ];
  19433. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19434. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19435. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19436. v( vert.x, vert.y, -z );
  19437. }
  19438. }
  19439. }
  19440. bs = bevelSize;
  19441. // Back facing vertices
  19442. for ( i = 0; i < vlen; i ++ ) {
  19443. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19444. if ( !extrudeByPath ) {
  19445. v( vert.x, vert.y, 0 );
  19446. } else {
  19447. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19448. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19449. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19450. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19451. v( position2.x, position2.y, position2.z );
  19452. }
  19453. }
  19454. // Add stepped vertices...
  19455. // Including front facing vertices
  19456. var s;
  19457. for ( s = 1; s <= steps; s ++ ) {
  19458. for ( i = 0; i < vlen; i ++ ) {
  19459. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19460. if ( !extrudeByPath ) {
  19461. v( vert.x, vert.y, amount / steps * s );
  19462. } else {
  19463. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19464. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19465. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19466. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19467. v( position2.x, position2.y, position2.z );
  19468. }
  19469. }
  19470. }
  19471. // Add bevel segments planes
  19472. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19473. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19474. t = b / bevelSegments;
  19475. z = bevelThickness * ( 1 - t );
  19476. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19477. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19478. // contract shape
  19479. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19480. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19481. v( vert.x, vert.y, amount + z );
  19482. }
  19483. // expand holes
  19484. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19485. ahole = holes[ h ];
  19486. oneHoleMovements = holesMovements[ h ];
  19487. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19488. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19489. if ( !extrudeByPath ) {
  19490. v( vert.x, vert.y, amount + z );
  19491. } else {
  19492. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19493. }
  19494. }
  19495. }
  19496. }
  19497. /* Faces */
  19498. // Top and bottom faces
  19499. buildLidFaces();
  19500. // Sides faces
  19501. buildSideFaces();
  19502. ///// Internal functions
  19503. function buildLidFaces() {
  19504. if ( bevelEnabled ) {
  19505. var layer = 0 ; // steps + 1
  19506. var offset = vlen * layer;
  19507. // Bottom faces
  19508. for ( i = 0; i < flen; i ++ ) {
  19509. face = faces[ i ];
  19510. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19511. }
  19512. layer = steps + bevelSegments * 2;
  19513. offset = vlen * layer;
  19514. // Top faces
  19515. for ( i = 0; i < flen; i ++ ) {
  19516. face = faces[ i ];
  19517. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19518. }
  19519. } else {
  19520. // Bottom faces
  19521. for ( i = 0; i < flen; i++ ) {
  19522. face = faces[ i ];
  19523. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19524. }
  19525. // Top faces
  19526. for ( i = 0; i < flen; i ++ ) {
  19527. face = faces[ i ];
  19528. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19529. }
  19530. }
  19531. }
  19532. // Create faces for the z-sides of the shape
  19533. function buildSideFaces() {
  19534. var layeroffset = 0;
  19535. sidewalls( contour, layeroffset );
  19536. layeroffset += contour.length;
  19537. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19538. ahole = holes[ h ];
  19539. sidewalls( ahole, layeroffset );
  19540. //, true
  19541. layeroffset += ahole.length;
  19542. }
  19543. }
  19544. function sidewalls( contour, layeroffset ) {
  19545. var j, k;
  19546. i = contour.length;
  19547. while ( --i >= 0 ) {
  19548. j = i;
  19549. k = i - 1;
  19550. if ( k < 0 ) k = contour.length - 1;
  19551. //console.log('b', i,j, i-1, k,vertices.length);
  19552. var s = 0, sl = steps + bevelSegments * 2;
  19553. for ( s = 0; s < sl; s ++ ) {
  19554. var slen1 = vlen * s;
  19555. var slen2 = vlen * ( s + 1 );
  19556. var a = layeroffset + j + slen1,
  19557. b = layeroffset + k + slen1,
  19558. c = layeroffset + k + slen2,
  19559. d = layeroffset + j + slen2;
  19560. f4( a, b, c, d, contour, s, sl, j, k );
  19561. }
  19562. }
  19563. }
  19564. function v( x, y, z ) {
  19565. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19566. }
  19567. function f3( a, b, c, isBottom ) {
  19568. a += shapesOffset;
  19569. b += shapesOffset;
  19570. c += shapesOffset;
  19571. // normal, color, material
  19572. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19573. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19574. scope.faceVertexUvs[ 0 ].push( uvs );
  19575. }
  19576. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19577. a += shapesOffset;
  19578. b += shapesOffset;
  19579. c += shapesOffset;
  19580. d += shapesOffset;
  19581. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19582. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19583. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19584. scope.faceVertexUvs[ 0 ].push( uvs );
  19585. }
  19586. };
  19587. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19588. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19589. var ax = geometry.vertices[ indexA ].x,
  19590. ay = geometry.vertices[ indexA ].y,
  19591. bx = geometry.vertices[ indexB ].x,
  19592. by = geometry.vertices[ indexB ].y,
  19593. cx = geometry.vertices[ indexC ].x,
  19594. cy = geometry.vertices[ indexC ].y;
  19595. return [
  19596. new THREE.Vector2( ax, ay ),
  19597. new THREE.Vector2( bx, by ),
  19598. new THREE.Vector2( cx, cy )
  19599. ];
  19600. },
  19601. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19602. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19603. },
  19604. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19605. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19606. contourIndex1, contourIndex2 ) {
  19607. var ax = geometry.vertices[ indexA ].x,
  19608. ay = geometry.vertices[ indexA ].y,
  19609. az = geometry.vertices[ indexA ].z,
  19610. bx = geometry.vertices[ indexB ].x,
  19611. by = geometry.vertices[ indexB ].y,
  19612. bz = geometry.vertices[ indexB ].z,
  19613. cx = geometry.vertices[ indexC ].x,
  19614. cy = geometry.vertices[ indexC ].y,
  19615. cz = geometry.vertices[ indexC ].z,
  19616. dx = geometry.vertices[ indexD ].x,
  19617. dy = geometry.vertices[ indexD ].y,
  19618. dz = geometry.vertices[ indexD ].z;
  19619. if ( Math.abs( ay - by ) < 0.01 ) {
  19620. return [
  19621. new THREE.Vector2( ax, 1 - az ),
  19622. new THREE.Vector2( bx, 1 - bz ),
  19623. new THREE.Vector2( cx, 1 - cz ),
  19624. new THREE.Vector2( dx, 1 - dz )
  19625. ];
  19626. } else {
  19627. return [
  19628. new THREE.Vector2( ay, 1 - az ),
  19629. new THREE.Vector2( by, 1 - bz ),
  19630. new THREE.Vector2( cy, 1 - cz ),
  19631. new THREE.Vector2( dy, 1 - dz )
  19632. ];
  19633. }
  19634. }
  19635. };
  19636. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19637. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19638. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19639. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19640. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19641. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19642. /**
  19643. * @author jonobr1 / http://jonobr1.com
  19644. *
  19645. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19646. * ExtrudeGeometry.
  19647. *
  19648. * parameters = {
  19649. *
  19650. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19651. *
  19652. * material: <int> // material index for front and back faces
  19653. * uvGenerator: <Object> // object that provides UV generator functions
  19654. *
  19655. * }
  19656. **/
  19657. THREE.ShapeGeometry = function ( shapes, options ) {
  19658. THREE.Geometry.call( this );
  19659. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19660. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19661. this.addShapeList( shapes, options );
  19662. this.computeCentroids();
  19663. this.computeFaceNormals();
  19664. };
  19665. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19666. /**
  19667. * Add an array of shapes to THREE.ShapeGeometry.
  19668. */
  19669. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19670. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19671. this.addShape( shapes[ i ], options );
  19672. }
  19673. return this;
  19674. };
  19675. /**
  19676. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19677. */
  19678. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19679. if ( options === undefined ) options = {};
  19680. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19681. var material = options.material;
  19682. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19683. var shapebb = this.shapebb;
  19684. //
  19685. var i, l, hole, s;
  19686. var shapesOffset = this.vertices.length;
  19687. var shapePoints = shape.extractPoints( curveSegments );
  19688. var vertices = shapePoints.shape;
  19689. var holes = shapePoints.holes;
  19690. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19691. if ( reverse ) {
  19692. vertices = vertices.reverse();
  19693. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19694. for ( i = 0, l = holes.length; i < l; i++ ) {
  19695. hole = holes[ i ];
  19696. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19697. holes[ i ] = hole.reverse();
  19698. }
  19699. }
  19700. reverse = false;
  19701. }
  19702. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19703. // Vertices
  19704. var contour = vertices;
  19705. for ( i = 0, l = holes.length; i < l; i++ ) {
  19706. hole = holes[ i ];
  19707. vertices = vertices.concat( hole );
  19708. }
  19709. //
  19710. var vert, vlen = vertices.length;
  19711. var face, flen = faces.length;
  19712. var cont, clen = contour.length;
  19713. for ( i = 0; i < vlen; i++ ) {
  19714. vert = vertices[ i ];
  19715. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19716. }
  19717. for ( i = 0; i < flen; i++ ) {
  19718. face = faces[ i ];
  19719. var a = face[ 0 ] + shapesOffset;
  19720. var b = face[ 1 ] + shapesOffset;
  19721. var c = face[ 2 ] + shapesOffset;
  19722. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19723. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19724. }
  19725. };
  19726. /**
  19727. * @author astrodud / http://astrodud.isgreat.org/
  19728. * @author zz85 / https://github.com/zz85
  19729. * @author bhouston / http://exocortex.com
  19730. */
  19731. // points - to create a closed torus, one must use a set of points
  19732. // like so: [ a, b, c, d, a ], see first is the same as last.
  19733. // segments - the number of circumference segments to create
  19734. // phiStart - the starting radian
  19735. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19736. // 2*pi is a closed lathe, less than 2PI is a portion.
  19737. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19738. THREE.Geometry.call( this );
  19739. segments = segments || 12;
  19740. phiStart = phiStart || 0;
  19741. phiLength = phiLength || 2 * Math.PI;
  19742. var inversePointLength = 1.0 / ( points.length - 1 );
  19743. var inverseSegments = 1.0 / segments;
  19744. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19745. var phi = phiStart + i * inverseSegments * phiLength;
  19746. var c = Math.cos( phi ),
  19747. s = Math.sin( phi );
  19748. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19749. var pt = points[ j ];
  19750. var vertex = new THREE.Vector3();
  19751. vertex.x = c * pt.x - s * pt.y;
  19752. vertex.y = s * pt.x + c * pt.y;
  19753. vertex.z = pt.z;
  19754. this.vertices.push( vertex );
  19755. }
  19756. }
  19757. var np = points.length;
  19758. for ( var i = 0, il = segments; i < il; i ++ ) {
  19759. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19760. var base = j + np * i;
  19761. var a = base;
  19762. var b = base + np;
  19763. var c = base + 1 + np;
  19764. var d = base + 1;
  19765. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19766. var u0 = i * inverseSegments;
  19767. var v0 = j * inversePointLength;
  19768. var u1 = u0 + inverseSegments;
  19769. var v1 = v0 + inversePointLength;
  19770. this.faceVertexUvs[ 0 ].push( [
  19771. new THREE.Vector2( u0, v0 ),
  19772. new THREE.Vector2( u1, v0 ),
  19773. new THREE.Vector2( u1, v1 ),
  19774. new THREE.Vector2( u0, v1 )
  19775. ] );
  19776. }
  19777. }
  19778. this.mergeVertices();
  19779. this.computeCentroids();
  19780. this.computeFaceNormals();
  19781. this.computeVertexNormals();
  19782. };
  19783. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19784. /**
  19785. * @author mrdoob / http://mrdoob.com/
  19786. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19787. */
  19788. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19789. THREE.Geometry.call( this );
  19790. this.width = width;
  19791. this.height = height;
  19792. this.widthSegments = widthSegments || 1;
  19793. this.heightSegments = heightSegments || 1;
  19794. var ix, iz;
  19795. var width_half = width / 2;
  19796. var height_half = height / 2;
  19797. var gridX = this.widthSegments;
  19798. var gridZ = this.heightSegments;
  19799. var gridX1 = gridX + 1;
  19800. var gridZ1 = gridZ + 1;
  19801. var segment_width = this.width / gridX;
  19802. var segment_height = this.height / gridZ;
  19803. var normal = new THREE.Vector3( 0, 0, 1 );
  19804. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19805. for ( ix = 0; ix < gridX1; ix ++ ) {
  19806. var x = ix * segment_width - width_half;
  19807. var y = iz * segment_height - height_half;
  19808. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19809. }
  19810. }
  19811. for ( iz = 0; iz < gridZ; iz ++ ) {
  19812. for ( ix = 0; ix < gridX; ix ++ ) {
  19813. var a = ix + gridX1 * iz;
  19814. var b = ix + gridX1 * ( iz + 1 );
  19815. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19816. var d = ( ix + 1 ) + gridX1 * iz;
  19817. var face = new THREE.Face4( a, b, c, d );
  19818. face.normal.copy( normal );
  19819. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19820. this.faces.push( face );
  19821. this.faceVertexUvs[ 0 ].push( [
  19822. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19823. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19824. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19825. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19826. ] );
  19827. }
  19828. }
  19829. this.computeCentroids();
  19830. };
  19831. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19832. /**
  19833. * @author Kaleb Murphy
  19834. */
  19835. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19836. THREE.Geometry.call( this );
  19837. innerRadius = innerRadius || 0;
  19838. outerRadius = outerRadius || 50;
  19839. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19840. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19841. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19842. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19843. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19844. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19845. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19846. var vertex = new THREE.Vector3();
  19847. var segment = thetaStart + o / thetaSegments * thetaLength;
  19848. vertex.x = radius * Math.cos( segment );
  19849. vertex.y = radius * Math.sin( segment );
  19850. this.vertices.push( vertex );
  19851. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19852. }
  19853. radius += radiusStep;
  19854. }
  19855. var n = new THREE.Vector3( 0, 0, 1 );
  19856. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19857. var thetaSegment = i * thetaSegments;
  19858. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19859. var segment = o + thetaSegment;
  19860. var v1 = segment + i;
  19861. var v2 = segment + thetaSegments + i;
  19862. var v3 = segment + thetaSegments + 1 + i;
  19863. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19864. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19865. v1 = segment + i;
  19866. v2 = segment + thetaSegments + 1 + i;
  19867. v3 = segment + 1 + i;
  19868. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19869. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19870. }
  19871. }
  19872. this.computeCentroids();
  19873. this.computeFaceNormals();
  19874. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19875. };
  19876. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19877. /**
  19878. * @author mrdoob / http://mrdoob.com/
  19879. */
  19880. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19881. THREE.Geometry.call( this );
  19882. this.radius = radius = radius || 50;
  19883. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19884. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19885. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19886. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19887. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19888. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19889. var x, y, vertices = [], uvs = [];
  19890. for ( y = 0; y <= heightSegments; y ++ ) {
  19891. var verticesRow = [];
  19892. var uvsRow = [];
  19893. for ( x = 0; x <= widthSegments; x ++ ) {
  19894. var u = x / widthSegments;
  19895. var v = y / heightSegments;
  19896. var vertex = new THREE.Vector3();
  19897. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19898. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19899. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19900. this.vertices.push( vertex );
  19901. verticesRow.push( this.vertices.length - 1 );
  19902. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19903. }
  19904. vertices.push( verticesRow );
  19905. uvs.push( uvsRow );
  19906. }
  19907. for ( y = 0; y < this.heightSegments; y ++ ) {
  19908. for ( x = 0; x < this.widthSegments; x ++ ) {
  19909. var v1 = vertices[ y ][ x + 1 ];
  19910. var v2 = vertices[ y ][ x ];
  19911. var v3 = vertices[ y + 1 ][ x ];
  19912. var v4 = vertices[ y + 1 ][ x + 1 ];
  19913. var n1 = this.vertices[ v1 ].clone().normalize();
  19914. var n2 = this.vertices[ v2 ].clone().normalize();
  19915. var n3 = this.vertices[ v3 ].clone().normalize();
  19916. var n4 = this.vertices[ v4 ].clone().normalize();
  19917. var uv1 = uvs[ y ][ x + 1 ].clone();
  19918. var uv2 = uvs[ y ][ x ].clone();
  19919. var uv3 = uvs[ y + 1 ][ x ].clone();
  19920. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19921. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19922. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19923. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19924. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19925. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19926. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19927. } else {
  19928. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19929. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19930. }
  19931. }
  19932. }
  19933. this.computeCentroids();
  19934. this.computeFaceNormals();
  19935. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19936. };
  19937. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19938. /**
  19939. * @author zz85 / http://www.lab4games.net/zz85/blog
  19940. * @author alteredq / http://alteredqualia.com/
  19941. *
  19942. * For creating 3D text geometry in three.js
  19943. *
  19944. * Text = 3D Text
  19945. *
  19946. * parameters = {
  19947. * size: <float>, // size of the text
  19948. * height: <float>, // thickness to extrude text
  19949. * curveSegments: <int>, // number of points on the curves
  19950. *
  19951. * font: <string>, // font name
  19952. * weight: <string>, // font weight (normal, bold)
  19953. * style: <string>, // font style (normal, italics)
  19954. *
  19955. * bevelEnabled: <bool>, // turn on bevel
  19956. * bevelThickness: <float>, // how deep into text bevel goes
  19957. * bevelSize: <float>, // how far from text outline is bevel
  19958. * }
  19959. *
  19960. */
  19961. /* Usage Examples
  19962. // TextGeometry wrapper
  19963. var text3d = new TextGeometry( text, options );
  19964. // Complete manner
  19965. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19966. var text3d = new ExtrudeGeometry( textShapes, options );
  19967. */
  19968. THREE.TextGeometry = function ( text, parameters ) {
  19969. parameters = parameters || {};
  19970. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19971. // translate parameters to ExtrudeGeometry API
  19972. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19973. // defaults
  19974. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19975. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19976. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19977. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19978. };
  19979. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19980. /**
  19981. * @author oosmoxiecode
  19982. * @author mrdoob / http://mrdoob.com/
  19983. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19984. */
  19985. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19986. THREE.Geometry.call( this );
  19987. var scope = this;
  19988. this.radius = radius || 100;
  19989. this.tube = tube || 40;
  19990. this.radialSegments = radialSegments || 8;
  19991. this.tubularSegments = tubularSegments || 6;
  19992. this.arc = arc || Math.PI * 2;
  19993. var center = new THREE.Vector3(), uvs = [], normals = [];
  19994. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19995. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19996. var u = i / this.tubularSegments * this.arc;
  19997. var v = j / this.radialSegments * Math.PI * 2;
  19998. center.x = this.radius * Math.cos( u );
  19999. center.y = this.radius * Math.sin( u );
  20000. var vertex = new THREE.Vector3();
  20001. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  20002. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  20003. vertex.z = this.tube * Math.sin( v );
  20004. this.vertices.push( vertex );
  20005. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  20006. normals.push( vertex.clone().sub( center ).normalize() );
  20007. }
  20008. }
  20009. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  20010. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  20011. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  20012. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20013. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  20014. var d = ( this.tubularSegments + 1 ) * j + i;
  20015. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  20016. face.normal.add( normals[ a ] );
  20017. face.normal.add( normals[ b ] );
  20018. face.normal.add( normals[ c ] );
  20019. face.normal.add( normals[ d ] );
  20020. face.normal.normalize();
  20021. this.faces.push( face );
  20022. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20023. }
  20024. }
  20025. this.computeCentroids();
  20026. };
  20027. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20028. /**
  20029. * @author oosmoxiecode
  20030. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20031. */
  20032. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20033. THREE.Geometry.call( this );
  20034. var scope = this;
  20035. this.radius = radius || 100;
  20036. this.tube = tube || 40;
  20037. this.radialSegments = radialSegments || 64;
  20038. this.tubularSegments = tubularSegments || 8;
  20039. this.p = p || 2;
  20040. this.q = q || 3;
  20041. this.heightScale = heightScale || 1;
  20042. this.grid = new Array( this.radialSegments );
  20043. var tang = new THREE.Vector3();
  20044. var n = new THREE.Vector3();
  20045. var bitan = new THREE.Vector3();
  20046. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20047. this.grid[ i ] = new Array( this.tubularSegments );
  20048. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  20049. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  20050. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  20051. tang.subVectors( p2, p1 );
  20052. n.addVectors( p2, p1 );
  20053. bitan.crossVectors( tang, n );
  20054. n.crossVectors( bitan, tang );
  20055. bitan.normalize();
  20056. n.normalize();
  20057. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20058. var v = j / this.tubularSegments * 2 * Math.PI;
  20059. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20060. var cy = this.tube * Math.sin( v );
  20061. var pos = new THREE.Vector3();
  20062. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20063. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20064. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20065. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  20066. }
  20067. }
  20068. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20069. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20070. var ip = ( i + 1 ) % this.radialSegments;
  20071. var jp = ( j + 1 ) % this.tubularSegments;
  20072. var a = this.grid[ i ][ j ];
  20073. var b = this.grid[ ip ][ j ];
  20074. var c = this.grid[ ip ][ jp ];
  20075. var d = this.grid[ i ][ jp ];
  20076. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  20077. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  20078. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20079. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20080. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20081. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  20082. }
  20083. }
  20084. this.computeCentroids();
  20085. this.computeFaceNormals();
  20086. this.computeVertexNormals();
  20087. function getPos( u, in_q, in_p, radius, heightScale ) {
  20088. var cu = Math.cos( u );
  20089. var su = Math.sin( u );
  20090. var quOverP = in_q / in_p * u;
  20091. var cs = Math.cos( quOverP );
  20092. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20093. var ty = radius * ( 2 + cs ) * su * 0.5;
  20094. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20095. return new THREE.Vector3( tx, ty, tz );
  20096. }
  20097. };
  20098. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20099. /**
  20100. * @author WestLangley / https://github.com/WestLangley
  20101. * @author zz85 / https://github.com/zz85
  20102. * @author miningold / https://github.com/miningold
  20103. *
  20104. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20105. *
  20106. * Creates a tube which extrudes along a 3d spline
  20107. *
  20108. * Uses parallel transport frames as described in
  20109. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20110. */
  20111. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20112. THREE.Geometry.call( this );
  20113. this.path = path;
  20114. this.segments = segments || 64;
  20115. this.radius = radius || 1;
  20116. this.radialSegments = radialSegments || 8;
  20117. this.closed = closed || false;
  20118. this.grid = [];
  20119. var scope = this,
  20120. tangent,
  20121. normal,
  20122. binormal,
  20123. numpoints = this.segments + 1,
  20124. x, y, z,
  20125. tx, ty, tz,
  20126. u, v,
  20127. cx, cy,
  20128. pos, pos2 = new THREE.Vector3(),
  20129. i, j,
  20130. ip, jp,
  20131. a, b, c, d,
  20132. uva, uvb, uvc, uvd;
  20133. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20134. tangents = frames.tangents,
  20135. normals = frames.normals,
  20136. binormals = frames.binormals;
  20137. // proxy internals
  20138. this.tangents = tangents;
  20139. this.normals = normals;
  20140. this.binormals = binormals;
  20141. function vert( x, y, z ) {
  20142. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20143. }
  20144. // consruct the grid
  20145. for ( i = 0; i < numpoints; i++ ) {
  20146. this.grid[ i ] = [];
  20147. u = i / ( numpoints - 1 );
  20148. pos = path.getPointAt( u );
  20149. tangent = tangents[ i ];
  20150. normal = normals[ i ];
  20151. binormal = binormals[ i ];
  20152. for ( j = 0; j < this.radialSegments; j++ ) {
  20153. v = j / this.radialSegments * 2 * Math.PI;
  20154. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20155. cy = this.radius * Math.sin( v );
  20156. pos2.copy( pos );
  20157. pos2.x += cx * normal.x + cy * binormal.x;
  20158. pos2.y += cx * normal.y + cy * binormal.y;
  20159. pos2.z += cx * normal.z + cy * binormal.z;
  20160. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20161. }
  20162. }
  20163. // construct the mesh
  20164. for ( i = 0; i < this.segments; i++ ) {
  20165. for ( j = 0; j < this.radialSegments; j++ ) {
  20166. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20167. jp = (j + 1) % this.radialSegments;
  20168. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20169. b = this.grid[ ip ][ j ];
  20170. c = this.grid[ ip ][ jp ];
  20171. d = this.grid[ i ][ jp ];
  20172. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20173. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20174. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20175. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20176. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20177. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  20178. }
  20179. }
  20180. this.computeCentroids();
  20181. this.computeFaceNormals();
  20182. this.computeVertexNormals();
  20183. };
  20184. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20185. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20186. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20187. var tangent = new THREE.Vector3(),
  20188. normal = new THREE.Vector3(),
  20189. binormal = new THREE.Vector3(),
  20190. tangents = [],
  20191. normals = [],
  20192. binormals = [],
  20193. vec = new THREE.Vector3(),
  20194. mat = new THREE.Matrix4(),
  20195. numpoints = segments + 1,
  20196. theta,
  20197. epsilon = 0.0001,
  20198. smallest,
  20199. tx, ty, tz,
  20200. i, u, v;
  20201. // expose internals
  20202. this.tangents = tangents;
  20203. this.normals = normals;
  20204. this.binormals = binormals;
  20205. // compute the tangent vectors for each segment on the path
  20206. for ( i = 0; i < numpoints; i++ ) {
  20207. u = i / ( numpoints - 1 );
  20208. tangents[ i ] = path.getTangentAt( u );
  20209. tangents[ i ].normalize();
  20210. }
  20211. initialNormal3();
  20212. function initialNormal1(lastBinormal) {
  20213. // fixed start binormal. Has dangers of 0 vectors
  20214. normals[ 0 ] = new THREE.Vector3();
  20215. binormals[ 0 ] = new THREE.Vector3();
  20216. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20217. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20218. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20219. }
  20220. function initialNormal2() {
  20221. // This uses the Frenet-Serret formula for deriving binormal
  20222. var t2 = path.getTangentAt( epsilon );
  20223. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20224. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20225. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20226. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20227. }
  20228. function initialNormal3() {
  20229. // select an initial normal vector perpenicular to the first tangent vector,
  20230. // and in the direction of the smallest tangent xyz component
  20231. normals[ 0 ] = new THREE.Vector3();
  20232. binormals[ 0 ] = new THREE.Vector3();
  20233. smallest = Number.MAX_VALUE;
  20234. tx = Math.abs( tangents[ 0 ].x );
  20235. ty = Math.abs( tangents[ 0 ].y );
  20236. tz = Math.abs( tangents[ 0 ].z );
  20237. if ( tx <= smallest ) {
  20238. smallest = tx;
  20239. normal.set( 1, 0, 0 );
  20240. }
  20241. if ( ty <= smallest ) {
  20242. smallest = ty;
  20243. normal.set( 0, 1, 0 );
  20244. }
  20245. if ( tz <= smallest ) {
  20246. normal.set( 0, 0, 1 );
  20247. }
  20248. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20249. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20250. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20251. }
  20252. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20253. for ( i = 1; i < numpoints; i++ ) {
  20254. normals[ i ] = normals[ i-1 ].clone();
  20255. binormals[ i ] = binormals[ i-1 ].clone();
  20256. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20257. if ( vec.length() > epsilon ) {
  20258. vec.normalize();
  20259. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20260. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20261. }
  20262. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20263. }
  20264. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20265. if ( closed ) {
  20266. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20267. theta /= ( numpoints - 1 );
  20268. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20269. theta = -theta;
  20270. }
  20271. for ( i = 1; i < numpoints; i++ ) {
  20272. // twist a little...
  20273. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20274. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20275. }
  20276. }
  20277. };
  20278. /**
  20279. * @author clockworkgeek / https://github.com/clockworkgeek
  20280. * @author timothypratley / https://github.com/timothypratley
  20281. * @author WestLangley / http://github.com/WestLangley
  20282. */
  20283. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20284. THREE.Geometry.call( this );
  20285. radius = radius || 1;
  20286. detail = detail || 0;
  20287. var that = this;
  20288. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20289. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20290. }
  20291. var midpoints = [], p = this.vertices;
  20292. var f = [];
  20293. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20294. var v1 = p[ faces[ i ][ 0 ] ];
  20295. var v2 = p[ faces[ i ][ 1 ] ];
  20296. var v3 = p[ faces[ i ][ 2 ] ];
  20297. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20298. }
  20299. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20300. subdivide(f[ i ], detail);
  20301. }
  20302. // Handle case when face straddles the seam
  20303. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20304. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20305. var x0 = uvs[ 0 ].x;
  20306. var x1 = uvs[ 1 ].x;
  20307. var x2 = uvs[ 2 ].x;
  20308. var max = Math.max( x0, Math.max( x1, x2 ) );
  20309. var min = Math.min( x0, Math.min( x1, x2 ) );
  20310. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20311. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20312. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20313. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20314. }
  20315. }
  20316. // Apply radius
  20317. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20318. this.vertices[ i ].multiplyScalar( radius );
  20319. }
  20320. // Merge vertices
  20321. this.mergeVertices();
  20322. this.computeCentroids();
  20323. this.computeFaceNormals();
  20324. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20325. // Project vector onto sphere's surface
  20326. function prepare( vector ) {
  20327. var vertex = vector.normalize().clone();
  20328. vertex.index = that.vertices.push( vertex ) - 1;
  20329. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20330. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20331. var v = inclination( vector ) / Math.PI + 0.5;
  20332. vertex.uv = new THREE.Vector2( u, 1 - v );
  20333. return vertex;
  20334. }
  20335. // Approximate a curved face with recursively sub-divided triangles.
  20336. function make( v1, v2, v3 ) {
  20337. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20338. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20339. that.faces.push( face );
  20340. var azi = azimuth( face.centroid );
  20341. that.faceVertexUvs[ 0 ].push( [
  20342. correctUV( v1.uv, v1, azi ),
  20343. correctUV( v2.uv, v2, azi ),
  20344. correctUV( v3.uv, v3, azi )
  20345. ] );
  20346. }
  20347. // Analytically subdivide a face to the required detail level.
  20348. function subdivide(face, detail ) {
  20349. var cols = Math.pow(2, detail);
  20350. var cells = Math.pow(4, detail);
  20351. var a = prepare( that.vertices[ face.a ] );
  20352. var b = prepare( that.vertices[ face.b ] );
  20353. var c = prepare( that.vertices[ face.c ] );
  20354. var v = [];
  20355. // Construct all of the vertices for this subdivision.
  20356. for ( var i = 0 ; i <= cols; i ++ ) {
  20357. v[ i ] = [];
  20358. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20359. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20360. var rows = cols - i;
  20361. for ( var j = 0; j <= rows; j ++) {
  20362. if ( j == 0 && i == cols ) {
  20363. v[ i ][ j ] = aj;
  20364. } else {
  20365. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20366. }
  20367. }
  20368. }
  20369. // Construct all of the faces.
  20370. for ( var i = 0; i < cols ; i ++ ) {
  20371. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20372. var k = Math.floor( j / 2 );
  20373. if ( j % 2 == 0 ) {
  20374. make(
  20375. v[ i ][ k + 1],
  20376. v[ i + 1 ][ k ],
  20377. v[ i ][ k ]
  20378. );
  20379. } else {
  20380. make(
  20381. v[ i ][ k + 1 ],
  20382. v[ i + 1][ k + 1],
  20383. v[ i + 1 ][ k ]
  20384. );
  20385. }
  20386. }
  20387. }
  20388. }
  20389. // Angle around the Y axis, counter-clockwise when looking from above.
  20390. function azimuth( vector ) {
  20391. return Math.atan2( vector.z, -vector.x );
  20392. }
  20393. // Angle above the XZ plane.
  20394. function inclination( vector ) {
  20395. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20396. }
  20397. // Texture fixing helper. Spheres have some odd behaviours.
  20398. function correctUV( uv, vector, azimuth ) {
  20399. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20400. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20401. return uv.clone();
  20402. }
  20403. };
  20404. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20405. /**
  20406. * @author timothypratley / https://github.com/timothypratley
  20407. */
  20408. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20409. this.radius = radius;
  20410. this.detail = detail;
  20411. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20412. var vertices = [
  20413. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20414. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20415. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20416. ];
  20417. var faces = [
  20418. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20419. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20420. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20421. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20422. ];
  20423. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20424. };
  20425. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20426. /**
  20427. * @author timothypratley / https://github.com/timothypratley
  20428. */
  20429. THREE.OctahedronGeometry = function ( radius, detail ) {
  20430. var vertices = [
  20431. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20432. ];
  20433. var faces = [
  20434. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20435. ];
  20436. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20437. };
  20438. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20439. /**
  20440. * @author timothypratley / https://github.com/timothypratley
  20441. */
  20442. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20443. var vertices = [
  20444. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20445. ];
  20446. var faces = [
  20447. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20448. ];
  20449. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20450. };
  20451. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20452. /**
  20453. * @author zz85 / https://github.com/zz85
  20454. * Parametric Surfaces Geometry
  20455. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20456. *
  20457. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20458. *
  20459. */
  20460. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20461. THREE.Geometry.call( this );
  20462. var verts = this.vertices;
  20463. var faces = this.faces;
  20464. var uvs = this.faceVertexUvs[ 0 ];
  20465. useTris = (useTris === undefined) ? false : useTris;
  20466. var i, il, j, p;
  20467. var u, v;
  20468. var stackCount = stacks + 1;
  20469. var sliceCount = slices + 1;
  20470. for ( i = 0; i <= stacks; i ++ ) {
  20471. v = i / stacks;
  20472. for ( j = 0; j <= slices; j ++ ) {
  20473. u = j / slices;
  20474. p = func( u, v );
  20475. verts.push( p );
  20476. }
  20477. }
  20478. var a, b, c, d;
  20479. var uva, uvb, uvc, uvd;
  20480. for ( i = 0; i < stacks; i ++ ) {
  20481. for ( j = 0; j < slices; j ++ ) {
  20482. a = i * sliceCount + j;
  20483. b = i * sliceCount + j + 1;
  20484. c = (i + 1) * sliceCount + j;
  20485. d = (i + 1) * sliceCount + j + 1;
  20486. uva = new THREE.Vector2( j / slices, i / stacks );
  20487. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20488. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20489. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20490. if ( useTris ) {
  20491. faces.push( new THREE.Face3( a, b, c ) );
  20492. faces.push( new THREE.Face3( b, d, c ) );
  20493. uvs.push( [ uva, uvb, uvc ] );
  20494. uvs.push( [ uvb, uvd, uvc ] );
  20495. } else {
  20496. faces.push( new THREE.Face4( a, b, d, c ) );
  20497. uvs.push( [ uva, uvb, uvd, uvc ] );
  20498. }
  20499. }
  20500. }
  20501. // console.log(this);
  20502. // magic bullet
  20503. // var diff = this.mergeVertices();
  20504. // console.log('removed ', diff, ' vertices by merging');
  20505. this.computeCentroids();
  20506. this.computeFaceNormals();
  20507. this.computeVertexNormals();
  20508. };
  20509. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20510. /**
  20511. * @author qiao / https://github.com/qiao
  20512. * @fileoverview This is a convex hull generator using the incremental method.
  20513. * The complexity is O(n^2) where n is the number of vertices.
  20514. * O(nlogn) algorithms do exist, but they are much more complicated.
  20515. *
  20516. * Benchmark:
  20517. *
  20518. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20519. *
  20520. * Num Vertices Time(ms)
  20521. *
  20522. * 10 1
  20523. * 20 3
  20524. * 30 19
  20525. * 40 48
  20526. * 50 107
  20527. */
  20528. THREE.ConvexGeometry = function( vertices ) {
  20529. THREE.Geometry.call( this );
  20530. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20531. for ( var i = 3; i < vertices.length; i++ ) {
  20532. addPoint( i );
  20533. }
  20534. function addPoint( vertexId ) {
  20535. var vertex = vertices[ vertexId ].clone();
  20536. var mag = vertex.length();
  20537. vertex.x += mag * randomOffset();
  20538. vertex.y += mag * randomOffset();
  20539. vertex.z += mag * randomOffset();
  20540. var hole = [];
  20541. for ( var f = 0; f < faces.length; ) {
  20542. var face = faces[ f ];
  20543. // for each face, if the vertex can see it,
  20544. // then we try to add the face's edges into the hole.
  20545. if ( visible( face, vertex ) ) {
  20546. for ( var e = 0; e < 3; e++ ) {
  20547. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20548. var boundary = true;
  20549. // remove duplicated edges.
  20550. for ( var h = 0; h < hole.length; h++ ) {
  20551. if ( equalEdge( hole[ h ], edge ) ) {
  20552. hole[ h ] = hole[ hole.length - 1 ];
  20553. hole.pop();
  20554. boundary = false;
  20555. break;
  20556. }
  20557. }
  20558. if ( boundary ) {
  20559. hole.push( edge );
  20560. }
  20561. }
  20562. // remove faces[ f ]
  20563. faces[ f ] = faces[ faces.length - 1 ];
  20564. faces.pop();
  20565. } else { // not visible
  20566. f++;
  20567. }
  20568. }
  20569. // construct the new faces formed by the edges of the hole and the vertex
  20570. for ( var h = 0; h < hole.length; h++ ) {
  20571. faces.push( [
  20572. hole[ h ][ 0 ],
  20573. hole[ h ][ 1 ],
  20574. vertexId
  20575. ] );
  20576. }
  20577. }
  20578. /**
  20579. * Whether the face is visible from the vertex
  20580. */
  20581. function visible( face, vertex ) {
  20582. var va = vertices[ face[ 0 ] ];
  20583. var vb = vertices[ face[ 1 ] ];
  20584. var vc = vertices[ face[ 2 ] ];
  20585. var n = normal( va, vb, vc );
  20586. // distance from face to origin
  20587. var dist = n.dot( va );
  20588. return n.dot( vertex ) >= dist;
  20589. }
  20590. /**
  20591. * Face normal
  20592. */
  20593. function normal( va, vb, vc ) {
  20594. var cb = new THREE.Vector3();
  20595. var ab = new THREE.Vector3();
  20596. cb.subVectors( vc, vb );
  20597. ab.subVectors( va, vb );
  20598. cb.cross( ab );
  20599. cb.normalize();
  20600. return cb;
  20601. }
  20602. /**
  20603. * Detect whether two edges are equal.
  20604. * Note that when constructing the convex hull, two same edges can only
  20605. * be of the negative direction.
  20606. */
  20607. function equalEdge( ea, eb ) {
  20608. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20609. }
  20610. /**
  20611. * Create a random offset between -1e-6 and 1e-6.
  20612. */
  20613. function randomOffset() {
  20614. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20615. }
  20616. /**
  20617. * XXX: Not sure if this is the correct approach. Need someone to review.
  20618. */
  20619. function vertexUv( vertex ) {
  20620. var mag = vertex.length();
  20621. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20622. }
  20623. // Push vertices into `this.vertices`, skipping those inside the hull
  20624. var id = 0;
  20625. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20626. for ( var i = 0; i < faces.length; i++ ) {
  20627. var face = faces[ i ];
  20628. for ( var j = 0; j < 3; j++ ) {
  20629. if ( newId[ face[ j ] ] === undefined ) {
  20630. newId[ face[ j ] ] = id++;
  20631. this.vertices.push( vertices[ face[ j ] ] );
  20632. }
  20633. face[ j ] = newId[ face[ j ] ];
  20634. }
  20635. }
  20636. // Convert faces into instances of THREE.Face3
  20637. for ( var i = 0; i < faces.length; i++ ) {
  20638. this.faces.push( new THREE.Face3(
  20639. faces[ i ][ 0 ],
  20640. faces[ i ][ 1 ],
  20641. faces[ i ][ 2 ]
  20642. ) );
  20643. }
  20644. // Compute UVs
  20645. for ( var i = 0; i < this.faces.length; i++ ) {
  20646. var face = this.faces[ i ];
  20647. this.faceVertexUvs[ 0 ].push( [
  20648. vertexUv( this.vertices[ face.a ] ),
  20649. vertexUv( this.vertices[ face.b ] ),
  20650. vertexUv( this.vertices[ face.c ])
  20651. ] );
  20652. }
  20653. this.computeCentroids();
  20654. this.computeFaceNormals();
  20655. this.computeVertexNormals();
  20656. };
  20657. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20658. /**
  20659. * @author sroucheray / http://sroucheray.org/
  20660. * @author mrdoob / http://mrdoob.com/
  20661. */
  20662. THREE.AxisHelper = function ( size ) {
  20663. size = size || 1;
  20664. var geometry = new THREE.Geometry();
  20665. geometry.vertices.push(
  20666. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20667. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20668. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20669. );
  20670. geometry.colors.push(
  20671. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20672. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20673. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20674. );
  20675. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20676. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20677. };
  20678. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20679. /**
  20680. * @author WestLangley / http://github.com/WestLangley
  20681. * @author zz85 / http://github.com/zz85
  20682. * @author bhouston / http://exocortex.com
  20683. *
  20684. * Creates an arrow for visualizing directions
  20685. *
  20686. * Parameters:
  20687. * dir - Vector3
  20688. * origin - Vector3
  20689. * length - Number
  20690. * hex - color in hex value
  20691. */
  20692. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20693. // dir is assumed to be normalized
  20694. THREE.Object3D.call( this );
  20695. if ( hex === undefined ) hex = 0xffff00;
  20696. if ( length === undefined ) length = 1;
  20697. this.position = origin;
  20698. var lineGeometry = new THREE.Geometry();
  20699. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20700. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20701. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20702. this.line.matrixAutoUpdate = false;
  20703. this.add( this.line );
  20704. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20705. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20706. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20707. this.cone.matrixAutoUpdate = false;
  20708. this.add( this.cone );
  20709. this.setDirection( dir );
  20710. this.setLength( length );
  20711. };
  20712. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20713. THREE.ArrowHelper.prototype.setDirection = function () {
  20714. var axis = new THREE.Vector3();
  20715. var radians;
  20716. return function ( dir ) {
  20717. // dir is assumed to be normalized
  20718. if ( dir.y > 0.99999 ) {
  20719. this.quaternion.set( 0, 0, 0, 1 );
  20720. } else if ( dir.y < - 0.99999 ) {
  20721. this.quaternion.set( 1, 0, 0, 0 );
  20722. } else {
  20723. axis.set( dir.z, 0, - dir.x ).normalize();
  20724. radians = Math.acos( dir.y );
  20725. this.quaternion.setFromAxisAngle( axis, radians );
  20726. }
  20727. };
  20728. }();
  20729. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20730. this.scale.set( length, length, length );
  20731. };
  20732. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20733. this.line.material.color.setHex( hex );
  20734. this.cone.material.color.setHex( hex );
  20735. };
  20736. /**
  20737. * @author mrdoob / http://mrdoob.com/
  20738. */
  20739. THREE.BoxHelper = function ( object ) {
  20740. // 5____4
  20741. // 1/___0/|
  20742. // | 6__|_7
  20743. // 2/___3/
  20744. var vertices = [
  20745. new THREE.Vector3( 1, 1, 1 ),
  20746. new THREE.Vector3( - 1, 1, 1 ),
  20747. new THREE.Vector3( - 1, - 1, 1 ),
  20748. new THREE.Vector3( 1, - 1, 1 ),
  20749. new THREE.Vector3( 1, 1, - 1 ),
  20750. new THREE.Vector3( - 1, 1, - 1 ),
  20751. new THREE.Vector3( - 1, - 1, - 1 ),
  20752. new THREE.Vector3( 1, - 1, - 1 )
  20753. ];
  20754. this.vertices = vertices;
  20755. // TODO: Wouldn't be nice if Line had .segments?
  20756. var geometry = new THREE.Geometry();
  20757. geometry.vertices.push(
  20758. vertices[ 0 ], vertices[ 1 ],
  20759. vertices[ 1 ], vertices[ 2 ],
  20760. vertices[ 2 ], vertices[ 3 ],
  20761. vertices[ 3 ], vertices[ 0 ],
  20762. vertices[ 4 ], vertices[ 5 ],
  20763. vertices[ 5 ], vertices[ 6 ],
  20764. vertices[ 6 ], vertices[ 7 ],
  20765. vertices[ 7 ], vertices[ 4 ],
  20766. vertices[ 0 ], vertices[ 4 ],
  20767. vertices[ 1 ], vertices[ 5 ],
  20768. vertices[ 2 ], vertices[ 6 ],
  20769. vertices[ 3 ], vertices[ 7 ]
  20770. );
  20771. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20772. if ( object !== undefined ) {
  20773. this.update( object );
  20774. }
  20775. };
  20776. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20777. THREE.BoxHelper.prototype.update = function ( object ) {
  20778. var geometry = object.geometry;
  20779. if ( geometry.boundingBox === null ) {
  20780. geometry.computeBoundingBox();
  20781. }
  20782. var min = geometry.boundingBox.min;
  20783. var max = geometry.boundingBox.max;
  20784. var vertices = this.vertices;
  20785. vertices[ 0 ].set( max.x, max.y, max.z );
  20786. vertices[ 1 ].set( min.x, max.y, max.z );
  20787. vertices[ 2 ].set( min.x, min.y, max.z );
  20788. vertices[ 3 ].set( max.x, min.y, max.z );
  20789. vertices[ 4 ].set( max.x, max.y, min.z );
  20790. vertices[ 5 ].set( min.x, max.y, min.z );
  20791. vertices[ 6 ].set( min.x, min.y, min.z );
  20792. vertices[ 7 ].set( max.x, min.y, min.z );
  20793. this.geometry.computeBoundingSphere();
  20794. this.geometry.verticesNeedUpdate = true;
  20795. this.matrixAutoUpdate = false;
  20796. this.matrixWorld = object.matrixWorld;
  20797. };
  20798. /**
  20799. * @author WestLangley / http://github.com/WestLangley
  20800. */
  20801. // a helper to show the world-axis-aligned bounding box for an object
  20802. THREE.BoundingBoxHelper = function ( object, hex ) {
  20803. var color = hex || 0x888888;
  20804. this.object = object;
  20805. this.box = new THREE.Box3();
  20806. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20807. };
  20808. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20809. THREE.BoundingBoxHelper.prototype.update = function () {
  20810. this.box.setFromObject( this.object );
  20811. this.box.size( this.scale );
  20812. this.box.center( this.position );
  20813. };
  20814. /**
  20815. * @author alteredq / http://alteredqualia.com/
  20816. *
  20817. * - shows frustum, line of sight and up of the camera
  20818. * - suitable for fast updates
  20819. * - based on frustum visualization in lightgl.js shadowmap example
  20820. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20821. */
  20822. THREE.CameraHelper = function ( camera ) {
  20823. THREE.Line.call( this );
  20824. var geometry = new THREE.Geometry();
  20825. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20826. var pointMap = {};
  20827. // colors
  20828. var hexFrustum = 0xffaa00;
  20829. var hexCone = 0xff0000;
  20830. var hexUp = 0x00aaff;
  20831. var hexTarget = 0xffffff;
  20832. var hexCross = 0x333333;
  20833. // near
  20834. addLine( "n1", "n2", hexFrustum );
  20835. addLine( "n2", "n4", hexFrustum );
  20836. addLine( "n4", "n3", hexFrustum );
  20837. addLine( "n3", "n1", hexFrustum );
  20838. // far
  20839. addLine( "f1", "f2", hexFrustum );
  20840. addLine( "f2", "f4", hexFrustum );
  20841. addLine( "f4", "f3", hexFrustum );
  20842. addLine( "f3", "f1", hexFrustum );
  20843. // sides
  20844. addLine( "n1", "f1", hexFrustum );
  20845. addLine( "n2", "f2", hexFrustum );
  20846. addLine( "n3", "f3", hexFrustum );
  20847. addLine( "n4", "f4", hexFrustum );
  20848. // cone
  20849. addLine( "p", "n1", hexCone );
  20850. addLine( "p", "n2", hexCone );
  20851. addLine( "p", "n3", hexCone );
  20852. addLine( "p", "n4", hexCone );
  20853. // up
  20854. addLine( "u1", "u2", hexUp );
  20855. addLine( "u2", "u3", hexUp );
  20856. addLine( "u3", "u1", hexUp );
  20857. // target
  20858. addLine( "c", "t", hexTarget );
  20859. addLine( "p", "c", hexCross );
  20860. // cross
  20861. addLine( "cn1", "cn2", hexCross );
  20862. addLine( "cn3", "cn4", hexCross );
  20863. addLine( "cf1", "cf2", hexCross );
  20864. addLine( "cf3", "cf4", hexCross );
  20865. function addLine( a, b, hex ) {
  20866. addPoint( a, hex );
  20867. addPoint( b, hex );
  20868. }
  20869. function addPoint( id, hex ) {
  20870. geometry.vertices.push( new THREE.Vector3() );
  20871. geometry.colors.push( new THREE.Color( hex ) );
  20872. if ( pointMap[ id ] === undefined ) {
  20873. pointMap[ id ] = [];
  20874. }
  20875. pointMap[ id ].push( geometry.vertices.length - 1 );
  20876. }
  20877. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20878. this.camera = camera;
  20879. this.matrixWorld = camera.matrixWorld;
  20880. this.matrixAutoUpdate = false;
  20881. this.pointMap = pointMap;
  20882. this.update();
  20883. };
  20884. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20885. THREE.CameraHelper.prototype.update = function () {
  20886. var vector = new THREE.Vector3();
  20887. var camera = new THREE.Camera();
  20888. var projector = new THREE.Projector();
  20889. return function () {
  20890. var scope = this;
  20891. var w = 1, h = 1;
  20892. // we need just camera projection matrix
  20893. // world matrix must be identity
  20894. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20895. // center / target
  20896. setPoint( "c", 0, 0, -1 );
  20897. setPoint( "t", 0, 0, 1 );
  20898. // near
  20899. setPoint( "n1", -w, -h, -1 );
  20900. setPoint( "n2", w, -h, -1 );
  20901. setPoint( "n3", -w, h, -1 );
  20902. setPoint( "n4", w, h, -1 );
  20903. // far
  20904. setPoint( "f1", -w, -h, 1 );
  20905. setPoint( "f2", w, -h, 1 );
  20906. setPoint( "f3", -w, h, 1 );
  20907. setPoint( "f4", w, h, 1 );
  20908. // up
  20909. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20910. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20911. setPoint( "u3", 0, h * 2, -1 );
  20912. // cross
  20913. setPoint( "cf1", -w, 0, 1 );
  20914. setPoint( "cf2", w, 0, 1 );
  20915. setPoint( "cf3", 0, -h, 1 );
  20916. setPoint( "cf4", 0, h, 1 );
  20917. setPoint( "cn1", -w, 0, -1 );
  20918. setPoint( "cn2", w, 0, -1 );
  20919. setPoint( "cn3", 0, -h, -1 );
  20920. setPoint( "cn4", 0, h, -1 );
  20921. function setPoint( point, x, y, z ) {
  20922. vector.set( x, y, z );
  20923. projector.unprojectVector( vector, camera );
  20924. var points = scope.pointMap[ point ];
  20925. if ( points !== undefined ) {
  20926. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20927. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20928. }
  20929. }
  20930. }
  20931. this.geometry.verticesNeedUpdate = true;
  20932. };
  20933. }();
  20934. /**
  20935. * @author alteredq / http://alteredqualia.com/
  20936. * @author mrdoob / http://mrdoob.com/
  20937. */
  20938. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20939. THREE.Object3D.call( this );
  20940. this.matrixAutoUpdate = false;
  20941. this.light = light;
  20942. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20943. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20944. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20945. this.lightSphere = new THREE.Mesh( geometry, material );
  20946. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20947. this.lightSphere.matrixAutoUpdate = false;
  20948. this.add( this.lightSphere );
  20949. /*
  20950. this.targetSphere = new THREE.Mesh( geometry, material );
  20951. this.targetSphere.position = this.light.target.position;
  20952. this.add( this.targetSphere );
  20953. */
  20954. geometry = new THREE.Geometry();
  20955. geometry.vertices.push( this.light.position );
  20956. geometry.vertices.push( this.light.target.position );
  20957. geometry.computeLineDistances();
  20958. material = new THREE.LineDashedMaterial( { dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20959. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20960. this.targetLine = new THREE.Line( geometry, material );
  20961. this.add( this.targetLine );
  20962. }
  20963. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20964. THREE.DirectionalLightHelper.prototype.update = function () {
  20965. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20966. this.targetLine.geometry.computeLineDistances();
  20967. this.targetLine.geometry.verticesNeedUpdate = true;
  20968. this.targetLine.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20969. };
  20970. /**
  20971. * @author mrdoob / http://mrdoob.com/
  20972. * @author WestLangley / http://github.com/WestLangley
  20973. */
  20974. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20975. this.object = object;
  20976. this.size = size || 1;
  20977. var color = hex || 0xffff00;
  20978. var width = linewidth || 1;
  20979. var geometry = new THREE.Geometry();
  20980. var faces = this.object.geometry.faces;
  20981. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20982. geometry.vertices.push( new THREE.Vector3() );
  20983. geometry.vertices.push( new THREE.Vector3() );
  20984. }
  20985. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20986. this.matrixAutoUpdate = false;
  20987. this.normalMatrix = new THREE.Matrix3();
  20988. this.update();
  20989. };
  20990. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20991. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20992. var v1 = new THREE.Vector3();
  20993. return function( object ) {
  20994. this.object.updateMatrixWorld( true );
  20995. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20996. var vertices = this.geometry.vertices;
  20997. var faces = this.object.geometry.faces;
  20998. var worldMatrix = this.object.matrixWorld;
  20999. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21000. var face = faces[ i ];
  21001. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21002. var idx = 2 * i;
  21003. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  21004. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  21005. }
  21006. this.geometry.verticesNeedUpdate = true;
  21007. return this;
  21008. }
  21009. }());
  21010. /**
  21011. * @author mrdoob / http://mrdoob.com/
  21012. */
  21013. THREE.GridHelper = function ( size, step ) {
  21014. var geometry = new THREE.Geometry();
  21015. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21016. this.color1 = new THREE.Color( 0x444444 );
  21017. this.color2 = new THREE.Color( 0x888888 );
  21018. for ( var i = - size; i <= size; i += step ) {
  21019. geometry.vertices.push(
  21020. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21021. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21022. );
  21023. var color = i === 0 ? this.color1 : this.color2;
  21024. geometry.colors.push( color, color, color, color );
  21025. }
  21026. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21027. };
  21028. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21029. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21030. this.color1.set( colorCenterLine );
  21031. this.color2.set( colorGrid );
  21032. this.geometry.colorsNeedUpdate = true;
  21033. }
  21034. /**
  21035. * @author alteredq / http://alteredqualia.com/
  21036. * @author mrdoob / http://mrdoob.com/
  21037. */
  21038. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21039. THREE.Object3D.call( this );
  21040. this.light = light;
  21041. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21042. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21043. for ( var i = 0, il = 8; i < il; i ++ ) {
  21044. geometry.faces[ i ].materialIndex = i < 4 ? 0 : 1;
  21045. }
  21046. var materialSky = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21047. materialSky.color.copy( light.color ).multiplyScalar( light.intensity );
  21048. var materialGround = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21049. materialGround.color.copy( light.groundColor ).multiplyScalar( light.intensity );
  21050. this.lightSphere = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ materialSky, materialGround ] ) );
  21051. this.lightSphere.position = light.position;
  21052. this.lightSphere.lookAt( new THREE.Vector3() );
  21053. this.add( this.lightSphere );
  21054. };
  21055. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21056. THREE.HemisphereLightHelper.prototype.update = function () {
  21057. this.lightSphere.lookAt( new THREE.Vector3() );
  21058. this.lightSphere.material.materials[ 0 ].color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21059. this.lightSphere.material.materials[ 1 ].color.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21060. };
  21061. /**
  21062. * @author alteredq / http://alteredqualia.com/
  21063. * @author mrdoob / http://mrdoob.com/
  21064. */
  21065. THREE.PointLightHelper = function ( light, sphereSize ) {
  21066. THREE.Object3D.call( this );
  21067. this.matrixAutoUpdate = false;
  21068. this.light = light;
  21069. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21070. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21071. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21072. this.lightSphere = new THREE.Mesh( geometry, material );
  21073. this.lightSphere.matrixWorld = this.light.matrixWorld;
  21074. this.lightSphere.matrixAutoUpdate = false;
  21075. this.add( this.lightSphere );
  21076. /*
  21077. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21078. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21079. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21080. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21081. var d = light.distance;
  21082. if ( d === 0.0 ) {
  21083. this.lightDistance.visible = false;
  21084. } else {
  21085. this.lightDistance.scale.set( d, d, d );
  21086. }
  21087. this.add( this.lightDistance );
  21088. */
  21089. };
  21090. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21091. THREE.PointLightHelper.prototype.update = function () {
  21092. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21093. /*
  21094. this.lightDistance.material.color.copy( this.color );
  21095. var d = this.light.distance;
  21096. if ( d === 0.0 ) {
  21097. this.lightDistance.visible = false;
  21098. } else {
  21099. this.lightDistance.visible = true;
  21100. this.lightDistance.scale.set( d, d, d );
  21101. }
  21102. */
  21103. };
  21104. /**
  21105. * @author alteredq / http://alteredqualia.com/
  21106. * @author mrdoob / http://mrdoob.com/
  21107. * @author WestLangley / http://github.com/WestLangley
  21108. */
  21109. THREE.SpotLightHelper = function ( light ) {
  21110. // spotlight helper must be a child of the scene
  21111. this.light = light;
  21112. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21113. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21114. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21115. var material = new THREE.MeshBasicMaterial( { wireframe: true, opacity: 0.3, transparent: true } );
  21116. THREE.Mesh.call( this, geometry, material );
  21117. this.update();
  21118. };
  21119. THREE.SpotLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21120. THREE.SpotLightHelper.prototype.update = ( function () {
  21121. var targetPosition = new THREE.Vector3();
  21122. return function() {
  21123. var coneLength = this.light.distance ? this.light.distance : 10000;
  21124. var coneWidth = coneLength * Math.tan( this.light.angle );
  21125. this.scale.set( coneWidth, coneWidth, coneLength );
  21126. this.light.updateMatrixWorld( true );
  21127. this.position.getPositionFromMatrix( this.light.matrixWorld );
  21128. this.light.target.updateMatrixWorld( true );
  21129. targetPosition.getPositionFromMatrix( this.light.target.matrixWorld );
  21130. this.lookAt( targetPosition );
  21131. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21132. }
  21133. }());
  21134. /**
  21135. * @author mrdoob / http://mrdoob.com/
  21136. * @author WestLangley / http://github.com/WestLangley
  21137. */
  21138. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21139. this.object = object;
  21140. this.size = size || 1;
  21141. var color = hex || 0xff0000;
  21142. var width = linewidth || 1;
  21143. var geometry = new THREE.Geometry();
  21144. var vertices = object.geometry.vertices;
  21145. var faces = object.geometry.faces;
  21146. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21147. var face = faces[ i ];
  21148. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21149. geometry.vertices.push( new THREE.Vector3() );
  21150. geometry.vertices.push( new THREE.Vector3() );
  21151. }
  21152. }
  21153. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21154. this.matrixAutoUpdate = false;
  21155. this.normalMatrix = new THREE.Matrix3();
  21156. this.update();
  21157. };
  21158. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21159. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21160. var v1 = new THREE.Vector3();
  21161. return function( object ) {
  21162. var keys = [ 'a', 'b', 'c', 'd' ];
  21163. this.object.updateMatrixWorld( true );
  21164. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21165. var vertices = this.geometry.vertices;
  21166. var verts = this.object.geometry.vertices;
  21167. var faces = this.object.geometry.faces;
  21168. var worldMatrix = this.object.matrixWorld;
  21169. var idx = 0;
  21170. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21171. var face = faces[ i ];
  21172. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21173. var vertexId = face[ keys[ j ] ];
  21174. var vertex = verts[ vertexId ];
  21175. var normal = face.vertexNormals[ j ];
  21176. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21177. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21178. v1.add( vertices[ idx ] );
  21179. idx = idx + 1;
  21180. vertices[ idx ].copy( v1 );
  21181. idx = idx + 1;
  21182. }
  21183. }
  21184. this.geometry.verticesNeedUpdate = true;
  21185. return this;
  21186. }
  21187. }());
  21188. /**
  21189. * @author mrdoob / http://mrdoob.com/
  21190. * @author WestLangley / http://github.com/WestLangley
  21191. */
  21192. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21193. this.object = object;
  21194. this.size = size || 1;
  21195. var color = hex || 0x0000ff;
  21196. var width = linewidth || 1;
  21197. var geometry = new THREE.Geometry();
  21198. var vertices = object.geometry.vertices;
  21199. var faces = object.geometry.faces;
  21200. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21201. var face = faces[ i ];
  21202. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21203. geometry.vertices.push( new THREE.Vector3() );
  21204. geometry.vertices.push( new THREE.Vector3() );
  21205. }
  21206. }
  21207. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21208. this.matrixAutoUpdate = false;
  21209. this.update();
  21210. };
  21211. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21212. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21213. var v1 = new THREE.Vector3();
  21214. return function( object ) {
  21215. var keys = [ 'a', 'b', 'c', 'd' ];
  21216. this.object.updateMatrixWorld( true );
  21217. var vertices = this.geometry.vertices;
  21218. var verts = this.object.geometry.vertices;
  21219. var faces = this.object.geometry.faces;
  21220. var worldMatrix = this.object.matrixWorld;
  21221. var idx = 0;
  21222. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21223. var face = faces[ i ];
  21224. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21225. var vertexId = face[ keys[ j ] ];
  21226. var vertex = verts[ vertexId ];
  21227. var tangent = face.vertexTangents[ j ];
  21228. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21229. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21230. v1.add( vertices[ idx ] );
  21231. idx = idx + 1;
  21232. vertices[ idx ].copy( v1 );
  21233. idx = idx + 1;
  21234. }
  21235. }
  21236. this.geometry.verticesNeedUpdate = true;
  21237. return this;
  21238. }
  21239. }());
  21240. /**
  21241. * @author mrdoob / http://mrdoob.com/
  21242. */
  21243. THREE.WireframeHelper = function ( object ) {
  21244. var edge = [ 0, 0 ], hash = {};
  21245. var sortFunction = function ( a, b ) { return a - b };
  21246. var keys = [ 'a', 'b', 'c', 'd' ];
  21247. var geometry = new THREE.Geometry();
  21248. var vertices = object.geometry.vertices;
  21249. var faces = object.geometry.faces;
  21250. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21251. var face = faces[ i ];
  21252. var length = face instanceof THREE.Face4 ? 4 : 3;
  21253. for ( var j = 0; j < length; j ++ ) {
  21254. edge[ 0 ] = face[ keys[ j ] ];
  21255. edge[ 1 ] = face[ keys[ ( j + 1 ) % length ] ];
  21256. edge.sort( sortFunction );
  21257. var key = edge.toString();
  21258. if ( hash[ key ] === undefined ) {
  21259. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  21260. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  21261. hash[ key ] = true;
  21262. }
  21263. }
  21264. }
  21265. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  21266. this.matrixAutoUpdate = false;
  21267. this.matrixWorld = object.matrixWorld;
  21268. };
  21269. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21270. /**
  21271. * @author alteredq / http://alteredqualia.com/
  21272. */
  21273. THREE.ImmediateRenderObject = function () {
  21274. THREE.Object3D.call( this );
  21275. this.render = function ( renderCallback ) { };
  21276. };
  21277. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21278. /**
  21279. * @author mikael emtinger / http://gomo.se/
  21280. * @author alteredq / http://alteredqualia.com/
  21281. */
  21282. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21283. THREE.Object3D.call( this );
  21284. this.lensFlares = [];
  21285. this.positionScreen = new THREE.Vector3();
  21286. this.customUpdateCallback = undefined;
  21287. if( texture !== undefined ) {
  21288. this.add( texture, size, distance, blending, color );
  21289. }
  21290. };
  21291. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21292. /*
  21293. * Add: adds another flare
  21294. */
  21295. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21296. if( size === undefined ) size = -1;
  21297. if( distance === undefined ) distance = 0;
  21298. if( opacity === undefined ) opacity = 1;
  21299. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21300. if( blending === undefined ) blending = THREE.NormalBlending;
  21301. distance = Math.min( distance, Math.max( 0, distance ) );
  21302. this.lensFlares.push( { texture: texture, // THREE.Texture
  21303. size: size, // size in pixels (-1 = use texture.width)
  21304. distance: distance, // distance (0-1) from light source (0=at light source)
  21305. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21306. scale: 1, // scale
  21307. rotation: 1, // rotation
  21308. opacity: opacity, // opacity
  21309. color: color, // color
  21310. blending: blending } ); // blending
  21311. };
  21312. /*
  21313. * Update lens flares update positions on all flares based on the screen position
  21314. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21315. */
  21316. THREE.LensFlare.prototype.updateLensFlares = function () {
  21317. var f, fl = this.lensFlares.length;
  21318. var flare;
  21319. var vecX = -this.positionScreen.x * 2;
  21320. var vecY = -this.positionScreen.y * 2;
  21321. for( f = 0; f < fl; f ++ ) {
  21322. flare = this.lensFlares[ f ];
  21323. flare.x = this.positionScreen.x + vecX * flare.distance;
  21324. flare.y = this.positionScreen.y + vecY * flare.distance;
  21325. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21326. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21327. }
  21328. };
  21329. /**
  21330. * @author alteredq / http://alteredqualia.com/
  21331. */
  21332. THREE.MorphBlendMesh = function( geometry, material ) {
  21333. THREE.Mesh.call( this, geometry, material );
  21334. this.animationsMap = {};
  21335. this.animationsList = [];
  21336. // prepare default animation
  21337. // (all frames played together in 1 second)
  21338. var numFrames = this.geometry.morphTargets.length;
  21339. var name = "__default";
  21340. var startFrame = 0;
  21341. var endFrame = numFrames - 1;
  21342. var fps = numFrames / 1;
  21343. this.createAnimation( name, startFrame, endFrame, fps );
  21344. this.setAnimationWeight( name, 1 );
  21345. };
  21346. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21347. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21348. var animation = {
  21349. startFrame: start,
  21350. endFrame: end,
  21351. length: end - start + 1,
  21352. fps: fps,
  21353. duration: ( end - start ) / fps,
  21354. lastFrame: 0,
  21355. currentFrame: 0,
  21356. active: false,
  21357. time: 0,
  21358. direction: 1,
  21359. weight: 1,
  21360. directionBackwards: false,
  21361. mirroredLoop: false
  21362. };
  21363. this.animationsMap[ name ] = animation;
  21364. this.animationsList.push( animation );
  21365. };
  21366. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21367. var pattern = /([a-z]+)(\d+)/;
  21368. var firstAnimation, frameRanges = {};
  21369. var geometry = this.geometry;
  21370. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21371. var morph = geometry.morphTargets[ i ];
  21372. var chunks = morph.name.match( pattern );
  21373. if ( chunks && chunks.length > 1 ) {
  21374. var name = chunks[ 1 ];
  21375. var num = chunks[ 2 ];
  21376. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21377. var range = frameRanges[ name ];
  21378. if ( i < range.start ) range.start = i;
  21379. if ( i > range.end ) range.end = i;
  21380. if ( ! firstAnimation ) firstAnimation = name;
  21381. }
  21382. }
  21383. for ( var name in frameRanges ) {
  21384. var range = frameRanges[ name ];
  21385. this.createAnimation( name, range.start, range.end, fps );
  21386. }
  21387. this.firstAnimation = firstAnimation;
  21388. };
  21389. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21390. var animation = this.animationsMap[ name ];
  21391. if ( animation ) {
  21392. animation.direction = 1;
  21393. animation.directionBackwards = false;
  21394. }
  21395. };
  21396. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21397. var animation = this.animationsMap[ name ];
  21398. if ( animation ) {
  21399. animation.direction = -1;
  21400. animation.directionBackwards = true;
  21401. }
  21402. };
  21403. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21404. var animation = this.animationsMap[ name ];
  21405. if ( animation ) {
  21406. animation.fps = fps;
  21407. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21408. }
  21409. };
  21410. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21411. var animation = this.animationsMap[ name ];
  21412. if ( animation ) {
  21413. animation.duration = duration;
  21414. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21415. }
  21416. };
  21417. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21418. var animation = this.animationsMap[ name ];
  21419. if ( animation ) {
  21420. animation.weight = weight;
  21421. }
  21422. };
  21423. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21424. var animation = this.animationsMap[ name ];
  21425. if ( animation ) {
  21426. animation.time = time;
  21427. }
  21428. };
  21429. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21430. var time = 0;
  21431. var animation = this.animationsMap[ name ];
  21432. if ( animation ) {
  21433. time = animation.time;
  21434. }
  21435. return time;
  21436. };
  21437. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21438. var duration = -1;
  21439. var animation = this.animationsMap[ name ];
  21440. if ( animation ) {
  21441. duration = animation.duration;
  21442. }
  21443. return duration;
  21444. };
  21445. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21446. var animation = this.animationsMap[ name ];
  21447. if ( animation ) {
  21448. animation.time = 0;
  21449. animation.active = true;
  21450. } else {
  21451. console.warn( "animation[" + name + "] undefined" );
  21452. }
  21453. };
  21454. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21455. var animation = this.animationsMap[ name ];
  21456. if ( animation ) {
  21457. animation.active = false;
  21458. }
  21459. };
  21460. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21461. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21462. var animation = this.animationsList[ i ];
  21463. if ( ! animation.active ) continue;
  21464. var frameTime = animation.duration / animation.length;
  21465. animation.time += animation.direction * delta;
  21466. if ( animation.mirroredLoop ) {
  21467. if ( animation.time > animation.duration || animation.time < 0 ) {
  21468. animation.direction *= -1;
  21469. if ( animation.time > animation.duration ) {
  21470. animation.time = animation.duration;
  21471. animation.directionBackwards = true;
  21472. }
  21473. if ( animation.time < 0 ) {
  21474. animation.time = 0;
  21475. animation.directionBackwards = false;
  21476. }
  21477. }
  21478. } else {
  21479. animation.time = animation.time % animation.duration;
  21480. if ( animation.time < 0 ) animation.time += animation.duration;
  21481. }
  21482. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21483. var weight = animation.weight;
  21484. if ( keyframe !== animation.currentFrame ) {
  21485. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21486. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21487. this.morphTargetInfluences[ keyframe ] = 0;
  21488. animation.lastFrame = animation.currentFrame;
  21489. animation.currentFrame = keyframe;
  21490. }
  21491. var mix = ( animation.time % frameTime ) / frameTime;
  21492. if ( animation.directionBackwards ) mix = 1 - mix;
  21493. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21494. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21495. }
  21496. };
  21497. /**
  21498. * @author mikael emtinger / http://gomo.se/
  21499. * @author alteredq / http://alteredqualia.com/
  21500. */
  21501. THREE.LensFlarePlugin = function () {
  21502. var _gl, _renderer, _precision, _lensFlare = {};
  21503. this.init = function ( renderer ) {
  21504. _gl = renderer.context;
  21505. _renderer = renderer;
  21506. _precision = renderer.getPrecision();
  21507. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21508. _lensFlare.faces = new Uint16Array( 6 );
  21509. var i = 0;
  21510. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21511. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21512. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21513. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21514. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21515. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21516. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21517. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21518. i = 0;
  21519. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21520. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21521. // buffers
  21522. _lensFlare.vertexBuffer = _gl.createBuffer();
  21523. _lensFlare.elementBuffer = _gl.createBuffer();
  21524. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21525. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21526. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21527. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21528. // textures
  21529. _lensFlare.tempTexture = _gl.createTexture();
  21530. _lensFlare.occlusionTexture = _gl.createTexture();
  21531. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21532. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21533. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21534. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21535. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21536. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21537. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21538. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21539. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21540. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21541. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21542. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21543. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21544. _lensFlare.hasVertexTexture = false;
  21545. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21546. } else {
  21547. _lensFlare.hasVertexTexture = true;
  21548. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21549. }
  21550. _lensFlare.attributes = {};
  21551. _lensFlare.uniforms = {};
  21552. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21553. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21554. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21555. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21556. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21557. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21558. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21559. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21560. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21561. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21562. };
  21563. /*
  21564. * Render lens flares
  21565. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21566. * reads these back and calculates occlusion.
  21567. * Then _lensFlare.update_lensFlares() is called to re-position and
  21568. * update transparency of flares. Then they are rendered.
  21569. *
  21570. */
  21571. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21572. var flares = scene.__webglFlares,
  21573. nFlares = flares.length;
  21574. if ( ! nFlares ) return;
  21575. var tempPosition = new THREE.Vector3();
  21576. var invAspect = viewportHeight / viewportWidth,
  21577. halfViewportWidth = viewportWidth * 0.5,
  21578. halfViewportHeight = viewportHeight * 0.5;
  21579. var size = 16 / viewportHeight,
  21580. scale = new THREE.Vector2( size * invAspect, size );
  21581. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21582. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21583. var uniforms = _lensFlare.uniforms,
  21584. attributes = _lensFlare.attributes;
  21585. // set _lensFlare program and reset blending
  21586. _gl.useProgram( _lensFlare.program );
  21587. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21588. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21589. // loop through all lens flares to update their occlusion and positions
  21590. // setup gl and common used attribs/unforms
  21591. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21592. _gl.uniform1i( uniforms.map, 1 );
  21593. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21594. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21595. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21596. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21597. _gl.disable( _gl.CULL_FACE );
  21598. _gl.depthMask( false );
  21599. var i, j, jl, flare, sprite;
  21600. for ( i = 0; i < nFlares; i ++ ) {
  21601. size = 16 / viewportHeight;
  21602. scale.set( size * invAspect, size );
  21603. // calc object screen position
  21604. flare = flares[ i ];
  21605. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21606. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21607. tempPosition.applyProjection( camera.projectionMatrix );
  21608. // setup arrays for gl programs
  21609. screenPosition.copy( tempPosition )
  21610. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21611. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21612. // screen cull
  21613. if ( _lensFlare.hasVertexTexture || (
  21614. screenPositionPixels.x > 0 &&
  21615. screenPositionPixels.x < viewportWidth &&
  21616. screenPositionPixels.y > 0 &&
  21617. screenPositionPixels.y < viewportHeight ) ) {
  21618. // save current RGB to temp texture
  21619. _gl.activeTexture( _gl.TEXTURE1 );
  21620. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21621. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21622. // render pink quad
  21623. _gl.uniform1i( uniforms.renderType, 0 );
  21624. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21625. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21626. _gl.disable( _gl.BLEND );
  21627. _gl.enable( _gl.DEPTH_TEST );
  21628. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21629. // copy result to occlusionMap
  21630. _gl.activeTexture( _gl.TEXTURE0 );
  21631. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21632. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21633. // restore graphics
  21634. _gl.uniform1i( uniforms.renderType, 1 );
  21635. _gl.disable( _gl.DEPTH_TEST );
  21636. _gl.activeTexture( _gl.TEXTURE1 );
  21637. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21638. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21639. // update object positions
  21640. flare.positionScreen.copy( screenPosition )
  21641. if ( flare.customUpdateCallback ) {
  21642. flare.customUpdateCallback( flare );
  21643. } else {
  21644. flare.updateLensFlares();
  21645. }
  21646. // render flares
  21647. _gl.uniform1i( uniforms.renderType, 2 );
  21648. _gl.enable( _gl.BLEND );
  21649. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21650. sprite = flare.lensFlares[ j ];
  21651. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21652. screenPosition.x = sprite.x;
  21653. screenPosition.y = sprite.y;
  21654. screenPosition.z = sprite.z;
  21655. size = sprite.size * sprite.scale / viewportHeight;
  21656. scale.x = size * invAspect;
  21657. scale.y = size;
  21658. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21659. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21660. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21661. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21662. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21663. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21664. _renderer.setTexture( sprite.texture, 1 );
  21665. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21666. }
  21667. }
  21668. }
  21669. }
  21670. // restore gl
  21671. _gl.enable( _gl.CULL_FACE );
  21672. _gl.enable( _gl.DEPTH_TEST );
  21673. _gl.depthMask( true );
  21674. };
  21675. function createProgram ( shader, precision ) {
  21676. var program = _gl.createProgram();
  21677. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21678. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21679. var prefix = "precision " + precision + " float;\n";
  21680. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21681. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21682. _gl.compileShader( fragmentShader );
  21683. _gl.compileShader( vertexShader );
  21684. _gl.attachShader( program, fragmentShader );
  21685. _gl.attachShader( program, vertexShader );
  21686. _gl.linkProgram( program );
  21687. return program;
  21688. };
  21689. };
  21690. /**
  21691. * @author alteredq / http://alteredqualia.com/
  21692. */
  21693. THREE.ShadowMapPlugin = function () {
  21694. var _gl,
  21695. _renderer,
  21696. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21697. _frustum = new THREE.Frustum(),
  21698. _projScreenMatrix = new THREE.Matrix4(),
  21699. _min = new THREE.Vector3(),
  21700. _max = new THREE.Vector3(),
  21701. _matrixPosition = new THREE.Vector3();
  21702. this.init = function ( renderer ) {
  21703. _gl = renderer.context;
  21704. _renderer = renderer;
  21705. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21706. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21707. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21708. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21709. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21710. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21711. _depthMaterial._shadowPass = true;
  21712. _depthMaterialMorph._shadowPass = true;
  21713. _depthMaterialSkin._shadowPass = true;
  21714. _depthMaterialMorphSkin._shadowPass = true;
  21715. };
  21716. this.render = function ( scene, camera ) {
  21717. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21718. this.update( scene, camera );
  21719. };
  21720. this.update = function ( scene, camera ) {
  21721. var i, il, j, jl, n,
  21722. shadowMap, shadowMatrix, shadowCamera,
  21723. program, buffer, material,
  21724. webglObject, object, light,
  21725. renderList,
  21726. lights = [],
  21727. k = 0,
  21728. fog = null;
  21729. // set GL state for depth map
  21730. _gl.clearColor( 1, 1, 1, 1 );
  21731. _gl.disable( _gl.BLEND );
  21732. _gl.enable( _gl.CULL_FACE );
  21733. _gl.frontFace( _gl.CCW );
  21734. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21735. _gl.cullFace( _gl.FRONT );
  21736. } else {
  21737. _gl.cullFace( _gl.BACK );
  21738. }
  21739. _renderer.setDepthTest( true );
  21740. // preprocess lights
  21741. // - skip lights that are not casting shadows
  21742. // - create virtual lights for cascaded shadow maps
  21743. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21744. light = scene.__lights[ i ];
  21745. if ( ! light.castShadow ) continue;
  21746. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21747. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21748. var virtualLight;
  21749. if ( ! light.shadowCascadeArray[ n ] ) {
  21750. virtualLight = createVirtualLight( light, n );
  21751. virtualLight.originalCamera = camera;
  21752. var gyro = new THREE.Gyroscope();
  21753. gyro.position = light.shadowCascadeOffset;
  21754. gyro.add( virtualLight );
  21755. gyro.add( virtualLight.target );
  21756. camera.add( gyro );
  21757. light.shadowCascadeArray[ n ] = virtualLight;
  21758. console.log( "Created virtualLight", virtualLight );
  21759. } else {
  21760. virtualLight = light.shadowCascadeArray[ n ];
  21761. }
  21762. updateVirtualLight( light, n );
  21763. lights[ k ] = virtualLight;
  21764. k ++;
  21765. }
  21766. } else {
  21767. lights[ k ] = light;
  21768. k ++;
  21769. }
  21770. }
  21771. // render depth map
  21772. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21773. light = lights[ i ];
  21774. if ( ! light.shadowMap ) {
  21775. var shadowFilter = THREE.LinearFilter;
  21776. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21777. shadowFilter = THREE.NearestFilter;
  21778. }
  21779. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21780. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21781. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21782. light.shadowMatrix = new THREE.Matrix4();
  21783. }
  21784. if ( ! light.shadowCamera ) {
  21785. if ( light instanceof THREE.SpotLight ) {
  21786. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21787. } else if ( light instanceof THREE.DirectionalLight ) {
  21788. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21789. } else {
  21790. console.error( "Unsupported light type for shadow" );
  21791. continue;
  21792. }
  21793. scene.add( light.shadowCamera );
  21794. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21795. }
  21796. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21797. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21798. light.shadowCamera.add( light.cameraHelper );
  21799. }
  21800. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21801. updateShadowCamera( camera, light );
  21802. }
  21803. shadowMap = light.shadowMap;
  21804. shadowMatrix = light.shadowMatrix;
  21805. shadowCamera = light.shadowCamera;
  21806. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21807. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21808. shadowCamera.lookAt( _matrixPosition );
  21809. shadowCamera.updateMatrixWorld();
  21810. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21811. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21812. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21813. // compute shadow matrix
  21814. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21815. 0.0, 0.5, 0.0, 0.5,
  21816. 0.0, 0.0, 0.5, 0.5,
  21817. 0.0, 0.0, 0.0, 1.0 );
  21818. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21819. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21820. // update camera matrices and frustum
  21821. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21822. _frustum.setFromMatrix( _projScreenMatrix );
  21823. // render shadow map
  21824. _renderer.setRenderTarget( shadowMap );
  21825. _renderer.clear();
  21826. // set object matrices & frustum culling
  21827. renderList = scene.__webglObjects;
  21828. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21829. webglObject = renderList[ j ];
  21830. object = webglObject.object;
  21831. webglObject.render = false;
  21832. if ( object.visible && object.castShadow ) {
  21833. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21834. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21835. webglObject.render = true;
  21836. }
  21837. }
  21838. }
  21839. // render regular objects
  21840. var objectMaterial, useMorphing, useSkinning;
  21841. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21842. webglObject = renderList[ j ];
  21843. if ( webglObject.render ) {
  21844. object = webglObject.object;
  21845. buffer = webglObject.buffer;
  21846. // culling is overriden globally for all objects
  21847. // while rendering depth map
  21848. // need to deal with MeshFaceMaterial somehow
  21849. // in that case just use the first of material.materials for now
  21850. // (proper solution would require to break objects by materials
  21851. // similarly to regular rendering and then set corresponding
  21852. // depth materials per each chunk instead of just once per object)
  21853. objectMaterial = getObjectMaterial( object );
  21854. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21855. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21856. if ( object.customDepthMaterial ) {
  21857. material = object.customDepthMaterial;
  21858. } else if ( useSkinning ) {
  21859. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21860. } else if ( useMorphing ) {
  21861. material = _depthMaterialMorph;
  21862. } else {
  21863. material = _depthMaterial;
  21864. }
  21865. if ( buffer instanceof THREE.BufferGeometry ) {
  21866. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21867. } else {
  21868. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21869. }
  21870. }
  21871. }
  21872. // set matrices and render immediate objects
  21873. renderList = scene.__webglObjectsImmediate;
  21874. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21875. webglObject = renderList[ j ];
  21876. object = webglObject.object;
  21877. if ( object.visible && object.castShadow ) {
  21878. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21879. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21880. }
  21881. }
  21882. }
  21883. // restore GL state
  21884. var clearColor = _renderer.getClearColor(),
  21885. clearAlpha = _renderer.getClearAlpha();
  21886. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21887. _gl.enable( _gl.BLEND );
  21888. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21889. _gl.cullFace( _gl.BACK );
  21890. }
  21891. };
  21892. function createVirtualLight( light, cascade ) {
  21893. var virtualLight = new THREE.DirectionalLight();
  21894. virtualLight.isVirtual = true;
  21895. virtualLight.onlyShadow = true;
  21896. virtualLight.castShadow = true;
  21897. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21898. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21899. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21900. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21901. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21902. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21903. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21904. virtualLight.shadowDarkness = light.shadowDarkness;
  21905. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21906. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21907. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21908. virtualLight.pointsWorld = [];
  21909. virtualLight.pointsFrustum = [];
  21910. var pointsWorld = virtualLight.pointsWorld,
  21911. pointsFrustum = virtualLight.pointsFrustum;
  21912. for ( var i = 0; i < 8; i ++ ) {
  21913. pointsWorld[ i ] = new THREE.Vector3();
  21914. pointsFrustum[ i ] = new THREE.Vector3();
  21915. }
  21916. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21917. var farZ = light.shadowCascadeFarZ[ cascade ];
  21918. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21919. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21920. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21921. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21922. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21923. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21924. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21925. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21926. return virtualLight;
  21927. }
  21928. // Synchronize virtual light with the original light
  21929. function updateVirtualLight( light, cascade ) {
  21930. var virtualLight = light.shadowCascadeArray[ cascade ];
  21931. virtualLight.position.copy( light.position );
  21932. virtualLight.target.position.copy( light.target.position );
  21933. virtualLight.lookAt( virtualLight.target );
  21934. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21935. virtualLight.shadowDarkness = light.shadowDarkness;
  21936. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21937. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21938. var farZ = light.shadowCascadeFarZ[ cascade ];
  21939. var pointsFrustum = virtualLight.pointsFrustum;
  21940. pointsFrustum[ 0 ].z = nearZ;
  21941. pointsFrustum[ 1 ].z = nearZ;
  21942. pointsFrustum[ 2 ].z = nearZ;
  21943. pointsFrustum[ 3 ].z = nearZ;
  21944. pointsFrustum[ 4 ].z = farZ;
  21945. pointsFrustum[ 5 ].z = farZ;
  21946. pointsFrustum[ 6 ].z = farZ;
  21947. pointsFrustum[ 7 ].z = farZ;
  21948. }
  21949. // Fit shadow camera's ortho frustum to camera frustum
  21950. function updateShadowCamera( camera, light ) {
  21951. var shadowCamera = light.shadowCamera,
  21952. pointsFrustum = light.pointsFrustum,
  21953. pointsWorld = light.pointsWorld;
  21954. _min.set( Infinity, Infinity, Infinity );
  21955. _max.set( -Infinity, -Infinity, -Infinity );
  21956. for ( var i = 0; i < 8; i ++ ) {
  21957. var p = pointsWorld[ i ];
  21958. p.copy( pointsFrustum[ i ] );
  21959. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21960. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21961. if ( p.x < _min.x ) _min.x = p.x;
  21962. if ( p.x > _max.x ) _max.x = p.x;
  21963. if ( p.y < _min.y ) _min.y = p.y;
  21964. if ( p.y > _max.y ) _max.y = p.y;
  21965. if ( p.z < _min.z ) _min.z = p.z;
  21966. if ( p.z > _max.z ) _max.z = p.z;
  21967. }
  21968. shadowCamera.left = _min.x;
  21969. shadowCamera.right = _max.x;
  21970. shadowCamera.top = _max.y;
  21971. shadowCamera.bottom = _min.y;
  21972. // can't really fit near/far
  21973. //shadowCamera.near = _min.z;
  21974. //shadowCamera.far = _max.z;
  21975. shadowCamera.updateProjectionMatrix();
  21976. }
  21977. // For the moment just ignore objects that have multiple materials with different animation methods
  21978. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21979. function getObjectMaterial( object ) {
  21980. return object.material instanceof THREE.MeshFaceMaterial
  21981. ? object.material.materials[ 0 ]
  21982. : object.material;
  21983. };
  21984. };
  21985. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21986. /**
  21987. * @author mikael emtinger / http://gomo.se/
  21988. * @author alteredq / http://alteredqualia.com/
  21989. */
  21990. THREE.SpritePlugin = function () {
  21991. var _gl, _renderer, _precision, _sprite = {};
  21992. this.init = function ( renderer ) {
  21993. _gl = renderer.context;
  21994. _renderer = renderer;
  21995. _precision = renderer.getPrecision();
  21996. _sprite.vertices = new Float32Array( 8 + 8 );
  21997. _sprite.faces = new Uint16Array( 6 );
  21998. var i = 0;
  21999. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  22000. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  22001. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  22002. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  22003. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  22004. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  22005. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  22006. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  22007. i = 0;
  22008. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  22009. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  22010. _sprite.vertexBuffer = _gl.createBuffer();
  22011. _sprite.elementBuffer = _gl.createBuffer();
  22012. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  22013. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  22014. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  22015. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  22016. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  22017. _sprite.attributes = {};
  22018. _sprite.uniforms = {};
  22019. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  22020. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  22021. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  22022. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  22023. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  22024. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  22025. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  22026. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  22027. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  22028. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  22029. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  22030. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  22031. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  22032. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  22033. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  22034. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  22035. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  22036. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  22037. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  22038. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  22039. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  22040. };
  22041. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22042. var sprites = scene.__webglSprites,
  22043. nSprites = sprites.length;
  22044. if ( ! nSprites ) return;
  22045. var attributes = _sprite.attributes,
  22046. uniforms = _sprite.uniforms;
  22047. var invAspect = viewportHeight / viewportWidth;
  22048. var halfViewportWidth = viewportWidth * 0.5,
  22049. halfViewportHeight = viewportHeight * 0.5;
  22050. // setup gl
  22051. _gl.useProgram( _sprite.program );
  22052. _gl.enableVertexAttribArray( attributes.position );
  22053. _gl.enableVertexAttribArray( attributes.uv );
  22054. _gl.disable( _gl.CULL_FACE );
  22055. _gl.enable( _gl.BLEND );
  22056. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  22057. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22058. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22059. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  22060. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22061. _gl.activeTexture( _gl.TEXTURE0 );
  22062. _gl.uniform1i( uniforms.map, 0 );
  22063. var oldFogType = 0;
  22064. var sceneFogType = 0;
  22065. var fog = scene.fog;
  22066. if ( fog ) {
  22067. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22068. if ( fog instanceof THREE.Fog ) {
  22069. _gl.uniform1f( uniforms.fogNear, fog.near );
  22070. _gl.uniform1f( uniforms.fogFar, fog.far );
  22071. _gl.uniform1i( uniforms.fogType, 1 );
  22072. oldFogType = 1;
  22073. sceneFogType = 1;
  22074. } else if ( fog instanceof THREE.FogExp2 ) {
  22075. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22076. _gl.uniform1i( uniforms.fogType, 2 );
  22077. oldFogType = 2;
  22078. sceneFogType = 2;
  22079. }
  22080. } else {
  22081. _gl.uniform1i( uniforms.fogType, 0 );
  22082. oldFogType = 0;
  22083. sceneFogType = 0;
  22084. }
  22085. // update positions and sort
  22086. var i, sprite, material, screenPosition, size, fogType, scale = [];
  22087. for( i = 0; i < nSprites; i ++ ) {
  22088. sprite = sprites[ i ];
  22089. material = sprite.material;
  22090. if ( ! sprite.visible || material.opacity === 0 ) continue;
  22091. if ( ! material.useScreenCoordinates ) {
  22092. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22093. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22094. } else {
  22095. sprite.z = - sprite.position.z;
  22096. }
  22097. }
  22098. sprites.sort( painterSortStable );
  22099. // render all sprites
  22100. for( i = 0; i < nSprites; i ++ ) {
  22101. sprite = sprites[ i ];
  22102. material = sprite.material;
  22103. if ( ! sprite.visible || material.opacity === 0 ) continue;
  22104. if ( material.map && material.map.image && material.map.image.width ) {
  22105. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22106. if ( material.useScreenCoordinates === true ) {
  22107. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  22108. _gl.uniform3f(
  22109. uniforms.screenPosition,
  22110. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  22111. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  22112. Math.max( 0, Math.min( 1, sprite.position.z ) )
  22113. );
  22114. scale[ 0 ] = _renderer.devicePixelRatio;
  22115. scale[ 1 ] = _renderer.devicePixelRatio;
  22116. } else {
  22117. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  22118. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  22119. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22120. scale[ 0 ] = 1;
  22121. scale[ 1 ] = 1;
  22122. }
  22123. if ( scene.fog && material.fog ) {
  22124. fogType = sceneFogType;
  22125. } else {
  22126. fogType = 0;
  22127. }
  22128. if ( oldFogType !== fogType ) {
  22129. _gl.uniform1i( uniforms.fogType, fogType );
  22130. oldFogType = fogType;
  22131. }
  22132. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  22133. scale[ 0 ] *= size * invAspect * sprite.scale.x
  22134. scale[ 1 ] *= size * sprite.scale.y;
  22135. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  22136. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  22137. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  22138. _gl.uniform1f( uniforms.opacity, material.opacity );
  22139. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22140. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  22141. _gl.uniform2fv( uniforms.scale, scale );
  22142. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22143. _renderer.setDepthTest( material.depthTest );
  22144. _renderer.setDepthWrite( material.depthWrite );
  22145. _renderer.setTexture( material.map, 0 );
  22146. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22147. }
  22148. }
  22149. // restore gl
  22150. _gl.enable( _gl.CULL_FACE );
  22151. };
  22152. function createProgram ( shader, precision ) {
  22153. var program = _gl.createProgram();
  22154. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22155. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22156. var prefix = "precision " + precision + " float;\n";
  22157. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  22158. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  22159. _gl.compileShader( fragmentShader );
  22160. _gl.compileShader( vertexShader );
  22161. _gl.attachShader( program, fragmentShader );
  22162. _gl.attachShader( program, vertexShader );
  22163. _gl.linkProgram( program );
  22164. return program;
  22165. };
  22166. function painterSortStable ( a, b ) {
  22167. if ( a.z !== b.z ) {
  22168. return b.z - a.z;
  22169. } else {
  22170. return b.id - a.id;
  22171. }
  22172. };
  22173. };
  22174. /**
  22175. * @author alteredq / http://alteredqualia.com/
  22176. */
  22177. THREE.DepthPassPlugin = function () {
  22178. this.enabled = false;
  22179. this.renderTarget = null;
  22180. var _gl,
  22181. _renderer,
  22182. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22183. _frustum = new THREE.Frustum(),
  22184. _projScreenMatrix = new THREE.Matrix4();
  22185. this.init = function ( renderer ) {
  22186. _gl = renderer.context;
  22187. _renderer = renderer;
  22188. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22189. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22190. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22191. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22192. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22193. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22194. _depthMaterial._shadowPass = true;
  22195. _depthMaterialMorph._shadowPass = true;
  22196. _depthMaterialSkin._shadowPass = true;
  22197. _depthMaterialMorphSkin._shadowPass = true;
  22198. };
  22199. this.render = function ( scene, camera ) {
  22200. if ( ! this.enabled ) return;
  22201. this.update( scene, camera );
  22202. };
  22203. this.update = function ( scene, camera ) {
  22204. var i, il, j, jl, n,
  22205. program, buffer, material,
  22206. webglObject, object, light,
  22207. renderList,
  22208. fog = null;
  22209. // set GL state for depth map
  22210. _gl.clearColor( 1, 1, 1, 1 );
  22211. _gl.disable( _gl.BLEND );
  22212. _renderer.setDepthTest( true );
  22213. // update scene
  22214. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22215. // update camera matrices and frustum
  22216. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22217. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22218. _frustum.setFromMatrix( _projScreenMatrix );
  22219. // render depth map
  22220. _renderer.setRenderTarget( this.renderTarget );
  22221. _renderer.clear();
  22222. // set object matrices & frustum culling
  22223. renderList = scene.__webglObjects;
  22224. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22225. webglObject = renderList[ j ];
  22226. object = webglObject.object;
  22227. webglObject.render = false;
  22228. if ( object.visible ) {
  22229. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22230. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22231. webglObject.render = true;
  22232. }
  22233. }
  22234. }
  22235. // render regular objects
  22236. var objectMaterial, useMorphing, useSkinning;
  22237. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22238. webglObject = renderList[ j ];
  22239. if ( webglObject.render ) {
  22240. object = webglObject.object;
  22241. buffer = webglObject.buffer;
  22242. // todo: create proper depth material for particles
  22243. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22244. objectMaterial = getObjectMaterial( object );
  22245. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22246. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22247. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22248. if ( object.customDepthMaterial ) {
  22249. material = object.customDepthMaterial;
  22250. } else if ( useSkinning ) {
  22251. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22252. } else if ( useMorphing ) {
  22253. material = _depthMaterialMorph;
  22254. } else {
  22255. material = _depthMaterial;
  22256. }
  22257. if ( buffer instanceof THREE.BufferGeometry ) {
  22258. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22259. } else {
  22260. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22261. }
  22262. }
  22263. }
  22264. // set matrices and render immediate objects
  22265. renderList = scene.__webglObjectsImmediate;
  22266. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22267. webglObject = renderList[ j ];
  22268. object = webglObject.object;
  22269. if ( object.visible ) {
  22270. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22271. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22272. }
  22273. }
  22274. // restore GL state
  22275. var clearColor = _renderer.getClearColor(),
  22276. clearAlpha = _renderer.getClearAlpha();
  22277. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22278. _gl.enable( _gl.BLEND );
  22279. };
  22280. // For the moment just ignore objects that have multiple materials with different animation methods
  22281. // Only the first material will be taken into account for deciding which depth material to use
  22282. function getObjectMaterial( object ) {
  22283. return object.material instanceof THREE.MeshFaceMaterial
  22284. ? object.material.materials[ 0 ]
  22285. : object.material;
  22286. };
  22287. };
  22288. /**
  22289. * @author mikael emtinger / http://gomo.se/
  22290. */
  22291. THREE.ShaderFlares = {
  22292. 'lensFlareVertexTexture': {
  22293. vertexShader: [
  22294. "uniform lowp int renderType;",
  22295. "uniform vec3 screenPosition;",
  22296. "uniform vec2 scale;",
  22297. "uniform float rotation;",
  22298. "uniform sampler2D occlusionMap;",
  22299. "attribute vec2 position;",
  22300. "attribute vec2 uv;",
  22301. "varying vec2 vUV;",
  22302. "varying float vVisibility;",
  22303. "void main() {",
  22304. "vUV = uv;",
  22305. "vec2 pos = position;",
  22306. "if( renderType == 2 ) {",
  22307. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22308. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22309. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22310. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22311. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22312. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22313. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22314. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22315. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22316. "vVisibility = visibility.r / 9.0;",
  22317. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22318. "vVisibility *= visibility.b / 9.0;",
  22319. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22320. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22321. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22322. "}",
  22323. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22324. "}"
  22325. ].join( "\n" ),
  22326. fragmentShader: [
  22327. "uniform lowp int renderType;",
  22328. "uniform sampler2D map;",
  22329. "uniform float opacity;",
  22330. "uniform vec3 color;",
  22331. "varying vec2 vUV;",
  22332. "varying float vVisibility;",
  22333. "void main() {",
  22334. // pink square
  22335. "if( renderType == 0 ) {",
  22336. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22337. // restore
  22338. "} else if( renderType == 1 ) {",
  22339. "gl_FragColor = texture2D( map, vUV );",
  22340. // flare
  22341. "} else {",
  22342. "vec4 texture = texture2D( map, vUV );",
  22343. "texture.a *= opacity * vVisibility;",
  22344. "gl_FragColor = texture;",
  22345. "gl_FragColor.rgb *= color;",
  22346. "}",
  22347. "}"
  22348. ].join( "\n" )
  22349. },
  22350. 'lensFlare': {
  22351. vertexShader: [
  22352. "uniform lowp int renderType;",
  22353. "uniform vec3 screenPosition;",
  22354. "uniform vec2 scale;",
  22355. "uniform float rotation;",
  22356. "attribute vec2 position;",
  22357. "attribute vec2 uv;",
  22358. "varying vec2 vUV;",
  22359. "void main() {",
  22360. "vUV = uv;",
  22361. "vec2 pos = position;",
  22362. "if( renderType == 2 ) {",
  22363. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22364. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22365. "}",
  22366. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22367. "}"
  22368. ].join( "\n" ),
  22369. fragmentShader: [
  22370. "precision mediump float;",
  22371. "uniform lowp int renderType;",
  22372. "uniform sampler2D map;",
  22373. "uniform sampler2D occlusionMap;",
  22374. "uniform float opacity;",
  22375. "uniform vec3 color;",
  22376. "varying vec2 vUV;",
  22377. "void main() {",
  22378. // pink square
  22379. "if( renderType == 0 ) {",
  22380. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22381. // restore
  22382. "} else if( renderType == 1 ) {",
  22383. "gl_FragColor = texture2D( map, vUV );",
  22384. // flare
  22385. "} else {",
  22386. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22387. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22388. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22389. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22390. "visibility = ( 1.0 - visibility / 4.0 );",
  22391. "vec4 texture = texture2D( map, vUV );",
  22392. "texture.a *= opacity * visibility;",
  22393. "gl_FragColor = texture;",
  22394. "gl_FragColor.rgb *= color;",
  22395. "}",
  22396. "}"
  22397. ].join( "\n" )
  22398. }
  22399. };
  22400. /**
  22401. * @author mikael emtinger / http://gomo.se/
  22402. * @author alteredq / http://alteredqualia.com/
  22403. *
  22404. */
  22405. THREE.ShaderSprite = {
  22406. 'sprite': {
  22407. vertexShader: [
  22408. "uniform int useScreenCoordinates;",
  22409. "uniform int sizeAttenuation;",
  22410. "uniform vec3 screenPosition;",
  22411. "uniform mat4 modelViewMatrix;",
  22412. "uniform mat4 projectionMatrix;",
  22413. "uniform float rotation;",
  22414. "uniform vec2 scale;",
  22415. "uniform vec2 alignment;",
  22416. "uniform vec2 uvOffset;",
  22417. "uniform vec2 uvScale;",
  22418. "attribute vec2 position;",
  22419. "attribute vec2 uv;",
  22420. "varying vec2 vUV;",
  22421. "void main() {",
  22422. "vUV = uvOffset + uv * uvScale;",
  22423. "vec2 alignedPosition = position + alignment;",
  22424. "vec2 rotatedPosition;",
  22425. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22426. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22427. "vec4 finalPosition;",
  22428. "if( useScreenCoordinates != 0 ) {",
  22429. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22430. "} else {",
  22431. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22432. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  22433. "}",
  22434. "gl_Position = finalPosition;",
  22435. "}"
  22436. ].join( "\n" ),
  22437. fragmentShader: [
  22438. "uniform vec3 color;",
  22439. "uniform sampler2D map;",
  22440. "uniform float opacity;",
  22441. "uniform int fogType;",
  22442. "uniform vec3 fogColor;",
  22443. "uniform float fogDensity;",
  22444. "uniform float fogNear;",
  22445. "uniform float fogFar;",
  22446. "uniform float alphaTest;",
  22447. "varying vec2 vUV;",
  22448. "void main() {",
  22449. "vec4 texture = texture2D( map, vUV );",
  22450. "if ( texture.a < alphaTest ) discard;",
  22451. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22452. "if ( fogType > 0 ) {",
  22453. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22454. "float fogFactor = 0.0;",
  22455. "if ( fogType == 1 ) {",
  22456. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22457. "} else {",
  22458. "const float LOG2 = 1.442695;",
  22459. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22460. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22461. "}",
  22462. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22463. "}",
  22464. "}"
  22465. ].join( "\n" )
  22466. }
  22467. };