three.js 833 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '54dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. // Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
  16. // not sure we should have this, or at least not have it here
  17. // http://stackoverflow.com/questions/646628/javascript-startswith
  18. // http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
  19. // http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
  20. String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
  21. return this.slice( 0, str.length ) === str;
  22. };
  23. String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
  24. var t = String( str );
  25. var index = this.lastIndexOf( t );
  26. return ( -1 < index && index ) === (this.length - t.length);
  27. };
  28. String.prototype.trim = String.prototype.trim || function () {
  29. return this.replace( /^\s+|\s+$/g, '' );
  30. };
  31. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  32. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  33. // requestAnimationFrame polyfill by Erik Möller
  34. // fixes from Paul Irish and Tino Zijdel
  35. ( function () {
  36. var lastTime = 0;
  37. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  38. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  39. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  40. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  41. }
  42. if ( window.requestAnimationFrame === undefined ) {
  43. window.requestAnimationFrame = function ( callback, element ) {
  44. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  45. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  46. lastTime = currTime + timeToCall;
  47. return id;
  48. };
  49. }
  50. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  51. }() );
  52. // GL STATE CONSTANTS
  53. THREE.CullFaceNone = 0;
  54. THREE.CullFaceBack = 1;
  55. THREE.CullFaceFront = 2;
  56. THREE.CullFaceFrontBack = 3;
  57. THREE.FrontFaceDirectionCW = 0;
  58. THREE.FrontFaceDirectionCCW = 1;
  59. // MATERIAL CONSTANTS
  60. // side
  61. THREE.FrontSide = 0;
  62. THREE.BackSide = 1;
  63. THREE.DoubleSide = 2;
  64. // shading
  65. THREE.NoShading = 0;
  66. THREE.FlatShading = 1;
  67. THREE.SmoothShading = 2;
  68. // colors
  69. THREE.NoColors = 0;
  70. THREE.FaceColors = 1;
  71. THREE.VertexColors = 2;
  72. // blending modes
  73. THREE.NoBlending = 0;
  74. THREE.NormalBlending = 1;
  75. THREE.AdditiveBlending = 2;
  76. THREE.SubtractiveBlending = 3;
  77. THREE.MultiplyBlending = 4;
  78. THREE.CustomBlending = 5;
  79. // custom blending equations
  80. // (numbers start from 100 not to clash with other
  81. // mappings to OpenGL constants defined in Texture.js)
  82. THREE.AddEquation = 100;
  83. THREE.SubtractEquation = 101;
  84. THREE.ReverseSubtractEquation = 102;
  85. // custom blending destination factors
  86. THREE.ZeroFactor = 200;
  87. THREE.OneFactor = 201;
  88. THREE.SrcColorFactor = 202;
  89. THREE.OneMinusSrcColorFactor = 203;
  90. THREE.SrcAlphaFactor = 204;
  91. THREE.OneMinusSrcAlphaFactor = 205;
  92. THREE.DstAlphaFactor = 206;
  93. THREE.OneMinusDstAlphaFactor = 207;
  94. // custom blending source factors
  95. //THREE.ZeroFactor = 200;
  96. //THREE.OneFactor = 201;
  97. //THREE.SrcAlphaFactor = 204;
  98. //THREE.OneMinusSrcAlphaFactor = 205;
  99. //THREE.DstAlphaFactor = 206;
  100. //THREE.OneMinusDstAlphaFactor = 207;
  101. THREE.DstColorFactor = 208;
  102. THREE.OneMinusDstColorFactor = 209;
  103. THREE.SrcAlphaSaturateFactor = 210;
  104. // TEXTURE CONSTANTS
  105. THREE.MultiplyOperation = 0;
  106. THREE.MixOperation = 1;
  107. THREE.AddOperation = 2;
  108. // Mapping modes
  109. THREE.UVMapping = function () {};
  110. THREE.CubeReflectionMapping = function () {};
  111. THREE.CubeRefractionMapping = function () {};
  112. THREE.SphericalReflectionMapping = function () {};
  113. THREE.SphericalRefractionMapping = function () {};
  114. // Wrapping modes
  115. THREE.RepeatWrapping = 1000;
  116. THREE.ClampToEdgeWrapping = 1001;
  117. THREE.MirroredRepeatWrapping = 1002;
  118. // Filters
  119. THREE.NearestFilter = 1003;
  120. THREE.NearestMipMapNearestFilter = 1004;
  121. THREE.NearestMipMapLinearFilter = 1005;
  122. THREE.LinearFilter = 1006;
  123. THREE.LinearMipMapNearestFilter = 1007;
  124. THREE.LinearMipMapLinearFilter = 1008;
  125. // Data types
  126. THREE.UnsignedByteType = 1009;
  127. THREE.ByteType = 1010;
  128. THREE.ShortType = 1011;
  129. THREE.UnsignedShortType = 1012;
  130. THREE.IntType = 1013;
  131. THREE.UnsignedIntType = 1014;
  132. THREE.FloatType = 1015;
  133. // Pixel types
  134. //THREE.UnsignedByteType = 1009;
  135. THREE.UnsignedShort4444Type = 1016;
  136. THREE.UnsignedShort5551Type = 1017;
  137. THREE.UnsignedShort565Type = 1018;
  138. // Pixel formats
  139. THREE.AlphaFormat = 1019;
  140. THREE.RGBFormat = 1020;
  141. THREE.RGBAFormat = 1021;
  142. THREE.LuminanceFormat = 1022;
  143. THREE.LuminanceAlphaFormat = 1023;
  144. // Compressed texture formats
  145. THREE.RGB_S3TC_DXT1_Format = 2001;
  146. THREE.RGBA_S3TC_DXT1_Format = 2002;
  147. THREE.RGBA_S3TC_DXT3_Format = 2003;
  148. THREE.RGBA_S3TC_DXT5_Format = 2004;
  149. /*
  150. // Potential future PVRTC compressed texture formats
  151. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  152. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  153. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  154. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  155. */
  156. /**
  157. * @author alteredq / http://alteredqualia.com/
  158. */
  159. THREE.Clock = function ( autoStart ) {
  160. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  161. this.startTime = 0;
  162. this.oldTime = 0;
  163. this.elapsedTime = 0;
  164. this.running = false;
  165. };
  166. THREE.Clock.prototype.start = function () {
  167. this.startTime = Date.now();
  168. this.oldTime = this.startTime;
  169. this.running = true;
  170. };
  171. THREE.Clock.prototype.stop = function () {
  172. this.getElapsedTime();
  173. this.running = false;
  174. };
  175. THREE.Clock.prototype.getElapsedTime = function () {
  176. this.getDelta();
  177. return this.elapsedTime;
  178. };
  179. THREE.Clock.prototype.getDelta = function () {
  180. var diff = 0;
  181. if ( this.autoStart && ! this.running ) {
  182. this.start();
  183. }
  184. if ( this.running ) {
  185. var newTime = Date.now();
  186. diff = 0.001 * ( newTime - this.oldTime );
  187. this.oldTime = newTime;
  188. this.elapsedTime += diff;
  189. }
  190. return diff;
  191. };/**
  192. * @author mrdoob / http://mrdoob.com/
  193. */
  194. THREE.Color = function ( value ) {
  195. if ( value !== undefined ) this.set( value );
  196. return this;
  197. };
  198. THREE.Color.prototype = {
  199. constructor: THREE.Color,
  200. r: 1, g: 1, b: 1,
  201. copy: function ( color ) {
  202. this.r = color.r;
  203. this.g = color.g;
  204. this.b = color.b;
  205. return this;
  206. },
  207. copyGammaToLinear: function ( color ) {
  208. this.r = color.r * color.r;
  209. this.g = color.g * color.g;
  210. this.b = color.b * color.b;
  211. return this;
  212. },
  213. copyLinearToGamma: function ( color ) {
  214. this.r = Math.sqrt( color.r );
  215. this.g = Math.sqrt( color.g );
  216. this.b = Math.sqrt( color.b );
  217. return this;
  218. },
  219. convertGammaToLinear: function () {
  220. var r = this.r, g = this.g, b = this.b;
  221. this.r = r * r;
  222. this.g = g * g;
  223. this.b = b * b;
  224. return this;
  225. },
  226. convertLinearToGamma: function () {
  227. this.r = Math.sqrt( this.r );
  228. this.g = Math.sqrt( this.g );
  229. this.b = Math.sqrt( this.b );
  230. return this;
  231. },
  232. set: function ( value ) {
  233. switch ( typeof value ) {
  234. case "number":
  235. this.setHex( value );
  236. break;
  237. case "string":
  238. this.setStyle( value );
  239. break;
  240. }
  241. },
  242. setRGB: function ( r, g, b ) {
  243. this.r = r;
  244. this.g = g;
  245. this.b = b;
  246. return this;
  247. },
  248. setHSV: function ( h, s, v ) {
  249. // based on MochiKit implementation by Bob Ippolito
  250. // h,s,v ranges are < 0.0 - 1.0 >
  251. var i, f, p, q, t;
  252. if ( v === 0 ) {
  253. this.r = this.g = this.b = 0;
  254. } else {
  255. i = Math.floor( h * 6 );
  256. f = ( h * 6 ) - i;
  257. p = v * ( 1 - s );
  258. q = v * ( 1 - ( s * f ) );
  259. t = v * ( 1 - ( s * ( 1 - f ) ) );
  260. if ( i === 0 ) {
  261. this.r = v;
  262. this.g = t;
  263. this.b = p;
  264. } else if ( i === 1 ) {
  265. this.r = q;
  266. this.g = v;
  267. this.b = p;
  268. } else if ( i === 2 ) {
  269. this.r = p;
  270. this.g = v;
  271. this.b = t;
  272. } else if ( i === 3 ) {
  273. this.r = p;
  274. this.g = q;
  275. this.b = v;
  276. } else if ( i === 4 ) {
  277. this.r = t;
  278. this.g = p;
  279. this.b = v;
  280. } else if ( i === 5 ) {
  281. this.r = v;
  282. this.g = p;
  283. this.b = q;
  284. }
  285. }
  286. return this;
  287. },
  288. getHex: function () {
  289. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  290. },
  291. setHex: function ( hex ) {
  292. hex = Math.floor( hex );
  293. this.r = ( hex >> 16 & 255 ) / 255;
  294. this.g = ( hex >> 8 & 255 ) / 255;
  295. this.b = ( hex & 255 ) / 255;
  296. return this;
  297. },
  298. getHexString: function () {
  299. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  300. },
  301. getStyle: function () {
  302. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  303. },
  304. setStyle: function ( style ) {
  305. // rgb(255,0,0)
  306. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  307. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  308. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  309. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  310. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  311. return this;
  312. }
  313. // rgb(100%,0%,0%)
  314. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  315. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  316. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  317. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  318. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  319. return this;
  320. }
  321. // #ff0000
  322. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  323. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  324. this.setHex( parseInt( color[ 1 ], 16 ) );
  325. return this;
  326. }
  327. // #f00
  328. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  329. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  330. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  331. return this;
  332. }
  333. // red
  334. if ( /^(\w+)$/i.test( style ) ) {
  335. this.setHex( THREE.ColorKeywords[ style ] );
  336. return this;
  337. }
  338. },
  339. getHSV: function ( hsv ) {
  340. // based on MochiKit implementation by Bob Ippolito
  341. // h,s,v ranges are < 0.0 - 1.0 >
  342. var r = this.r;
  343. var g = this.g;
  344. var b = this.b;
  345. var max = Math.max( Math.max( r, g ), b );
  346. var min = Math.min( Math.min( r, g ), b );
  347. var hue;
  348. var saturation;
  349. var value = max;
  350. if ( min === max ) {
  351. hue = 0;
  352. saturation = 0;
  353. } else {
  354. var delta = ( max - min );
  355. saturation = delta / max;
  356. if ( r === max ) {
  357. hue = ( g - b ) / delta;
  358. } else if ( g === max ) {
  359. hue = 2 + ( ( b - r ) / delta );
  360. } else {
  361. hue = 4 + ( ( r - g ) / delta );
  362. }
  363. hue /= 6;
  364. if ( hue < 0 ) {
  365. hue += 1;
  366. }
  367. if ( hue > 1 ) {
  368. hue -= 1;
  369. }
  370. }
  371. if ( hsv === undefined ) {
  372. hsv = { h: 0, s: 0, v: 0 };
  373. }
  374. hsv.h = hue;
  375. hsv.s = saturation;
  376. hsv.v = value;
  377. return hsv;
  378. },
  379. lerpSelf: function ( color, alpha ) {
  380. this.r += ( color.r - this.r ) * alpha;
  381. this.g += ( color.g - this.g ) * alpha;
  382. this.b += ( color.b - this.b ) * alpha;
  383. return this;
  384. },
  385. clone: function () {
  386. return new THREE.Color().setRGB( this.r, this.g, this.b );
  387. }
  388. };
  389. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF, "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2, "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50, "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B, "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B, "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F, "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3, "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222, "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700, "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4, "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00, "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3, "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA, "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32, "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3, "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC, "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD, "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6, "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9, "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F, "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE, "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA, "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0, "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  390. /**
  391. * @author mrdoob / http://mrdoob.com/
  392. * @author philogb / http://blog.thejit.org/
  393. * @author egraether / http://egraether.com/
  394. * @author zz85 / http://www.lab4games.net/zz85/blog
  395. */
  396. THREE.Vector2 = function ( x, y ) {
  397. this.x = x || 0;
  398. this.y = y || 0;
  399. };
  400. THREE.Vector2.prototype = {
  401. constructor: THREE.Vector2,
  402. set: function ( x, y ) {
  403. this.x = x;
  404. this.y = y;
  405. return this;
  406. },
  407. copy: function ( v ) {
  408. this.x = v.x;
  409. this.y = v.y;
  410. return this;
  411. },
  412. add: function ( a, b ) {
  413. this.x = a.x + b.x;
  414. this.y = a.y + b.y;
  415. return this;
  416. },
  417. addSelf: function ( v ) {
  418. this.x += v.x;
  419. this.y += v.y;
  420. return this;
  421. },
  422. sub: function ( a, b ) {
  423. this.x = a.x - b.x;
  424. this.y = a.y - b.y;
  425. return this;
  426. },
  427. subSelf: function ( v ) {
  428. this.x -= v.x;
  429. this.y -= v.y;
  430. return this;
  431. },
  432. multiplyScalar: function ( s ) {
  433. this.x *= s;
  434. this.y *= s;
  435. return this;
  436. },
  437. divideScalar: function ( s ) {
  438. if ( s ) {
  439. this.x /= s;
  440. this.y /= s;
  441. } else {
  442. this.set( 0, 0 );
  443. }
  444. return this;
  445. },
  446. negate: function() {
  447. return this.multiplyScalar( - 1 );
  448. },
  449. dot: function ( v ) {
  450. return this.x * v.x + this.y * v.y;
  451. },
  452. lengthSq: function () {
  453. return this.x * this.x + this.y * this.y;
  454. },
  455. length: function () {
  456. return Math.sqrt( this.lengthSq() );
  457. },
  458. normalize: function () {
  459. return this.divideScalar( this.length() );
  460. },
  461. distanceTo: function ( v ) {
  462. return Math.sqrt( this.distanceToSquared( v ) );
  463. },
  464. distanceToSquared: function ( v ) {
  465. var dx = this.x - v.x, dy = this.y - v.y;
  466. return dx * dx + dy * dy;
  467. },
  468. setLength: function ( l ) {
  469. return this.normalize().multiplyScalar( l );
  470. },
  471. lerpSelf: function ( v, alpha ) {
  472. this.x += ( v.x - this.x ) * alpha;
  473. this.y += ( v.y - this.y ) * alpha;
  474. return this;
  475. },
  476. equals: function( v ) {
  477. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  478. },
  479. clone: function () {
  480. return new THREE.Vector2( this.x, this.y );
  481. }
  482. };
  483. /**
  484. * @author mrdoob / http://mrdoob.com/
  485. * @author kile / http://kile.stravaganza.org/
  486. * @author philogb / http://blog.thejit.org/
  487. * @author mikael emtinger / http://gomo.se/
  488. * @author egraether / http://egraether.com/
  489. * @author WestLangley / http://github.com/WestLangley
  490. */
  491. THREE.Vector3 = function ( x, y, z ) {
  492. this.x = x || 0;
  493. this.y = y || 0;
  494. this.z = z || 0;
  495. };
  496. THREE.Vector3.prototype = {
  497. constructor: THREE.Vector3,
  498. set: function ( x, y, z ) {
  499. this.x = x;
  500. this.y = y;
  501. this.z = z;
  502. return this;
  503. },
  504. setX: function ( x ) {
  505. this.x = x;
  506. return this;
  507. },
  508. setY: function ( y ) {
  509. this.y = y;
  510. return this;
  511. },
  512. setZ: function ( z ) {
  513. this.z = z;
  514. return this;
  515. },
  516. copy: function ( v ) {
  517. this.x = v.x;
  518. this.y = v.y;
  519. this.z = v.z;
  520. return this;
  521. },
  522. add: function ( a, b ) {
  523. this.x = a.x + b.x;
  524. this.y = a.y + b.y;
  525. this.z = a.z + b.z;
  526. return this;
  527. },
  528. addSelf: function ( v ) {
  529. this.x += v.x;
  530. this.y += v.y;
  531. this.z += v.z;
  532. return this;
  533. },
  534. addScalar: function ( s ) {
  535. this.x += s;
  536. this.y += s;
  537. this.z += s;
  538. return this;
  539. },
  540. sub: function ( a, b ) {
  541. this.x = a.x - b.x;
  542. this.y = a.y - b.y;
  543. this.z = a.z - b.z;
  544. return this;
  545. },
  546. subSelf: function ( v ) {
  547. this.x -= v.x;
  548. this.y -= v.y;
  549. this.z -= v.z;
  550. return this;
  551. },
  552. multiply: function ( a, b ) {
  553. this.x = a.x * b.x;
  554. this.y = a.y * b.y;
  555. this.z = a.z * b.z;
  556. return this;
  557. },
  558. multiplySelf: function ( v ) {
  559. this.x *= v.x;
  560. this.y *= v.y;
  561. this.z *= v.z;
  562. return this;
  563. },
  564. multiplyScalar: function ( s ) {
  565. this.x *= s;
  566. this.y *= s;
  567. this.z *= s;
  568. return this;
  569. },
  570. divideSelf: function ( v ) {
  571. this.x /= v.x;
  572. this.y /= v.y;
  573. this.z /= v.z;
  574. return this;
  575. },
  576. divideScalar: function ( s ) {
  577. if ( s ) {
  578. this.x /= s;
  579. this.y /= s;
  580. this.z /= s;
  581. } else {
  582. this.x = 0;
  583. this.y = 0;
  584. this.z = 0;
  585. }
  586. return this;
  587. },
  588. negate: function() {
  589. return this.multiplyScalar( - 1 );
  590. },
  591. dot: function ( v ) {
  592. return this.x * v.x + this.y * v.y + this.z * v.z;
  593. },
  594. lengthSq: function () {
  595. return this.x * this.x + this.y * this.y + this.z * this.z;
  596. },
  597. length: function () {
  598. return Math.sqrt( this.lengthSq() );
  599. },
  600. lengthManhattan: function () {
  601. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  602. },
  603. normalize: function () {
  604. return this.divideScalar( this.length() );
  605. },
  606. setLength: function ( l ) {
  607. return this.normalize().multiplyScalar( l );
  608. },
  609. lerpSelf: function ( v, alpha ) {
  610. this.x += ( v.x - this.x ) * alpha;
  611. this.y += ( v.y - this.y ) * alpha;
  612. this.z += ( v.z - this.z ) * alpha;
  613. return this;
  614. },
  615. cross: function ( a, b ) {
  616. this.x = a.y * b.z - a.z * b.y;
  617. this.y = a.z * b.x - a.x * b.z;
  618. this.z = a.x * b.y - a.y * b.x;
  619. return this;
  620. },
  621. crossSelf: function ( v ) {
  622. var x = this.x, y = this.y, z = this.z;
  623. this.x = y * v.z - z * v.y;
  624. this.y = z * v.x - x * v.z;
  625. this.z = x * v.y - y * v.x;
  626. return this;
  627. },
  628. angleTo: function ( v ) {
  629. return Math.acos( this.dot( v ) / this.length() / v.length() );
  630. },
  631. distanceTo: function ( v ) {
  632. return Math.sqrt( this.distanceToSquared( v ) );
  633. },
  634. distanceToSquared: function ( v ) {
  635. return new THREE.Vector3().sub( this, v ).lengthSq();
  636. },
  637. getPositionFromMatrix: function ( m ) {
  638. this.x = m.elements[12];
  639. this.y = m.elements[13];
  640. this.z = m.elements[14];
  641. return this;
  642. },
  643. setEulerFromRotationMatrix: function ( m, order ) {
  644. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  645. // clamp, to handle numerical problems
  646. function clamp( x ) {
  647. return Math.min( Math.max( x, -1 ), 1 );
  648. }
  649. var te = m.elements;
  650. var m11 = te[0], m12 = te[4], m13 = te[8];
  651. var m21 = te[1], m22 = te[5], m23 = te[9];
  652. var m31 = te[2], m32 = te[6], m33 = te[10];
  653. if ( order === undefined || order === 'XYZ' ) {
  654. this.y = Math.asin( clamp( m13 ) );
  655. if ( Math.abs( m13 ) < 0.99999 ) {
  656. this.x = Math.atan2( - m23, m33 );
  657. this.z = Math.atan2( - m12, m11 );
  658. } else {
  659. this.x = Math.atan2( m32, m22 );
  660. this.z = 0;
  661. }
  662. } else if ( order === 'YXZ' ) {
  663. this.x = Math.asin( - clamp( m23 ) );
  664. if ( Math.abs( m23 ) < 0.99999 ) {
  665. this.y = Math.atan2( m13, m33 );
  666. this.z = Math.atan2( m21, m22 );
  667. } else {
  668. this.y = Math.atan2( - m31, m11 );
  669. this.z = 0;
  670. }
  671. } else if ( order === 'ZXY' ) {
  672. this.x = Math.asin( clamp( m32 ) );
  673. if ( Math.abs( m32 ) < 0.99999 ) {
  674. this.y = Math.atan2( - m31, m33 );
  675. this.z = Math.atan2( - m12, m22 );
  676. } else {
  677. this.y = 0;
  678. this.z = Math.atan2( m21, m11 );
  679. }
  680. } else if ( order === 'ZYX' ) {
  681. this.y = Math.asin( - clamp( m31 ) );
  682. if ( Math.abs( m31 ) < 0.99999 ) {
  683. this.x = Math.atan2( m32, m33 );
  684. this.z = Math.atan2( m21, m11 );
  685. } else {
  686. this.x = 0;
  687. this.z = Math.atan2( - m12, m22 );
  688. }
  689. } else if ( order === 'YZX' ) {
  690. this.z = Math.asin( clamp( m21 ) );
  691. if ( Math.abs( m21 ) < 0.99999 ) {
  692. this.x = Math.atan2( - m23, m22 );
  693. this.y = Math.atan2( - m31, m11 );
  694. } else {
  695. this.x = 0;
  696. this.y = Math.atan2( m13, m33 );
  697. }
  698. } else if ( order === 'XZY' ) {
  699. this.z = Math.asin( - clamp( m12 ) );
  700. if ( Math.abs( m12 ) < 0.99999 ) {
  701. this.x = Math.atan2( m32, m22 );
  702. this.y = Math.atan2( m13, m11 );
  703. } else {
  704. this.x = Math.atan2( - m23, m33 );
  705. this.y = 0;
  706. }
  707. }
  708. return this;
  709. },
  710. setEulerFromQuaternion: function ( q, order ) {
  711. // q is assumed to be normalized
  712. // clamp, to handle numerical problems
  713. function clamp( x ) {
  714. return Math.min( Math.max( x, -1 ), 1 );
  715. }
  716. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  717. var sqx = q.x * q.x;
  718. var sqy = q.y * q.y;
  719. var sqz = q.z * q.z;
  720. var sqw = q.w * q.w;
  721. if ( order === undefined || order === 'XYZ' ) {
  722. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  723. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  724. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  725. } else if ( order === 'YXZ' ) {
  726. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  727. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  728. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  729. } else if ( order === 'ZXY' ) {
  730. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  731. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  732. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  733. } else if ( order === 'ZYX' ) {
  734. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  735. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  736. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  737. } else if ( order === 'YZX' ) {
  738. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  739. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  740. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  741. } else if ( order === 'XZY' ) {
  742. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  743. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  744. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  745. }
  746. return this;
  747. },
  748. getScaleFromMatrix: function ( m ) {
  749. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  750. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  751. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  752. this.x = sx;
  753. this.y = sy;
  754. this.z = sz;
  755. return this;
  756. },
  757. equals: function ( v ) {
  758. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  759. },
  760. clone: function () {
  761. return new THREE.Vector3( this.x, this.y, this.z );
  762. }
  763. };
  764. /**
  765. * @author supereggbert / http://www.paulbrunt.co.uk/
  766. * @author philogb / http://blog.thejit.org/
  767. * @author mikael emtinger / http://gomo.se/
  768. * @author egraether / http://egraether.com/
  769. * @author WestLangley / http://github.com/WestLangley
  770. */
  771. THREE.Vector4 = function ( x, y, z, w ) {
  772. this.x = x || 0;
  773. this.y = y || 0;
  774. this.z = z || 0;
  775. this.w = ( w !== undefined ) ? w : 1;
  776. };
  777. THREE.Vector4.prototype = {
  778. constructor: THREE.Vector4,
  779. set: function ( x, y, z, w ) {
  780. this.x = x;
  781. this.y = y;
  782. this.z = z;
  783. this.w = w;
  784. return this;
  785. },
  786. copy: function ( v ) {
  787. this.x = v.x;
  788. this.y = v.y;
  789. this.z = v.z;
  790. this.w = ( v.w !== undefined ) ? v.w : 1;
  791. return this;
  792. },
  793. add: function ( a, b ) {
  794. this.x = a.x + b.x;
  795. this.y = a.y + b.y;
  796. this.z = a.z + b.z;
  797. this.w = a.w + b.w;
  798. return this;
  799. },
  800. addSelf: function ( v ) {
  801. this.x += v.x;
  802. this.y += v.y;
  803. this.z += v.z;
  804. this.w += v.w;
  805. return this;
  806. },
  807. sub: function ( a, b ) {
  808. this.x = a.x - b.x;
  809. this.y = a.y - b.y;
  810. this.z = a.z - b.z;
  811. this.w = a.w - b.w;
  812. return this;
  813. },
  814. subSelf: function ( v ) {
  815. this.x -= v.x;
  816. this.y -= v.y;
  817. this.z -= v.z;
  818. this.w -= v.w;
  819. return this;
  820. },
  821. multiplyScalar: function ( s ) {
  822. this.x *= s;
  823. this.y *= s;
  824. this.z *= s;
  825. this.w *= s;
  826. return this;
  827. },
  828. divideScalar: function ( s ) {
  829. if ( s ) {
  830. this.x /= s;
  831. this.y /= s;
  832. this.z /= s;
  833. this.w /= s;
  834. } else {
  835. this.x = 0;
  836. this.y = 0;
  837. this.z = 0;
  838. this.w = 1;
  839. }
  840. return this;
  841. },
  842. negate: function() {
  843. return this.multiplyScalar( -1 );
  844. },
  845. dot: function ( v ) {
  846. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  847. },
  848. lengthSq: function () {
  849. return this.dot( this );
  850. },
  851. length: function () {
  852. return Math.sqrt( this.lengthSq() );
  853. },
  854. lengthManhattan: function () {
  855. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  856. },
  857. normalize: function () {
  858. return this.divideScalar( this.length() );
  859. },
  860. setLength: function ( l ) {
  861. return this.normalize().multiplyScalar( l );
  862. },
  863. lerpSelf: function ( v, alpha ) {
  864. this.x += ( v.x - this.x ) * alpha;
  865. this.y += ( v.y - this.y ) * alpha;
  866. this.z += ( v.z - this.z ) * alpha;
  867. this.w += ( v.w - this.w ) * alpha;
  868. return this;
  869. },
  870. clone: function () {
  871. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  872. },
  873. setAxisAngleFromQuaternion: function ( q ) {
  874. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  875. // q is assumed to be normalized
  876. this.w = 2 * Math.acos( q.w );
  877. var s = Math.sqrt( 1 - q.w * q.w );
  878. if ( s < 0.0001 ) {
  879. this.x = 1;
  880. this.y = 0;
  881. this.z = 0;
  882. } else {
  883. this.x = q.x / s;
  884. this.y = q.y / s;
  885. this.z = q.z / s;
  886. }
  887. return this;
  888. },
  889. setAxisAngleFromRotationMatrix: function ( m ) {
  890. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  891. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  892. var angle, x, y, z, // variables for result
  893. epsilon = 0.01, // margin to allow for rounding errors
  894. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  895. te = m.elements,
  896. m11 = te[0], m12 = te[4], m13 = te[8],
  897. m21 = te[1], m22 = te[5], m23 = te[9],
  898. m31 = te[2], m32 = te[6], m33 = te[10];
  899. if ( ( Math.abs( m12 - m21 ) < epsilon )
  900. && ( Math.abs( m13 - m31 ) < epsilon )
  901. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  902. // singularity found
  903. // first check for identity matrix which must have +1 for all terms
  904. // in leading diagonal and zero in other terms
  905. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  906. && ( Math.abs( m13 + m31 ) < epsilon2 )
  907. && ( Math.abs( m23 + m32 ) < epsilon2 )
  908. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  909. // this singularity is identity matrix so angle = 0
  910. this.set( 1, 0, 0, 0 );
  911. return this; // zero angle, arbitrary axis
  912. }
  913. // otherwise this singularity is angle = 180
  914. angle = Math.PI;
  915. var xx = ( m11 + 1 ) / 2;
  916. var yy = ( m22 + 1 ) / 2;
  917. var zz = ( m33 + 1 ) / 2;
  918. var xy = ( m12 + m21 ) / 4;
  919. var xz = ( m13 + m31 ) / 4;
  920. var yz = ( m23 + m32 ) / 4;
  921. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  922. if ( xx < epsilon ) {
  923. x = 0;
  924. y = 0.707106781;
  925. z = 0.707106781;
  926. } else {
  927. x = Math.sqrt( xx );
  928. y = xy / x;
  929. z = xz / x;
  930. }
  931. } else if ( yy > zz ) { // m22 is the largest diagonal term
  932. if ( yy < epsilon ) {
  933. x = 0.707106781;
  934. y = 0;
  935. z = 0.707106781;
  936. } else {
  937. y = Math.sqrt( yy );
  938. x = xy / y;
  939. z = yz / y;
  940. }
  941. } else { // m33 is the largest diagonal term so base result on this
  942. if ( zz < epsilon ) {
  943. x = 0.707106781;
  944. y = 0.707106781;
  945. z = 0;
  946. } else {
  947. z = Math.sqrt( zz );
  948. x = xz / z;
  949. y = yz / z;
  950. }
  951. }
  952. this.set( x, y, z, angle );
  953. return this; // return 180 deg rotation
  954. }
  955. // as we have reached here there are no singularities so we can handle normally
  956. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  957. + ( m13 - m31 ) * ( m13 - m31 )
  958. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  959. if ( Math.abs( s ) < 0.001 ) s = 1;
  960. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  961. // caught by singularity test above, but I've left it in just in case
  962. this.x = ( m32 - m23 ) / s;
  963. this.y = ( m13 - m31 ) / s;
  964. this.z = ( m21 - m12 ) / s;
  965. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  966. return this;
  967. }
  968. };
  969. /**
  970. * @author alteredq / http://alteredqualia.com/
  971. * @author WestLangley / http://github.com/WestLangley
  972. */
  973. THREE.Matrix3 = function () {
  974. this.elements = new Float32Array(9);
  975. };
  976. THREE.Matrix3.prototype = {
  977. constructor: THREE.Matrix3,
  978. multiplyVector3: function ( v ) {
  979. var te = this.elements;
  980. var vx = v.x, vy = v.y, vz = v.z;
  981. v.x = te[0] * vx + te[3] * vy + te[6] * vz;
  982. v.y = te[1] * vx + te[4] * vy + te[7] * vz;
  983. v.z = te[2] * vx + te[5] * vy + te[8] * vz;
  984. return v;
  985. },
  986. multiplyVector3Array: function ( a ) {
  987. var tmp = THREE.Matrix3.__v1;
  988. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  989. tmp.x = a[ i ];
  990. tmp.y = a[ i + 1 ];
  991. tmp.z = a[ i + 2 ];
  992. this.multiplyVector3( tmp );
  993. a[ i ] = tmp.x;
  994. a[ i + 1 ] = tmp.y;
  995. a[ i + 2 ] = tmp.z;
  996. }
  997. return a;
  998. },
  999. getInverse: function ( matrix ) {
  1000. // input: THREE.Matrix4
  1001. // ( based on http://code.google.com/p/webgl-mjs/ )
  1002. var me = matrix.elements;
  1003. var a11 = me[10] * me[5] - me[6] * me[9];
  1004. var a21 = - me[10] * me[1] + me[2] * me[9];
  1005. var a31 = me[6] * me[1] - me[2] * me[5];
  1006. var a12 = - me[10] * me[4] + me[6] * me[8];
  1007. var a22 = me[10] * me[0] - me[2] * me[8];
  1008. var a32 = - me[6] * me[0] + me[2] * me[4];
  1009. var a13 = me[9] * me[4] - me[5] * me[8];
  1010. var a23 = - me[9] * me[0] + me[1] * me[8];
  1011. var a33 = me[5] * me[0] - me[1] * me[4];
  1012. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  1013. // no inverse
  1014. if ( det === 0 ) {
  1015. console.warn( "Matrix3.getInverse(): determinant == 0" );
  1016. }
  1017. var idet = 1.0 / det;
  1018. var m = this.elements;
  1019. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  1020. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  1021. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  1022. return this;
  1023. },
  1024. transpose: function () {
  1025. var tmp, m = this.elements;
  1026. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1027. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1028. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1029. return this;
  1030. },
  1031. transposeIntoArray: function ( r ) {
  1032. var m = this.elements;
  1033. r[ 0 ] = m[ 0 ];
  1034. r[ 1 ] = m[ 3 ];
  1035. r[ 2 ] = m[ 6 ];
  1036. r[ 3 ] = m[ 1 ];
  1037. r[ 4 ] = m[ 4 ];
  1038. r[ 5 ] = m[ 7 ];
  1039. r[ 6 ] = m[ 2 ];
  1040. r[ 7 ] = m[ 5 ];
  1041. r[ 8 ] = m[ 8 ];
  1042. return this;
  1043. }
  1044. };
  1045. THREE.Matrix3.__v1 = new THREE.Vector3();/**
  1046. * @author mrdoob / http://mrdoob.com/
  1047. * @author supereggbert / http://www.paulbrunt.co.uk/
  1048. * @author philogb / http://blog.thejit.org/
  1049. * @author jordi_ros / http://plattsoft.com
  1050. * @author D1plo1d / http://github.com/D1plo1d
  1051. * @author alteredq / http://alteredqualia.com/
  1052. * @author mikael emtinger / http://gomo.se/
  1053. * @author timknip / http://www.floorplanner.com/
  1054. */
  1055. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1056. this.elements = new Float32Array( 16 );
  1057. this.set(
  1058. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1059. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1060. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1061. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1062. );
  1063. };
  1064. THREE.Matrix4.prototype = {
  1065. constructor: THREE.Matrix4,
  1066. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1067. var te = this.elements;
  1068. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1069. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1070. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1071. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1072. return this;
  1073. },
  1074. identity: function () {
  1075. this.set(
  1076. 1, 0, 0, 0,
  1077. 0, 1, 0, 0,
  1078. 0, 0, 1, 0,
  1079. 0, 0, 0, 1
  1080. );
  1081. return this;
  1082. },
  1083. copy: function ( m ) {
  1084. var me = m.elements;
  1085. this.set(
  1086. me[0], me[4], me[8], me[12],
  1087. me[1], me[5], me[9], me[13],
  1088. me[2], me[6], me[10], me[14],
  1089. me[3], me[7], me[11], me[15]
  1090. );
  1091. return this;
  1092. },
  1093. lookAt: function ( eye, target, up ) {
  1094. var te = this.elements;
  1095. var x = THREE.Matrix4.__v1;
  1096. var y = THREE.Matrix4.__v2;
  1097. var z = THREE.Matrix4.__v3;
  1098. z.sub( eye, target ).normalize();
  1099. if ( z.length() === 0 ) {
  1100. z.z = 1;
  1101. }
  1102. x.cross( up, z ).normalize();
  1103. if ( x.length() === 0 ) {
  1104. z.x += 0.0001;
  1105. x.cross( up, z ).normalize();
  1106. }
  1107. y.cross( z, x );
  1108. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1109. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1110. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1111. return this;
  1112. },
  1113. multiply: function ( a, b ) {
  1114. var ae = a.elements;
  1115. var be = b.elements;
  1116. var te = this.elements;
  1117. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1118. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1119. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1120. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1121. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1122. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1123. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1124. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1125. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1126. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1127. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1128. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1129. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1130. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1131. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1132. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1133. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1134. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1135. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1136. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1137. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1138. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1139. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1140. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1141. return this;
  1142. },
  1143. multiplySelf: function ( m ) {
  1144. return this.multiply( this, m );
  1145. },
  1146. multiplyToArray: function ( a, b, r ) {
  1147. var te = this.elements;
  1148. this.multiply( a, b );
  1149. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1150. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1151. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1152. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1153. return this;
  1154. },
  1155. multiplyScalar: function ( s ) {
  1156. var te = this.elements;
  1157. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1158. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1159. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1160. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1161. return this;
  1162. },
  1163. multiplyVector3: function ( v ) {
  1164. var te = this.elements;
  1165. var vx = v.x, vy = v.y, vz = v.z;
  1166. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1167. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1168. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1169. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1170. return v;
  1171. },
  1172. multiplyVector4: function ( v ) {
  1173. var te = this.elements;
  1174. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1175. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1176. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1177. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1178. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1179. return v;
  1180. },
  1181. multiplyVector3Array: function ( a ) {
  1182. var tmp = THREE.Matrix4.__v1;
  1183. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1184. tmp.x = a[ i ];
  1185. tmp.y = a[ i + 1 ];
  1186. tmp.z = a[ i + 2 ];
  1187. this.multiplyVector3( tmp );
  1188. a[ i ] = tmp.x;
  1189. a[ i + 1 ] = tmp.y;
  1190. a[ i + 2 ] = tmp.z;
  1191. }
  1192. return a;
  1193. },
  1194. rotateAxis: function ( v ) {
  1195. var te = this.elements;
  1196. var vx = v.x, vy = v.y, vz = v.z;
  1197. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1198. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1199. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1200. v.normalize();
  1201. return v;
  1202. },
  1203. crossVector: function ( a ) {
  1204. var te = this.elements;
  1205. var v = new THREE.Vector4();
  1206. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1207. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1208. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1209. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1210. return v;
  1211. },
  1212. determinant: function () {
  1213. var te = this.elements;
  1214. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1215. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1216. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1217. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1218. //TODO: make this more efficient
  1219. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1220. return (
  1221. n14 * n23 * n32 * n41-
  1222. n13 * n24 * n32 * n41-
  1223. n14 * n22 * n33 * n41+
  1224. n12 * n24 * n33 * n41+
  1225. n13 * n22 * n34 * n41-
  1226. n12 * n23 * n34 * n41-
  1227. n14 * n23 * n31 * n42+
  1228. n13 * n24 * n31 * n42+
  1229. n14 * n21 * n33 * n42-
  1230. n11 * n24 * n33 * n42-
  1231. n13 * n21 * n34 * n42+
  1232. n11 * n23 * n34 * n42+
  1233. n14 * n22 * n31 * n43-
  1234. n12 * n24 * n31 * n43-
  1235. n14 * n21 * n32 * n43+
  1236. n11 * n24 * n32 * n43+
  1237. n12 * n21 * n34 * n43-
  1238. n11 * n22 * n34 * n43-
  1239. n13 * n22 * n31 * n44+
  1240. n12 * n23 * n31 * n44+
  1241. n13 * n21 * n32 * n44-
  1242. n11 * n23 * n32 * n44-
  1243. n12 * n21 * n33 * n44+
  1244. n11 * n22 * n33 * n44
  1245. );
  1246. },
  1247. transpose: function () {
  1248. var te = this.elements;
  1249. var tmp;
  1250. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1251. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1252. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1253. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1254. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1255. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1256. return this;
  1257. },
  1258. flattenToArray: function ( flat ) {
  1259. var te = this.elements;
  1260. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1261. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1262. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1263. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1264. return flat;
  1265. },
  1266. flattenToArrayOffset: function( flat, offset ) {
  1267. var te = this.elements;
  1268. flat[ offset ] = te[0];
  1269. flat[ offset + 1 ] = te[1];
  1270. flat[ offset + 2 ] = te[2];
  1271. flat[ offset + 3 ] = te[3];
  1272. flat[ offset + 4 ] = te[4];
  1273. flat[ offset + 5 ] = te[5];
  1274. flat[ offset + 6 ] = te[6];
  1275. flat[ offset + 7 ] = te[7];
  1276. flat[ offset + 8 ] = te[8];
  1277. flat[ offset + 9 ] = te[9];
  1278. flat[ offset + 10 ] = te[10];
  1279. flat[ offset + 11 ] = te[11];
  1280. flat[ offset + 12 ] = te[12];
  1281. flat[ offset + 13 ] = te[13];
  1282. flat[ offset + 14 ] = te[14];
  1283. flat[ offset + 15 ] = te[15];
  1284. return flat;
  1285. },
  1286. getPosition: function () {
  1287. var te = this.elements;
  1288. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1289. },
  1290. setPosition: function ( v ) {
  1291. var te = this.elements;
  1292. te[12] = v.x;
  1293. te[13] = v.y;
  1294. te[14] = v.z;
  1295. return this;
  1296. },
  1297. getColumnX: function () {
  1298. var te = this.elements;
  1299. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1300. },
  1301. getColumnY: function () {
  1302. var te = this.elements;
  1303. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1304. },
  1305. getColumnZ: function() {
  1306. var te = this.elements;
  1307. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1308. },
  1309. getInverse: function ( m ) {
  1310. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1311. var te = this.elements;
  1312. var me = m.elements;
  1313. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1314. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1315. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1316. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1317. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1318. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1319. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1320. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1321. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1322. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1323. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1324. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1325. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1326. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1327. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1328. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1329. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1330. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1331. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1332. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1333. this.multiplyScalar( 1 / m.determinant() );
  1334. return this;
  1335. },
  1336. setRotationFromEuler: function ( v, order ) {
  1337. var te = this.elements;
  1338. var x = v.x, y = v.y, z = v.z;
  1339. var a = Math.cos( x ), b = Math.sin( x );
  1340. var c = Math.cos( y ), d = Math.sin( y );
  1341. var e = Math.cos( z ), f = Math.sin( z );
  1342. if ( order === undefined || order === 'XYZ' ) {
  1343. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1344. te[0] = c * e;
  1345. te[4] = - c * f;
  1346. te[8] = d;
  1347. te[1] = af + be * d;
  1348. te[5] = ae - bf * d;
  1349. te[9] = - b * c;
  1350. te[2] = bf - ae * d;
  1351. te[6] = be + af * d;
  1352. te[10] = a * c;
  1353. } else if ( order === 'YXZ' ) {
  1354. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1355. te[0] = ce + df * b;
  1356. te[4] = de * b - cf;
  1357. te[8] = a * d;
  1358. te[1] = a * f;
  1359. te[5] = a * e;
  1360. te[9] = - b;
  1361. te[2] = cf * b - de;
  1362. te[6] = df + ce * b;
  1363. te[10] = a * c;
  1364. } else if ( order === 'ZXY' ) {
  1365. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1366. te[0] = ce - df * b;
  1367. te[4] = - a * f;
  1368. te[8] = de + cf * b;
  1369. te[1] = cf + de * b;
  1370. te[5] = a * e;
  1371. te[9] = df - ce * b;
  1372. te[2] = - a * d;
  1373. te[6] = b;
  1374. te[10] = a * c;
  1375. } else if ( order === 'ZYX' ) {
  1376. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1377. te[0] = c * e;
  1378. te[4] = be * d - af;
  1379. te[8] = ae * d + bf;
  1380. te[1] = c * f;
  1381. te[5] = bf * d + ae;
  1382. te[9] = af * d - be;
  1383. te[2] = - d;
  1384. te[6] = b * c;
  1385. te[10] = a * c;
  1386. } else if ( order === 'YZX' ) {
  1387. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1388. te[0] = c * e;
  1389. te[4] = bd - ac * f;
  1390. te[8] = bc * f + ad;
  1391. te[1] = f;
  1392. te[5] = a * e;
  1393. te[9] = - b * e;
  1394. te[2] = - d * e;
  1395. te[6] = ad * f + bc;
  1396. te[10] = ac - bd * f;
  1397. } else if ( order === 'XZY' ) {
  1398. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1399. te[0] = c * e;
  1400. te[4] = - f;
  1401. te[8] = d * e;
  1402. te[1] = ac * f + bd;
  1403. te[5] = a * e;
  1404. te[9] = ad * f - bc;
  1405. te[2] = bc * f - ad;
  1406. te[6] = b * e;
  1407. te[10] = bd * f + ac;
  1408. }
  1409. return this;
  1410. },
  1411. setRotationFromQuaternion: function ( q ) {
  1412. var te = this.elements;
  1413. var x = q.x, y = q.y, z = q.z, w = q.w;
  1414. var x2 = x + x, y2 = y + y, z2 = z + z;
  1415. var xx = x * x2, xy = x * y2, xz = x * z2;
  1416. var yy = y * y2, yz = y * z2, zz = z * z2;
  1417. var wx = w * x2, wy = w * y2, wz = w * z2;
  1418. te[0] = 1 - ( yy + zz );
  1419. te[4] = xy - wz;
  1420. te[8] = xz + wy;
  1421. te[1] = xy + wz;
  1422. te[5] = 1 - ( xx + zz );
  1423. te[9] = yz - wx;
  1424. te[2] = xz - wy;
  1425. te[6] = yz + wx;
  1426. te[10] = 1 - ( xx + yy );
  1427. return this;
  1428. },
  1429. compose: function ( translation, rotation, scale ) {
  1430. var te = this.elements;
  1431. var mRotation = THREE.Matrix4.__m1;
  1432. var mScale = THREE.Matrix4.__m2;
  1433. mRotation.identity();
  1434. mRotation.setRotationFromQuaternion( rotation );
  1435. mScale.makeScale( scale.x, scale.y, scale.z );
  1436. this.multiply( mRotation, mScale );
  1437. te[12] = translation.x;
  1438. te[13] = translation.y;
  1439. te[14] = translation.z;
  1440. return this;
  1441. },
  1442. decompose: function ( translation, rotation, scale ) {
  1443. var te = this.elements;
  1444. // grab the axis vectors
  1445. var x = THREE.Matrix4.__v1;
  1446. var y = THREE.Matrix4.__v2;
  1447. var z = THREE.Matrix4.__v3;
  1448. x.set( te[0], te[1], te[2] );
  1449. y.set( te[4], te[5], te[6] );
  1450. z.set( te[8], te[9], te[10] );
  1451. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1452. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1453. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1454. scale.x = x.length();
  1455. scale.y = y.length();
  1456. scale.z = z.length();
  1457. translation.x = te[12];
  1458. translation.y = te[13];
  1459. translation.z = te[14];
  1460. // scale the rotation part
  1461. var matrix = THREE.Matrix4.__m1;
  1462. matrix.copy( this );
  1463. matrix.elements[0] /= scale.x;
  1464. matrix.elements[1] /= scale.x;
  1465. matrix.elements[2] /= scale.x;
  1466. matrix.elements[4] /= scale.y;
  1467. matrix.elements[5] /= scale.y;
  1468. matrix.elements[6] /= scale.y;
  1469. matrix.elements[8] /= scale.z;
  1470. matrix.elements[9] /= scale.z;
  1471. matrix.elements[10] /= scale.z;
  1472. rotation.setFromRotationMatrix( matrix );
  1473. return [ translation, rotation, scale ];
  1474. },
  1475. extractPosition: function ( m ) {
  1476. var te = this.elements;
  1477. var me = m.elements;
  1478. te[12] = me[12];
  1479. te[13] = me[13];
  1480. te[14] = me[14];
  1481. return this;
  1482. },
  1483. extractRotation: function ( m ) {
  1484. var te = this.elements;
  1485. var me = m.elements;
  1486. var vector = THREE.Matrix4.__v1;
  1487. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1488. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1489. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1490. te[0] = me[0] * scaleX;
  1491. te[1] = me[1] * scaleX;
  1492. te[2] = me[2] * scaleX;
  1493. te[4] = me[4] * scaleY;
  1494. te[5] = me[5] * scaleY;
  1495. te[6] = me[6] * scaleY;
  1496. te[8] = me[8] * scaleZ;
  1497. te[9] = me[9] * scaleZ;
  1498. te[10] = me[10] * scaleZ;
  1499. return this;
  1500. },
  1501. //
  1502. translate: function ( v ) {
  1503. var te = this.elements;
  1504. var x = v.x, y = v.y, z = v.z;
  1505. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1506. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1507. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1508. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1509. return this;
  1510. },
  1511. rotateX: function ( angle ) {
  1512. var te = this.elements;
  1513. var m12 = te[4];
  1514. var m22 = te[5];
  1515. var m32 = te[6];
  1516. var m42 = te[7];
  1517. var m13 = te[8];
  1518. var m23 = te[9];
  1519. var m33 = te[10];
  1520. var m43 = te[11];
  1521. var c = Math.cos( angle );
  1522. var s = Math.sin( angle );
  1523. te[4] = c * m12 + s * m13;
  1524. te[5] = c * m22 + s * m23;
  1525. te[6] = c * m32 + s * m33;
  1526. te[7] = c * m42 + s * m43;
  1527. te[8] = c * m13 - s * m12;
  1528. te[9] = c * m23 - s * m22;
  1529. te[10] = c * m33 - s * m32;
  1530. te[11] = c * m43 - s * m42;
  1531. return this;
  1532. },
  1533. rotateY: function ( angle ) {
  1534. var te = this.elements;
  1535. var m11 = te[0];
  1536. var m21 = te[1];
  1537. var m31 = te[2];
  1538. var m41 = te[3];
  1539. var m13 = te[8];
  1540. var m23 = te[9];
  1541. var m33 = te[10];
  1542. var m43 = te[11];
  1543. var c = Math.cos( angle );
  1544. var s = Math.sin( angle );
  1545. te[0] = c * m11 - s * m13;
  1546. te[1] = c * m21 - s * m23;
  1547. te[2] = c * m31 - s * m33;
  1548. te[3] = c * m41 - s * m43;
  1549. te[8] = c * m13 + s * m11;
  1550. te[9] = c * m23 + s * m21;
  1551. te[10] = c * m33 + s * m31;
  1552. te[11] = c * m43 + s * m41;
  1553. return this;
  1554. },
  1555. rotateZ: function ( angle ) {
  1556. var te = this.elements;
  1557. var m11 = te[0];
  1558. var m21 = te[1];
  1559. var m31 = te[2];
  1560. var m41 = te[3];
  1561. var m12 = te[4];
  1562. var m22 = te[5];
  1563. var m32 = te[6];
  1564. var m42 = te[7];
  1565. var c = Math.cos( angle );
  1566. var s = Math.sin( angle );
  1567. te[0] = c * m11 + s * m12;
  1568. te[1] = c * m21 + s * m22;
  1569. te[2] = c * m31 + s * m32;
  1570. te[3] = c * m41 + s * m42;
  1571. te[4] = c * m12 - s * m11;
  1572. te[5] = c * m22 - s * m21;
  1573. te[6] = c * m32 - s * m31;
  1574. te[7] = c * m42 - s * m41;
  1575. return this;
  1576. },
  1577. rotateByAxis: function ( axis, angle ) {
  1578. var te = this.elements;
  1579. // optimize by checking axis
  1580. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1581. return this.rotateX( angle );
  1582. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1583. return this.rotateY( angle );
  1584. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1585. return this.rotateZ( angle );
  1586. }
  1587. var x = axis.x, y = axis.y, z = axis.z;
  1588. var n = Math.sqrt(x * x + y * y + z * z);
  1589. x /= n;
  1590. y /= n;
  1591. z /= n;
  1592. var xx = x * x, yy = y * y, zz = z * z;
  1593. var c = Math.cos( angle );
  1594. var s = Math.sin( angle );
  1595. var oneMinusCosine = 1 - c;
  1596. var xy = x * y * oneMinusCosine;
  1597. var xz = x * z * oneMinusCosine;
  1598. var yz = y * z * oneMinusCosine;
  1599. var xs = x * s;
  1600. var ys = y * s;
  1601. var zs = z * s;
  1602. var r11 = xx + (1 - xx) * c;
  1603. var r21 = xy + zs;
  1604. var r31 = xz - ys;
  1605. var r12 = xy - zs;
  1606. var r22 = yy + (1 - yy) * c;
  1607. var r32 = yz + xs;
  1608. var r13 = xz + ys;
  1609. var r23 = yz - xs;
  1610. var r33 = zz + (1 - zz) * c;
  1611. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1612. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1613. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1614. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1615. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1616. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1617. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1618. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1619. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1620. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1621. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1622. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1623. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1624. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1625. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1626. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1627. return this;
  1628. },
  1629. scale: function ( v ) {
  1630. var te = this.elements;
  1631. var x = v.x, y = v.y, z = v.z;
  1632. te[0] *= x; te[4] *= y; te[8] *= z;
  1633. te[1] *= x; te[5] *= y; te[9] *= z;
  1634. te[2] *= x; te[6] *= y; te[10] *= z;
  1635. te[3] *= x; te[7] *= y; te[11] *= z;
  1636. return this;
  1637. },
  1638. getMaxScaleOnAxis: function () {
  1639. var te = this.elements;
  1640. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1641. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1642. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1643. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1644. },
  1645. //
  1646. makeTranslation: function ( x, y, z ) {
  1647. this.set(
  1648. 1, 0, 0, x,
  1649. 0, 1, 0, y,
  1650. 0, 0, 1, z,
  1651. 0, 0, 0, 1
  1652. );
  1653. return this;
  1654. },
  1655. makeRotationX: function ( theta ) {
  1656. var c = Math.cos( theta ), s = Math.sin( theta );
  1657. this.set(
  1658. 1, 0, 0, 0,
  1659. 0, c, -s, 0,
  1660. 0, s, c, 0,
  1661. 0, 0, 0, 1
  1662. );
  1663. return this;
  1664. },
  1665. makeRotationY: function ( theta ) {
  1666. var c = Math.cos( theta ), s = Math.sin( theta );
  1667. this.set(
  1668. c, 0, s, 0,
  1669. 0, 1, 0, 0,
  1670. -s, 0, c, 0,
  1671. 0, 0, 0, 1
  1672. );
  1673. return this;
  1674. },
  1675. makeRotationZ: function ( theta ) {
  1676. var c = Math.cos( theta ), s = Math.sin( theta );
  1677. this.set(
  1678. c, -s, 0, 0,
  1679. s, c, 0, 0,
  1680. 0, 0, 1, 0,
  1681. 0, 0, 0, 1
  1682. );
  1683. return this;
  1684. },
  1685. makeRotationAxis: function ( axis, angle ) {
  1686. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1687. var c = Math.cos( angle );
  1688. var s = Math.sin( angle );
  1689. var t = 1 - c;
  1690. var x = axis.x, y = axis.y, z = axis.z;
  1691. var tx = t * x, ty = t * y;
  1692. this.set(
  1693. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1694. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1695. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1696. 0, 0, 0, 1
  1697. );
  1698. return this;
  1699. },
  1700. makeScale: function ( x, y, z ) {
  1701. this.set(
  1702. x, 0, 0, 0,
  1703. 0, y, 0, 0,
  1704. 0, 0, z, 0,
  1705. 0, 0, 0, 1
  1706. );
  1707. return this;
  1708. },
  1709. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1710. var te = this.elements;
  1711. var x = 2 * near / ( right - left );
  1712. var y = 2 * near / ( top - bottom );
  1713. var a = ( right + left ) / ( right - left );
  1714. var b = ( top + bottom ) / ( top - bottom );
  1715. var c = - ( far + near ) / ( far - near );
  1716. var d = - 2 * far * near / ( far - near );
  1717. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1718. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1719. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1720. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1721. return this;
  1722. },
  1723. makePerspective: function ( fov, aspect, near, far ) {
  1724. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1725. var ymin = - ymax;
  1726. var xmin = ymin * aspect;
  1727. var xmax = ymax * aspect;
  1728. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1729. },
  1730. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1731. var te = this.elements;
  1732. var w = right - left;
  1733. var h = top - bottom;
  1734. var p = far - near;
  1735. var x = ( right + left ) / w;
  1736. var y = ( top + bottom ) / h;
  1737. var z = ( far + near ) / p;
  1738. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1739. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1740. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1741. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1742. return this;
  1743. },
  1744. clone: function () {
  1745. var te = this.elements;
  1746. return new THREE.Matrix4(
  1747. te[0], te[4], te[8], te[12],
  1748. te[1], te[5], te[9], te[13],
  1749. te[2], te[6], te[10], te[14],
  1750. te[3], te[7], te[11], te[15]
  1751. );
  1752. }
  1753. };
  1754. THREE.Matrix4.__v1 = new THREE.Vector3();
  1755. THREE.Matrix4.__v2 = new THREE.Vector3();
  1756. THREE.Matrix4.__v3 = new THREE.Vector3();
  1757. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1758. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1759. /**
  1760. * https://github.com/mrdoob/eventtarget.js/
  1761. */
  1762. THREE.EventTarget = function () {
  1763. var listeners = {};
  1764. this.addEventListener = function ( type, listener ) {
  1765. if ( listeners[ type ] === undefined ) {
  1766. listeners[ type ] = [];
  1767. }
  1768. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1769. listeners[ type ].push( listener );
  1770. }
  1771. };
  1772. this.dispatchEvent = function ( event ) {
  1773. var listenerArray = listeners[ event.type ];
  1774. if ( listenerArray !== undefined ) {
  1775. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  1776. listenerArray[ i ]( event );
  1777. }
  1778. }
  1779. };
  1780. this.removeEventListener = function ( type, listener ) {
  1781. var index = listeners[ type ].indexOf( listener );
  1782. if ( index !== - 1 ) {
  1783. listeners[ type ].splice( index, 1 );
  1784. }
  1785. };
  1786. };
  1787. /**
  1788. * @author mrdoob / http://mrdoob.com/
  1789. * @author alteredq / http://alteredqualia.com/
  1790. */
  1791. THREE.Frustum = function ( ) {
  1792. this.planes = [
  1793. new THREE.Vector4(),
  1794. new THREE.Vector4(),
  1795. new THREE.Vector4(),
  1796. new THREE.Vector4(),
  1797. new THREE.Vector4(),
  1798. new THREE.Vector4()
  1799. ];
  1800. };
  1801. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1802. var plane;
  1803. var planes = this.planes;
  1804. var me = m.elements;
  1805. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1806. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1807. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1808. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1809. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1810. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1811. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1812. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1813. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1814. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1815. for ( var i = 0; i < 6; i ++ ) {
  1816. plane = planes[ i ];
  1817. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1818. }
  1819. };
  1820. THREE.Frustum.prototype.contains = function ( object ) {
  1821. var distance = 0.0;
  1822. var planes = this.planes;
  1823. var matrix = object.matrixWorld;
  1824. var me = matrix.elements;
  1825. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1826. for ( var i = 0; i < 6; i ++ ) {
  1827. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1828. if ( distance <= radius ) return false;
  1829. }
  1830. return true;
  1831. };
  1832. THREE.Frustum.__v1 = new THREE.Vector3();
  1833. /**
  1834. * @author mrdoob / http://mrdoob.com/
  1835. */
  1836. ( function ( THREE ) {
  1837. THREE.Ray = function ( origin, direction, near, far ) {
  1838. this.origin = origin || new THREE.Vector3();
  1839. this.direction = direction || new THREE.Vector3();
  1840. this.near = near || 0;
  1841. this.far = far || Infinity;
  1842. };
  1843. var originCopy = new THREE.Vector3();
  1844. var localOriginCopy = new THREE.Vector3();
  1845. var localDirectionCopy = new THREE.Vector3();
  1846. var vector = new THREE.Vector3();
  1847. var normal = new THREE.Vector3();
  1848. var intersectPoint = new THREE.Vector3();
  1849. var inverseMatrix = new THREE.Matrix4();
  1850. var descSort = function ( a, b ) {
  1851. return a.distance - b.distance;
  1852. };
  1853. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1854. var distanceFromIntersection = function ( origin, direction, position ) {
  1855. v0.sub( position, origin );
  1856. var dot = v0.dot( direction );
  1857. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1858. var distance = position.distanceTo( intersect );
  1859. return distance;
  1860. };
  1861. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1862. var pointInFace3 = function ( p, a, b, c ) {
  1863. v0.sub( c, a );
  1864. v1.sub( b, a );
  1865. v2.sub( p, a );
  1866. var dot00 = v0.dot( v0 );
  1867. var dot01 = v0.dot( v1 );
  1868. var dot02 = v0.dot( v2 );
  1869. var dot11 = v1.dot( v1 );
  1870. var dot12 = v1.dot( v2 );
  1871. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1872. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1873. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1874. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1875. };
  1876. var intersectObject = function ( object, ray, intersects ) {
  1877. if ( object instanceof THREE.Particle ) {
  1878. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1879. if ( distance > object.scale.x ) {
  1880. return intersects;
  1881. }
  1882. intersects.push( {
  1883. distance: distance,
  1884. point: object.position,
  1885. face: null,
  1886. object: object
  1887. } );
  1888. } else if ( object instanceof THREE.Mesh ) {
  1889. // Checking boundingSphere
  1890. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1891. // Checking distance to ray
  1892. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1893. if ( distance > scaledRadius) {
  1894. return intersects;
  1895. }
  1896. // Checking faces
  1897. var geometry = object.geometry;
  1898. var vertices = geometry.vertices;
  1899. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1900. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  1901. var side = object.material.side;
  1902. var a, b, c, d;
  1903. var precision = ray.precision;
  1904. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1905. originCopy.copy( ray.origin );
  1906. inverseMatrix.getInverse( object.matrixWorld );
  1907. localOriginCopy.copy( originCopy );
  1908. inverseMatrix.multiplyVector3( localOriginCopy );
  1909. localDirectionCopy.copy( ray.direction );
  1910. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1911. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1912. var face = geometry.faces[ f ];
  1913. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  1914. if ( material === undefined ) continue;
  1915. side = material.side;
  1916. vector.sub( face.centroid, localOriginCopy );
  1917. var normal = face.normal;
  1918. var dot = localDirectionCopy.dot( normal );
  1919. // bail if ray and plane are parallel
  1920. if ( Math.abs( dot ) < precision ) continue;
  1921. // calc distance to plane
  1922. var scalar = normal.dot( vector ) / dot;
  1923. // if negative distance, then plane is behind ray
  1924. if ( scalar < 0 ) continue;
  1925. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1926. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1927. if ( face instanceof THREE.Face3 ) {
  1928. a = vertices[ face.a ];
  1929. b = vertices[ face.b ];
  1930. c = vertices[ face.c ];
  1931. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1932. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1933. distance = originCopy.distanceTo( point );
  1934. if ( distance < ray.near || distance > ray.far ) continue;
  1935. intersects.push( {
  1936. distance: distance,
  1937. point: point,
  1938. face: face,
  1939. faceIndex: f,
  1940. object: object
  1941. } );
  1942. }
  1943. } else if ( face instanceof THREE.Face4 ) {
  1944. a = vertices[ face.a ];
  1945. b = vertices[ face.b ];
  1946. c = vertices[ face.c ];
  1947. d = vertices[ face.d ];
  1948. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1949. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1950. distance = originCopy.distanceTo( point );
  1951. if ( distance < ray.near || distance > ray.far ) continue;
  1952. intersects.push( {
  1953. distance: distance,
  1954. point: point,
  1955. face: face,
  1956. faceIndex: f,
  1957. object: object
  1958. } );
  1959. }
  1960. }
  1961. }
  1962. }
  1963. }
  1964. };
  1965. var intersectDescendants = function ( object, ray, intersects ) {
  1966. var descendants = object.getDescendants();
  1967. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1968. intersectObject( descendants[ i ], ray, intersects );
  1969. }
  1970. };
  1971. //
  1972. THREE.Ray.prototype.precision = 0.0001;
  1973. THREE.Ray.prototype.set = function ( origin, direction ) {
  1974. this.origin = origin;
  1975. this.direction = direction;
  1976. };
  1977. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1978. var intersects = [];
  1979. if ( recursive === true ) {
  1980. intersectDescendants( object, this, intersects );
  1981. }
  1982. intersectObject( object, this, intersects );
  1983. intersects.sort( descSort );
  1984. return intersects;
  1985. };
  1986. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1987. var intersects = [];
  1988. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1989. intersectObject( objects[ i ], this, intersects );
  1990. if ( recursive === true ) {
  1991. intersectDescendants( objects[ i ], this, intersects );
  1992. }
  1993. }
  1994. intersects.sort( descSort );
  1995. return intersects;
  1996. };
  1997. }( THREE ) );
  1998. /**
  1999. * @author mrdoob / http://mrdoob.com/
  2000. */
  2001. THREE.Rectangle = function () {
  2002. var _left = 0;
  2003. var _top = 0;
  2004. var _right = 0;
  2005. var _bottom = 0;
  2006. var _width = 0;
  2007. var _height = 0;
  2008. var _isEmpty = true;
  2009. function resize() {
  2010. _width = _right - _left;
  2011. _height = _bottom - _top;
  2012. }
  2013. this.getX = function () {
  2014. return _left;
  2015. };
  2016. this.getY = function () {
  2017. return _top;
  2018. };
  2019. this.getWidth = function () {
  2020. return _width;
  2021. };
  2022. this.getHeight = function () {
  2023. return _height;
  2024. };
  2025. this.getLeft = function() {
  2026. return _left;
  2027. };
  2028. this.getTop = function() {
  2029. return _top;
  2030. };
  2031. this.getRight = function() {
  2032. return _right;
  2033. };
  2034. this.getBottom = function() {
  2035. return _bottom;
  2036. };
  2037. this.set = function ( left, top, right, bottom ) {
  2038. _isEmpty = false;
  2039. _left = left; _top = top;
  2040. _right = right; _bottom = bottom;
  2041. resize();
  2042. };
  2043. this.addPoint = function ( x, y ) {
  2044. if ( _isEmpty === true ) {
  2045. _isEmpty = false;
  2046. _left = x; _top = y;
  2047. _right = x; _bottom = y;
  2048. resize();
  2049. } else {
  2050. _left = _left < x ? _left : x; // Math.min( _left, x );
  2051. _top = _top < y ? _top : y; // Math.min( _top, y );
  2052. _right = _right > x ? _right : x; // Math.max( _right, x );
  2053. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  2054. resize();
  2055. }
  2056. };
  2057. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  2058. if ( _isEmpty === true ) {
  2059. _isEmpty = false;
  2060. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  2061. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  2062. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  2063. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  2064. resize();
  2065. } else {
  2066. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  2067. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  2068. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  2069. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  2070. resize();
  2071. };
  2072. };
  2073. this.addRectangle = function ( r ) {
  2074. if ( _isEmpty === true ) {
  2075. _isEmpty = false;
  2076. _left = r.getLeft(); _top = r.getTop();
  2077. _right = r.getRight(); _bottom = r.getBottom();
  2078. resize();
  2079. } else {
  2080. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  2081. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  2082. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  2083. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  2084. resize();
  2085. }
  2086. };
  2087. this.inflate = function ( v ) {
  2088. _left -= v; _top -= v;
  2089. _right += v; _bottom += v;
  2090. resize();
  2091. };
  2092. this.minSelf = function ( r ) {
  2093. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  2094. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  2095. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  2096. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  2097. resize();
  2098. };
  2099. this.intersects = function ( r ) {
  2100. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  2101. if ( _right < r.getLeft() ) return false;
  2102. if ( _left > r.getRight() ) return false;
  2103. if ( _bottom < r.getTop() ) return false;
  2104. if ( _top > r.getBottom() ) return false;
  2105. return true;
  2106. };
  2107. this.empty = function () {
  2108. _isEmpty = true;
  2109. _left = 0; _top = 0;
  2110. _right = 0; _bottom = 0;
  2111. resize();
  2112. };
  2113. this.isEmpty = function () {
  2114. return _isEmpty;
  2115. };
  2116. };
  2117. /**
  2118. * @author alteredq / http://alteredqualia.com/
  2119. */
  2120. THREE.Math = {
  2121. // Clamp value to range <a, b>
  2122. clamp: function ( x, a, b ) {
  2123. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2124. },
  2125. // Clamp value to range <a, inf)
  2126. clampBottom: function ( x, a ) {
  2127. return x < a ? a : x;
  2128. },
  2129. // Linear mapping from range <a1, a2> to range <b1, b2>
  2130. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2131. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2132. },
  2133. // Random float from <0, 1> with 16 bits of randomness
  2134. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2135. random16: function () {
  2136. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2137. },
  2138. // Random integer from <low, high> interval
  2139. randInt: function ( low, high ) {
  2140. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2141. },
  2142. // Random float from <low, high> interval
  2143. randFloat: function ( low, high ) {
  2144. return low + Math.random() * ( high - low );
  2145. },
  2146. // Random float from <-range/2, range/2> interval
  2147. randFloatSpread: function ( range ) {
  2148. return range * ( 0.5 - Math.random() );
  2149. },
  2150. sign: function ( x ) {
  2151. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2152. }
  2153. };
  2154. /**
  2155. * @author mrdoob / http://mrdoob.com/
  2156. * @author mikael emtinger / http://gomo.se/
  2157. * @author alteredq / http://alteredqualia.com/
  2158. */
  2159. THREE.Object3D = function () {
  2160. THREE.Object3DLibrary.push( this );
  2161. this.id = THREE.Object3DIdCount ++;
  2162. this.name = '';
  2163. this.properties = {};
  2164. this.parent = undefined;
  2165. this.children = [];
  2166. this.up = new THREE.Vector3( 0, 1, 0 );
  2167. this.position = new THREE.Vector3();
  2168. this.rotation = new THREE.Vector3();
  2169. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  2170. this.scale = new THREE.Vector3( 1, 1, 1 );
  2171. this.renderDepth = null;
  2172. this.rotationAutoUpdate = true;
  2173. this.matrix = new THREE.Matrix4();
  2174. this.matrixWorld = new THREE.Matrix4();
  2175. this.matrixRotationWorld = new THREE.Matrix4();
  2176. this.matrixAutoUpdate = true;
  2177. this.matrixWorldNeedsUpdate = true;
  2178. this.quaternion = new THREE.Quaternion();
  2179. this.useQuaternion = false;
  2180. this.boundRadius = 0.0;
  2181. this.boundRadiusScale = 1.0;
  2182. this.visible = true;
  2183. this.castShadow = false;
  2184. this.receiveShadow = false;
  2185. this.frustumCulled = true;
  2186. this._vector = new THREE.Vector3();
  2187. };
  2188. THREE.Object3D.prototype = {
  2189. constructor: THREE.Object3D,
  2190. applyMatrix: function ( matrix ) {
  2191. this.matrix.multiply( matrix, this.matrix );
  2192. this.scale.getScaleFromMatrix( this.matrix );
  2193. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2194. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2195. this.position.getPositionFromMatrix( this.matrix );
  2196. },
  2197. translate: function ( distance, axis ) {
  2198. this.matrix.rotateAxis( axis );
  2199. this.position.addSelf( axis.multiplyScalar( distance ) );
  2200. },
  2201. translateX: function ( distance ) {
  2202. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2203. },
  2204. translateY: function ( distance ) {
  2205. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2206. },
  2207. translateZ: function ( distance ) {
  2208. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2209. },
  2210. localToWorld: function ( vector ) {
  2211. return this.matrixWorld.multiplyVector3( vector );
  2212. },
  2213. worldToLocal: function ( vector ) {
  2214. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2215. },
  2216. lookAt: function ( vector ) {
  2217. // TODO: Add hierarchy support.
  2218. this.matrix.lookAt( vector, this.position, this.up );
  2219. if ( this.rotationAutoUpdate ) {
  2220. if ( this.useQuaternion === false ) {
  2221. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2222. } else {
  2223. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  2224. }
  2225. }
  2226. },
  2227. add: function ( object ) {
  2228. if ( object === this ) {
  2229. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2230. return;
  2231. }
  2232. if ( object instanceof THREE.Object3D ) {
  2233. if ( object.parent !== undefined ) {
  2234. object.parent.remove( object );
  2235. }
  2236. object.parent = this;
  2237. this.children.push( object );
  2238. // add to scene
  2239. var scene = this;
  2240. while ( scene.parent !== undefined ) {
  2241. scene = scene.parent;
  2242. }
  2243. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2244. scene.__addObject( object );
  2245. }
  2246. }
  2247. },
  2248. remove: function ( object ) {
  2249. var index = this.children.indexOf( object );
  2250. if ( index !== - 1 ) {
  2251. object.parent = undefined;
  2252. this.children.splice( index, 1 );
  2253. // remove from scene
  2254. var scene = this;
  2255. while ( scene.parent !== undefined ) {
  2256. scene = scene.parent;
  2257. }
  2258. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2259. scene.__removeObject( object );
  2260. }
  2261. }
  2262. },
  2263. traverse: function ( callback ) {
  2264. callback( this );
  2265. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2266. this.children[ i ].traverse( callback );
  2267. }
  2268. },
  2269. getChildByName: function ( name, recursive ) {
  2270. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2271. var child = this.children[ i ];
  2272. if ( child.name === name ) {
  2273. return child;
  2274. }
  2275. if ( recursive === true ) {
  2276. child = child.getChildByName( name, recursive );
  2277. if ( child !== undefined ) {
  2278. return child;
  2279. }
  2280. }
  2281. }
  2282. return undefined;
  2283. },
  2284. getDescendants: function ( array ) {
  2285. if ( array === undefined ) array = [];
  2286. Array.prototype.push.apply( array, this.children );
  2287. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2288. this.children[ i ].getDescendants( array );
  2289. }
  2290. return array;
  2291. },
  2292. updateMatrix: function () {
  2293. this.matrix.setPosition( this.position );
  2294. if ( this.useQuaternion === false ) {
  2295. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2296. } else {
  2297. this.matrix.setRotationFromQuaternion( this.quaternion );
  2298. }
  2299. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2300. this.matrix.scale( this.scale );
  2301. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2302. }
  2303. this.matrixWorldNeedsUpdate = true;
  2304. },
  2305. updateMatrixWorld: function ( force ) {
  2306. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2307. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2308. if ( this.parent === undefined ) {
  2309. this.matrixWorld.copy( this.matrix );
  2310. } else {
  2311. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2312. }
  2313. this.matrixWorldNeedsUpdate = false;
  2314. force = true;
  2315. }
  2316. // update children
  2317. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2318. this.children[ i ].updateMatrixWorld( force );
  2319. }
  2320. },
  2321. clone: function ( object ) {
  2322. if ( object === undefined ) object = new THREE.Object3D();
  2323. object.name = this.name;
  2324. object.up.copy( this.up );
  2325. object.position.copy( this.position );
  2326. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  2327. object.eulerOrder = this.eulerOrder;
  2328. object.scale.copy( this.scale );
  2329. object.renderDepth = this.renderDepth;
  2330. object.rotationAutoUpdate = this.rotationAutoUpdate;
  2331. object.matrix.copy( this.matrix );
  2332. object.matrixWorld.copy( this.matrixWorld );
  2333. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  2334. object.matrixAutoUpdate = this.matrixAutoUpdate;
  2335. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  2336. object.quaternion.copy( this.quaternion );
  2337. object.useQuaternion = this.useQuaternion;
  2338. object.boundRadius = this.boundRadius;
  2339. object.boundRadiusScale = this.boundRadiusScale;
  2340. object.visible = this.visible;
  2341. object.castShadow = this.castShadow;
  2342. object.receiveShadow = this.receiveShadow;
  2343. object.frustumCulled = this.frustumCulled;
  2344. for ( var i = 0; i < this.children.length; i ++ ) {
  2345. var child = this.children[ i ];
  2346. object.add( child.clone() );
  2347. }
  2348. return object;
  2349. },
  2350. deallocate: function () {
  2351. var index = THREE.Object3DLibrary.indexOf( this );
  2352. if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
  2353. }
  2354. };
  2355. THREE.Object3D.__m1 = new THREE.Matrix4();
  2356. THREE.Object3D.defaultEulerOrder = 'XYZ',
  2357. THREE.Object3DIdCount = 0;
  2358. THREE.Object3DLibrary = [];
  2359. /**
  2360. * @author mrdoob / http://mrdoob.com/
  2361. * @author supereggbert / http://www.paulbrunt.co.uk/
  2362. * @author julianwa / https://github.com/julianwa
  2363. */
  2364. THREE.Projector = function() {
  2365. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2366. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2367. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2368. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2369. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2370. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2371. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2372. _vector3 = new THREE.Vector3(),
  2373. _vector4 = new THREE.Vector4(),
  2374. _viewProjectionMatrix = new THREE.Matrix4(),
  2375. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2376. _normalMatrix = new THREE.Matrix3(),
  2377. _frustum = new THREE.Frustum(),
  2378. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2379. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2380. _face3VertexNormals;
  2381. this.projectVector = function ( vector, camera ) {
  2382. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2383. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2384. _viewProjectionMatrix.multiplyVector3( vector );
  2385. return vector;
  2386. };
  2387. this.unprojectVector = function ( vector, camera ) {
  2388. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2389. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2390. _viewProjectionMatrix.multiplyVector3( vector );
  2391. return vector;
  2392. };
  2393. this.pickingRay = function ( vector, camera ) {
  2394. var end, ray, t;
  2395. // set two vectors with opposing z values
  2396. vector.z = -1.0;
  2397. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2398. this.unprojectVector( vector, camera );
  2399. this.unprojectVector( end, camera );
  2400. // find direction from vector to end
  2401. end.subSelf( vector ).normalize();
  2402. return new THREE.Ray( vector, end );
  2403. };
  2404. var projectGraph = function ( root, sortObjects ) {
  2405. _objectCount = 0;
  2406. _renderData.objects.length = 0;
  2407. _renderData.sprites.length = 0;
  2408. _renderData.lights.length = 0;
  2409. var projectObject = function ( parent ) {
  2410. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  2411. var object = parent.children[ c ];
  2412. if ( object.visible === false ) continue;
  2413. if ( object instanceof THREE.Light ) {
  2414. _renderData.lights.push( object );
  2415. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  2416. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  2417. _object = getNextObjectInPool();
  2418. _object.object = object;
  2419. if ( object.renderDepth !== null ) {
  2420. _object.z = object.renderDepth;
  2421. } else {
  2422. _vector3.copy( object.matrixWorld.getPosition() );
  2423. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2424. _object.z = _vector3.z;
  2425. }
  2426. _renderData.objects.push( _object );
  2427. }
  2428. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2429. _object = getNextObjectInPool();
  2430. _object.object = object;
  2431. // TODO: Find an elegant and performant solution and remove this dupe code.
  2432. if ( object.renderDepth !== null ) {
  2433. _object.z = object.renderDepth;
  2434. } else {
  2435. _vector3.copy( object.matrixWorld.getPosition() );
  2436. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2437. _object.z = _vector3.z;
  2438. }
  2439. _renderData.sprites.push( _object );
  2440. } else {
  2441. _object = getNextObjectInPool();
  2442. _object.object = object;
  2443. if ( object.renderDepth !== null ) {
  2444. _object.z = object.renderDepth;
  2445. } else {
  2446. _vector3.copy( object.matrixWorld.getPosition() );
  2447. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2448. _object.z = _vector3.z;
  2449. }
  2450. _renderData.objects.push( _object );
  2451. }
  2452. projectObject( object );
  2453. }
  2454. };
  2455. projectObject( root );
  2456. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  2457. return _renderData;
  2458. };
  2459. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  2460. var near = camera.near, far = camera.far, visible = false,
  2461. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object, modelMatrix,
  2462. geometry, vertices, vertex, vertexPositionScreen,
  2463. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2464. v1, v2, v3, v4, isFaceMaterial, objectMaterials, material, side;
  2465. _face3Count = 0;
  2466. _face4Count = 0;
  2467. _lineCount = 0;
  2468. _particleCount = 0;
  2469. _renderData.elements.length = 0;
  2470. scene.updateMatrixWorld();
  2471. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2472. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2473. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2474. _frustum.setFromMatrix( _viewProjectionMatrix );
  2475. _renderData = projectGraph( scene, sortObjects );
  2476. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  2477. object = _renderData.objects[ o ].object;
  2478. modelMatrix = object.matrixWorld;
  2479. _vertexCount = 0;
  2480. if ( object instanceof THREE.Mesh ) {
  2481. geometry = object.geometry;
  2482. vertices = geometry.vertices;
  2483. faces = geometry.faces;
  2484. faceVertexUvs = geometry.faceVertexUvs;
  2485. _normalMatrix.getInverse( modelMatrix );
  2486. _normalMatrix.transpose();
  2487. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2488. objectMaterials = isFaceMaterial === true ? object.material : null;
  2489. side = object.material.side;
  2490. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2491. _vertex = getNextVertexInPool();
  2492. _vertex.positionWorld.copy( vertices[ v ] );
  2493. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2494. _vertex.positionScreen.copy( _vertex.positionWorld );
  2495. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2496. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2497. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2498. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2499. }
  2500. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2501. face = faces[ f ];
  2502. material = isFaceMaterial === true ? objectMaterials.materials[ face.materialIndex ] : object.material;
  2503. if ( material === undefined ) continue;
  2504. side = material.side;
  2505. if ( face instanceof THREE.Face3 ) {
  2506. v1 = _vertexPool[ face.a ];
  2507. v2 = _vertexPool[ face.b ];
  2508. v3 = _vertexPool[ face.c ];
  2509. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2510. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2511. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2512. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2513. _face = getNextFace3InPool();
  2514. _face.v1.copy( v1 );
  2515. _face.v2.copy( v2 );
  2516. _face.v3.copy( v3 );
  2517. } else {
  2518. continue;
  2519. }
  2520. } else {
  2521. continue;
  2522. }
  2523. } else if ( face instanceof THREE.Face4 ) {
  2524. v1 = _vertexPool[ face.a ];
  2525. v2 = _vertexPool[ face.b ];
  2526. v3 = _vertexPool[ face.c ];
  2527. v4 = _vertexPool[ face.d ];
  2528. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2529. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2530. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2531. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2532. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2533. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2534. _face = getNextFace4InPool();
  2535. _face.v1.copy( v1 );
  2536. _face.v2.copy( v2 );
  2537. _face.v3.copy( v3 );
  2538. _face.v4.copy( v4 );
  2539. } else {
  2540. continue;
  2541. }
  2542. } else {
  2543. continue;
  2544. }
  2545. }
  2546. _face.normalWorld.copy( face.normal );
  2547. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2548. _normalMatrix.multiplyVector3( _face.normalWorld ).normalize();
  2549. _face.centroidWorld.copy( face.centroid );
  2550. modelMatrix.multiplyVector3( _face.centroidWorld );
  2551. _face.centroidScreen.copy( _face.centroidWorld );
  2552. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2553. faceVertexNormals = face.vertexNormals;
  2554. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2555. normal = _face.vertexNormalsWorld[ n ];
  2556. normal.copy( faceVertexNormals[ n ] );
  2557. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2558. _normalMatrix.multiplyVector3( normal ).normalize();
  2559. }
  2560. _face.vertexNormalsLength = faceVertexNormals.length;
  2561. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2562. uvs = faceVertexUvs[ c ][ f ];
  2563. if ( uvs === undefined ) continue;
  2564. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2565. _face.uvs[ c ][ u ] = uvs[ u ];
  2566. }
  2567. }
  2568. _face.color = face.color;
  2569. _face.material = material;
  2570. _face.z = _face.centroidScreen.z;
  2571. _renderData.elements.push( _face );
  2572. }
  2573. } else if ( object instanceof THREE.Line ) {
  2574. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2575. vertices = object.geometry.vertices;
  2576. v1 = getNextVertexInPool();
  2577. v1.positionScreen.copy( vertices[ 0 ] );
  2578. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2579. // Handle LineStrip and LinePieces
  2580. var step = object.type === THREE.LinePieces ? 2 : 1;
  2581. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2582. v1 = getNextVertexInPool();
  2583. v1.positionScreen.copy( vertices[ v ] );
  2584. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2585. if ( ( v + 1 ) % step > 0 ) continue;
  2586. v2 = _vertexPool[ _vertexCount - 2 ];
  2587. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2588. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2589. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2590. // Perform the perspective divide
  2591. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2592. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2593. _line = getNextLineInPool();
  2594. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2595. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2596. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2597. _line.material = object.material;
  2598. _renderData.elements.push( _line );
  2599. }
  2600. }
  2601. }
  2602. }
  2603. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2604. object = _renderData.sprites[ o ].object;
  2605. modelMatrix = object.matrixWorld;
  2606. if ( object instanceof THREE.Particle ) {
  2607. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2608. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2609. _vector4.z /= _vector4.w;
  2610. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2611. _particle = getNextParticleInPool();
  2612. _particle.object = object;
  2613. _particle.x = _vector4.x / _vector4.w;
  2614. _particle.y = _vector4.y / _vector4.w;
  2615. _particle.z = _vector4.z;
  2616. _particle.rotation = object.rotation.z;
  2617. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2618. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2619. _particle.material = object.material;
  2620. _renderData.elements.push( _particle );
  2621. }
  2622. }
  2623. }
  2624. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  2625. return _renderData;
  2626. };
  2627. // Pools
  2628. function getNextObjectInPool() {
  2629. if ( _objectCount === _objectPoolLength ) {
  2630. var object = new THREE.RenderableObject();
  2631. _objectPool.push( object );
  2632. _objectPoolLength ++;
  2633. _objectCount ++;
  2634. return object;
  2635. }
  2636. return _objectPool[ _objectCount ++ ];
  2637. }
  2638. function getNextVertexInPool() {
  2639. if ( _vertexCount === _vertexPoolLength ) {
  2640. var vertex = new THREE.RenderableVertex();
  2641. _vertexPool.push( vertex );
  2642. _vertexPoolLength ++;
  2643. _vertexCount ++;
  2644. return vertex;
  2645. }
  2646. return _vertexPool[ _vertexCount ++ ];
  2647. }
  2648. function getNextFace3InPool() {
  2649. if ( _face3Count === _face3PoolLength ) {
  2650. var face = new THREE.RenderableFace3();
  2651. _face3Pool.push( face );
  2652. _face3PoolLength ++;
  2653. _face3Count ++;
  2654. return face;
  2655. }
  2656. return _face3Pool[ _face3Count ++ ];
  2657. }
  2658. function getNextFace4InPool() {
  2659. if ( _face4Count === _face4PoolLength ) {
  2660. var face = new THREE.RenderableFace4();
  2661. _face4Pool.push( face );
  2662. _face4PoolLength ++;
  2663. _face4Count ++;
  2664. return face;
  2665. }
  2666. return _face4Pool[ _face4Count ++ ];
  2667. }
  2668. function getNextLineInPool() {
  2669. if ( _lineCount === _linePoolLength ) {
  2670. var line = new THREE.RenderableLine();
  2671. _linePool.push( line );
  2672. _linePoolLength ++;
  2673. _lineCount ++
  2674. return line;
  2675. }
  2676. return _linePool[ _lineCount ++ ];
  2677. }
  2678. function getNextParticleInPool() {
  2679. if ( _particleCount === _particlePoolLength ) {
  2680. var particle = new THREE.RenderableParticle();
  2681. _particlePool.push( particle );
  2682. _particlePoolLength ++;
  2683. _particleCount ++
  2684. return particle;
  2685. }
  2686. return _particlePool[ _particleCount ++ ];
  2687. }
  2688. //
  2689. function painterSort( a, b ) {
  2690. return b.z - a.z;
  2691. }
  2692. function clipLine( s1, s2 ) {
  2693. var alpha1 = 0, alpha2 = 1,
  2694. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2695. // Z = -1 and Z = +1, respectively.
  2696. bc1near = s1.z + s1.w,
  2697. bc2near = s2.z + s2.w,
  2698. bc1far = - s1.z + s1.w,
  2699. bc2far = - s2.z + s2.w;
  2700. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2701. // Both vertices lie entirely within all clip planes.
  2702. return true;
  2703. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2704. // Both vertices lie entirely outside one of the clip planes.
  2705. return false;
  2706. } else {
  2707. // The line segment spans at least one clip plane.
  2708. if ( bc1near < 0 ) {
  2709. // v1 lies outside the near plane, v2 inside
  2710. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2711. } else if ( bc2near < 0 ) {
  2712. // v2 lies outside the near plane, v1 inside
  2713. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2714. }
  2715. if ( bc1far < 0 ) {
  2716. // v1 lies outside the far plane, v2 inside
  2717. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2718. } else if ( bc2far < 0 ) {
  2719. // v2 lies outside the far plane, v2 inside
  2720. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2721. }
  2722. if ( alpha2 < alpha1 ) {
  2723. // The line segment spans two boundaries, but is outside both of them.
  2724. // (This can't happen when we're only clipping against just near/far but good
  2725. // to leave the check here for future usage if other clip planes are added.)
  2726. return false;
  2727. } else {
  2728. // Update the s1 and s2 vertices to match the clipped line segment.
  2729. s1.lerpSelf( s2, alpha1 );
  2730. s2.lerpSelf( s1, 1 - alpha2 );
  2731. return true;
  2732. }
  2733. }
  2734. }
  2735. };
  2736. /**
  2737. * @author mikael emtinger / http://gomo.se/
  2738. * @author alteredq / http://alteredqualia.com/
  2739. * @author WestLangley / http://github.com/WestLangley
  2740. */
  2741. THREE.Quaternion = function( x, y, z, w ) {
  2742. this.x = x || 0;
  2743. this.y = y || 0;
  2744. this.z = z || 0;
  2745. this.w = ( w !== undefined ) ? w : 1;
  2746. };
  2747. THREE.Quaternion.prototype = {
  2748. constructor: THREE.Quaternion,
  2749. set: function ( x, y, z, w ) {
  2750. this.x = x;
  2751. this.y = y;
  2752. this.z = z;
  2753. this.w = w;
  2754. return this;
  2755. },
  2756. copy: function ( q ) {
  2757. this.x = q.x;
  2758. this.y = q.y;
  2759. this.z = q.z;
  2760. this.w = q.w;
  2761. return this;
  2762. },
  2763. setFromEuler: function ( v, order ) {
  2764. // http://www.mathworks.com/matlabcentral/fileexchange/
  2765. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2766. // content/SpinCalc.m
  2767. var c1 = Math.cos( v.x / 2 );
  2768. var c2 = Math.cos( v.y / 2 );
  2769. var c3 = Math.cos( v.z / 2 );
  2770. var s1 = Math.sin( v.x / 2 );
  2771. var s2 = Math.sin( v.y / 2 );
  2772. var s3 = Math.sin( v.z / 2 );
  2773. if ( order === undefined || order === 'XYZ' ) {
  2774. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2775. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2776. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2777. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2778. } else if ( order === 'YXZ' ) {
  2779. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2780. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2781. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2782. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2783. } else if ( order === 'ZXY' ) {
  2784. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2785. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2786. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2787. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2788. } else if ( order === 'ZYX' ) {
  2789. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2790. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2791. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2792. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2793. } else if ( order === 'YZX' ) {
  2794. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2795. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2796. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2797. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2798. } else if ( order === 'XZY' ) {
  2799. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2800. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2801. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2802. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2803. }
  2804. return this;
  2805. },
  2806. setFromAxisAngle: function ( axis, angle ) {
  2807. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2808. // axis have to be normalized
  2809. var halfAngle = angle / 2,
  2810. s = Math.sin( halfAngle );
  2811. this.x = axis.x * s;
  2812. this.y = axis.y * s;
  2813. this.z = axis.z * s;
  2814. this.w = Math.cos( halfAngle );
  2815. return this;
  2816. },
  2817. setFromRotationMatrix: function ( m ) {
  2818. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2819. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2820. var te = m.elements,
  2821. m11 = te[0], m12 = te[4], m13 = te[8],
  2822. m21 = te[1], m22 = te[5], m23 = te[9],
  2823. m31 = te[2], m32 = te[6], m33 = te[10],
  2824. trace = m11 + m22 + m33,
  2825. s;
  2826. if( trace > 0 ) {
  2827. s = 0.5 / Math.sqrt( trace + 1.0 );
  2828. this.w = 0.25 / s;
  2829. this.x = ( m32 - m23 ) * s;
  2830. this.y = ( m13 - m31 ) * s;
  2831. this.z = ( m21 - m12 ) * s;
  2832. } else if ( m11 > m22 && m11 > m33 ) {
  2833. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2834. this.w = (m32 - m23 ) / s;
  2835. this.x = 0.25 * s;
  2836. this.y = (m12 + m21 ) / s;
  2837. this.z = (m13 + m31 ) / s;
  2838. } else if (m22 > m33) {
  2839. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2840. this.w = (m13 - m31 ) / s;
  2841. this.x = (m12 + m21 ) / s;
  2842. this.y = 0.25 * s;
  2843. this.z = (m23 + m32 ) / s;
  2844. } else {
  2845. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2846. this.w = ( m21 - m12 ) / s;
  2847. this.x = ( m13 + m31 ) / s;
  2848. this.y = ( m23 + m32 ) / s;
  2849. this.z = 0.25 * s;
  2850. }
  2851. return this;
  2852. },
  2853. inverse: function () {
  2854. this.conjugate().normalize();
  2855. return this;
  2856. },
  2857. conjugate: function () {
  2858. this.x *= -1;
  2859. this.y *= -1;
  2860. this.z *= -1;
  2861. return this;
  2862. },
  2863. length: function () {
  2864. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2865. },
  2866. normalize: function () {
  2867. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2868. if ( l === 0 ) {
  2869. this.x = 0;
  2870. this.y = 0;
  2871. this.z = 0;
  2872. this.w = 1;
  2873. } else {
  2874. l = 1 / l;
  2875. this.x = this.x * l;
  2876. this.y = this.y * l;
  2877. this.z = this.z * l;
  2878. this.w = this.w * l;
  2879. }
  2880. return this;
  2881. },
  2882. multiply: function ( a, b ) {
  2883. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2884. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2885. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2886. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2887. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2888. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2889. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2890. return this;
  2891. },
  2892. multiplySelf: function ( b ) {
  2893. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2894. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2895. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2896. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2897. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2898. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2899. return this;
  2900. },
  2901. multiplyVector3: function ( vector, dest ) {
  2902. if ( !dest ) { dest = vector; }
  2903. var x = vector.x, y = vector.y, z = vector.z,
  2904. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2905. // calculate quat * vector
  2906. var ix = qw * x + qy * z - qz * y,
  2907. iy = qw * y + qz * x - qx * z,
  2908. iz = qw * z + qx * y - qy * x,
  2909. iw = -qx * x - qy * y - qz * z;
  2910. // calculate result * inverse quat
  2911. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2912. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2913. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2914. return dest;
  2915. },
  2916. slerpSelf: function ( qb, t ) {
  2917. var x = this.x, y = this.y, z = this.z, w = this.w;
  2918. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2919. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2920. if ( cosHalfTheta < 0 ) {
  2921. this.w = -qb.w;
  2922. this.x = -qb.x;
  2923. this.y = -qb.y;
  2924. this.z = -qb.z;
  2925. cosHalfTheta = -cosHalfTheta;
  2926. } else {
  2927. this.copy( qb );
  2928. }
  2929. if ( cosHalfTheta >= 1.0 ) {
  2930. this.w = w;
  2931. this.x = x;
  2932. this.y = y;
  2933. this.z = z;
  2934. return this;
  2935. }
  2936. var halfTheta = Math.acos( cosHalfTheta );
  2937. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2938. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2939. this.w = 0.5 * ( w + this.w );
  2940. this.x = 0.5 * ( x + this.x );
  2941. this.y = 0.5 * ( y + this.y );
  2942. this.z = 0.5 * ( z + this.z );
  2943. return this;
  2944. }
  2945. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2946. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2947. this.w = ( w * ratioA + this.w * ratioB );
  2948. this.x = ( x * ratioA + this.x * ratioB );
  2949. this.y = ( y * ratioA + this.y * ratioB );
  2950. this.z = ( z * ratioA + this.z * ratioB );
  2951. return this;
  2952. },
  2953. clone: function () {
  2954. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2955. }
  2956. }
  2957. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2958. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2959. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2960. if ( cosHalfTheta < 0 ) {
  2961. qm.w = -qb.w;
  2962. qm.x = -qb.x;
  2963. qm.y = -qb.y;
  2964. qm.z = -qb.z;
  2965. cosHalfTheta = -cosHalfTheta;
  2966. } else {
  2967. qm.copy( qb );
  2968. }
  2969. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2970. qm.w = qa.w;
  2971. qm.x = qa.x;
  2972. qm.y = qa.y;
  2973. qm.z = qa.z;
  2974. return qm;
  2975. }
  2976. var halfTheta = Math.acos( cosHalfTheta );
  2977. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2978. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2979. qm.w = 0.5 * ( qa.w + qm.w );
  2980. qm.x = 0.5 * ( qa.x + qm.x );
  2981. qm.y = 0.5 * ( qa.y + qm.y );
  2982. qm.z = 0.5 * ( qa.z + qm.z );
  2983. return qm;
  2984. }
  2985. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2986. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2987. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2988. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2989. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2990. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2991. return qm;
  2992. }
  2993. /**
  2994. * @author mrdoob / http://mrdoob.com/
  2995. */
  2996. THREE.Vertex = function ( v ) {
  2997. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2998. return v;
  2999. };
  3000. /**
  3001. * @author mrdoob / http://mrdoob.com/
  3002. * @author alteredq / http://alteredqualia.com/
  3003. */
  3004. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  3005. this.a = a;
  3006. this.b = b;
  3007. this.c = c;
  3008. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  3009. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3010. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3011. this.vertexColors = color instanceof Array ? color : [];
  3012. this.vertexTangents = [];
  3013. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  3014. this.centroid = new THREE.Vector3();
  3015. };
  3016. THREE.Face3.prototype = {
  3017. constructor: THREE.Face3,
  3018. clone: function () {
  3019. var face = new THREE.Face3( this.a, this.b, this.c );
  3020. face.normal.copy( this.normal );
  3021. face.color.copy( this.color );
  3022. face.centroid.copy( this.centroid );
  3023. face.materialIndex = this.materialIndex;
  3024. var i, il;
  3025. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3026. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3027. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3028. return face;
  3029. }
  3030. };
  3031. /**
  3032. * @author mrdoob / http://mrdoob.com/
  3033. * @author alteredq / http://alteredqualia.com/
  3034. */
  3035. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  3036. this.a = a;
  3037. this.b = b;
  3038. this.c = c;
  3039. this.d = d;
  3040. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  3041. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3042. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3043. this.vertexColors = color instanceof Array ? color : [];
  3044. this.vertexTangents = [];
  3045. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  3046. this.centroid = new THREE.Vector3();
  3047. };
  3048. THREE.Face4.prototype = {
  3049. constructor: THREE.Face4,
  3050. clone: function () {
  3051. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  3052. face.normal.copy( this.normal );
  3053. face.color.copy( this.color );
  3054. face.centroid.copy( this.centroid );
  3055. face.materialIndex = this.materialIndex;
  3056. var i, il;
  3057. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3058. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3059. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3060. return face;
  3061. }
  3062. };
  3063. /**
  3064. * @author mrdoob / http://mrdoob.com/
  3065. */
  3066. THREE.UV = function ( u, v ) {
  3067. this.u = u || 0;
  3068. this.v = v || 0;
  3069. };
  3070. THREE.UV.prototype = {
  3071. constructor: THREE.UV,
  3072. set: function ( u, v ) {
  3073. this.u = u;
  3074. this.v = v;
  3075. return this;
  3076. },
  3077. copy: function ( uv ) {
  3078. this.u = uv.u;
  3079. this.v = uv.v;
  3080. return this;
  3081. },
  3082. lerpSelf: function ( uv, alpha ) {
  3083. this.u += ( uv.u - this.u ) * alpha;
  3084. this.v += ( uv.v - this.v ) * alpha;
  3085. return this;
  3086. },
  3087. clone: function () {
  3088. return new THREE.UV( this.u, this.v );
  3089. }
  3090. };
  3091. /**
  3092. * @author mrdoob / http://mrdoob.com/
  3093. * @author kile / http://kile.stravaganza.org/
  3094. * @author alteredq / http://alteredqualia.com/
  3095. * @author mikael emtinger / http://gomo.se/
  3096. * @author zz85 / http://www.lab4games.net/zz85/blog
  3097. */
  3098. THREE.Geometry = function () {
  3099. THREE.GeometryLibrary.push( this );
  3100. this.id = THREE.GeometryIdCount ++;
  3101. this.name = '';
  3102. this.vertices = [];
  3103. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  3104. this.normals = []; // one-to-one vertex normals, used in Ribbon
  3105. this.faces = [];
  3106. this.faceUvs = [[]];
  3107. this.faceVertexUvs = [[]];
  3108. this.morphTargets = [];
  3109. this.morphColors = [];
  3110. this.morphNormals = [];
  3111. this.skinWeights = [];
  3112. this.skinIndices = [];
  3113. this.lineDistances = [];
  3114. this.boundingBox = null;
  3115. this.boundingSphere = null;
  3116. this.hasTangents = false;
  3117. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  3118. // update flags
  3119. this.verticesNeedUpdate = false;
  3120. this.elementsNeedUpdate = false;
  3121. this.uvsNeedUpdate = false;
  3122. this.normalsNeedUpdate = false;
  3123. this.tangentsNeedUpdate = false;
  3124. this.colorsNeedUpdate = false;
  3125. this.lineDistancesNeedUpdate = false;
  3126. this.buffersNeedUpdate = false;
  3127. };
  3128. THREE.Geometry.prototype = {
  3129. constructor : THREE.Geometry,
  3130. applyMatrix: function ( matrix ) {
  3131. var normalMatrix = new THREE.Matrix3();
  3132. normalMatrix.getInverse( matrix ).transpose();
  3133. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3134. var vertex = this.vertices[ i ];
  3135. matrix.multiplyVector3( vertex );
  3136. }
  3137. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3138. var face = this.faces[ i ];
  3139. normalMatrix.multiplyVector3( face.normal ).normalize();
  3140. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3141. normalMatrix.multiplyVector3( face.vertexNormals[ j ] ).normalize();
  3142. }
  3143. matrix.multiplyVector3( face.centroid );
  3144. }
  3145. },
  3146. computeCentroids: function () {
  3147. var f, fl, face;
  3148. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3149. face = this.faces[ f ];
  3150. face.centroid.set( 0, 0, 0 );
  3151. if ( face instanceof THREE.Face3 ) {
  3152. face.centroid.addSelf( this.vertices[ face.a ] );
  3153. face.centroid.addSelf( this.vertices[ face.b ] );
  3154. face.centroid.addSelf( this.vertices[ face.c ] );
  3155. face.centroid.divideScalar( 3 );
  3156. } else if ( face instanceof THREE.Face4 ) {
  3157. face.centroid.addSelf( this.vertices[ face.a ] );
  3158. face.centroid.addSelf( this.vertices[ face.b ] );
  3159. face.centroid.addSelf( this.vertices[ face.c ] );
  3160. face.centroid.addSelf( this.vertices[ face.d ] );
  3161. face.centroid.divideScalar( 4 );
  3162. }
  3163. }
  3164. },
  3165. computeFaceNormals: function () {
  3166. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3167. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3168. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3169. face = this.faces[ f ];
  3170. vA = this.vertices[ face.a ];
  3171. vB = this.vertices[ face.b ];
  3172. vC = this.vertices[ face.c ];
  3173. cb.sub( vC, vB );
  3174. ab.sub( vA, vB );
  3175. cb.crossSelf( ab );
  3176. cb.normalize();
  3177. face.normal.copy( cb );
  3178. }
  3179. },
  3180. computeVertexNormals: function ( areaWeighted ) {
  3181. var v, vl, f, fl, face, vertices;
  3182. // create internal buffers for reuse when calling this method repeatedly
  3183. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3184. if ( this.__tmpVertices === undefined ) {
  3185. this.__tmpVertices = new Array( this.vertices.length );
  3186. vertices = this.__tmpVertices;
  3187. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3188. vertices[ v ] = new THREE.Vector3();
  3189. }
  3190. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3191. face = this.faces[ f ];
  3192. if ( face instanceof THREE.Face3 ) {
  3193. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3194. } else if ( face instanceof THREE.Face4 ) {
  3195. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3196. }
  3197. }
  3198. } else {
  3199. vertices = this.__tmpVertices;
  3200. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3201. vertices[ v ].set( 0, 0, 0 );
  3202. }
  3203. }
  3204. if ( areaWeighted ) {
  3205. // vertex normals weighted by triangle areas
  3206. // http://www.iquilezles.org/www/articles/normals/normals.htm
  3207. var vA, vB, vC, vD;
  3208. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  3209. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  3210. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3211. face = this.faces[ f ];
  3212. if ( face instanceof THREE.Face3 ) {
  3213. vA = this.vertices[ face.a ];
  3214. vB = this.vertices[ face.b ];
  3215. vC = this.vertices[ face.c ];
  3216. cb.sub( vC, vB );
  3217. ab.sub( vA, vB );
  3218. cb.crossSelf( ab );
  3219. vertices[ face.a ].addSelf( cb );
  3220. vertices[ face.b ].addSelf( cb );
  3221. vertices[ face.c ].addSelf( cb );
  3222. } else if ( face instanceof THREE.Face4 ) {
  3223. vA = this.vertices[ face.a ];
  3224. vB = this.vertices[ face.b ];
  3225. vC = this.vertices[ face.c ];
  3226. vD = this.vertices[ face.d ];
  3227. // abd
  3228. db.sub( vD, vB );
  3229. ab.sub( vA, vB );
  3230. db.crossSelf( ab );
  3231. vertices[ face.a ].addSelf( db );
  3232. vertices[ face.b ].addSelf( db );
  3233. vertices[ face.d ].addSelf( db );
  3234. // bcd
  3235. dc.sub( vD, vC );
  3236. bc.sub( vB, vC );
  3237. dc.crossSelf( bc );
  3238. vertices[ face.b ].addSelf( dc );
  3239. vertices[ face.c ].addSelf( dc );
  3240. vertices[ face.d ].addSelf( dc );
  3241. }
  3242. }
  3243. } else {
  3244. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3245. face = this.faces[ f ];
  3246. if ( face instanceof THREE.Face3 ) {
  3247. vertices[ face.a ].addSelf( face.normal );
  3248. vertices[ face.b ].addSelf( face.normal );
  3249. vertices[ face.c ].addSelf( face.normal );
  3250. } else if ( face instanceof THREE.Face4 ) {
  3251. vertices[ face.a ].addSelf( face.normal );
  3252. vertices[ face.b ].addSelf( face.normal );
  3253. vertices[ face.c ].addSelf( face.normal );
  3254. vertices[ face.d ].addSelf( face.normal );
  3255. }
  3256. }
  3257. }
  3258. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3259. vertices[ v ].normalize();
  3260. }
  3261. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3262. face = this.faces[ f ];
  3263. if ( face instanceof THREE.Face3 ) {
  3264. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3265. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3266. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3267. } else if ( face instanceof THREE.Face4 ) {
  3268. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3269. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3270. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3271. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3272. }
  3273. }
  3274. },
  3275. computeMorphNormals: function () {
  3276. var i, il, f, fl, face;
  3277. // save original normals
  3278. // - create temp variables on first access
  3279. // otherwise just copy (for faster repeated calls)
  3280. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3281. face = this.faces[ f ];
  3282. if ( ! face.__originalFaceNormal ) {
  3283. face.__originalFaceNormal = face.normal.clone();
  3284. } else {
  3285. face.__originalFaceNormal.copy( face.normal );
  3286. }
  3287. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3288. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3289. if ( ! face.__originalVertexNormals[ i ] ) {
  3290. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3291. } else {
  3292. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3293. }
  3294. }
  3295. }
  3296. // use temp geometry to compute face and vertex normals for each morph
  3297. var tmpGeo = new THREE.Geometry();
  3298. tmpGeo.faces = this.faces;
  3299. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3300. // create on first access
  3301. if ( ! this.morphNormals[ i ] ) {
  3302. this.morphNormals[ i ] = {};
  3303. this.morphNormals[ i ].faceNormals = [];
  3304. this.morphNormals[ i ].vertexNormals = [];
  3305. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3306. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3307. var faceNormal, vertexNormals;
  3308. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3309. face = this.faces[ f ];
  3310. faceNormal = new THREE.Vector3();
  3311. if ( face instanceof THREE.Face3 ) {
  3312. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3313. } else {
  3314. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3315. }
  3316. dstNormalsFace.push( faceNormal );
  3317. dstNormalsVertex.push( vertexNormals );
  3318. }
  3319. }
  3320. var morphNormals = this.morphNormals[ i ];
  3321. // set vertices to morph target
  3322. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3323. // compute morph normals
  3324. tmpGeo.computeFaceNormals();
  3325. tmpGeo.computeVertexNormals();
  3326. // store morph normals
  3327. var faceNormal, vertexNormals;
  3328. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3329. face = this.faces[ f ];
  3330. faceNormal = morphNormals.faceNormals[ f ];
  3331. vertexNormals = morphNormals.vertexNormals[ f ];
  3332. faceNormal.copy( face.normal );
  3333. if ( face instanceof THREE.Face3 ) {
  3334. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3335. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3336. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3337. } else {
  3338. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3339. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3340. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3341. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3342. }
  3343. }
  3344. }
  3345. // restore original normals
  3346. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3347. face = this.faces[ f ];
  3348. face.normal = face.__originalFaceNormal;
  3349. face.vertexNormals = face.__originalVertexNormals;
  3350. }
  3351. },
  3352. computeTangents: function () {
  3353. // based on http://www.terathon.com/code/tangent.html
  3354. // tangents go to vertices
  3355. var f, fl, v, vl, i, il, vertexIndex,
  3356. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3357. x1, x2, y1, y2, z1, z2,
  3358. s1, s2, t1, t2, r, t, test,
  3359. tan1 = [], tan2 = [],
  3360. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3361. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3362. n = new THREE.Vector3(), w;
  3363. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3364. tan1[ v ] = new THREE.Vector3();
  3365. tan2[ v ] = new THREE.Vector3();
  3366. }
  3367. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3368. vA = context.vertices[ a ];
  3369. vB = context.vertices[ b ];
  3370. vC = context.vertices[ c ];
  3371. uvA = uv[ ua ];
  3372. uvB = uv[ ub ];
  3373. uvC = uv[ uc ];
  3374. x1 = vB.x - vA.x;
  3375. x2 = vC.x - vA.x;
  3376. y1 = vB.y - vA.y;
  3377. y2 = vC.y - vA.y;
  3378. z1 = vB.z - vA.z;
  3379. z2 = vC.z - vA.z;
  3380. s1 = uvB.u - uvA.u;
  3381. s2 = uvC.u - uvA.u;
  3382. t1 = uvB.v - uvA.v;
  3383. t2 = uvC.v - uvA.v;
  3384. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3385. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3386. ( t2 * y1 - t1 * y2 ) * r,
  3387. ( t2 * z1 - t1 * z2 ) * r );
  3388. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3389. ( s1 * y2 - s2 * y1 ) * r,
  3390. ( s1 * z2 - s2 * z1 ) * r );
  3391. tan1[ a ].addSelf( sdir );
  3392. tan1[ b ].addSelf( sdir );
  3393. tan1[ c ].addSelf( sdir );
  3394. tan2[ a ].addSelf( tdir );
  3395. tan2[ b ].addSelf( tdir );
  3396. tan2[ c ].addSelf( tdir );
  3397. }
  3398. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3399. face = this.faces[ f ];
  3400. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3401. if ( face instanceof THREE.Face3 ) {
  3402. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3403. } else if ( face instanceof THREE.Face4 ) {
  3404. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3405. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3406. }
  3407. }
  3408. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3409. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3410. face = this.faces[ f ];
  3411. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3412. n.copy( face.vertexNormals[ i ] );
  3413. vertexIndex = face[ faceIndex[ i ] ];
  3414. t = tan1[ vertexIndex ];
  3415. // Gram-Schmidt orthogonalize
  3416. tmp.copy( t );
  3417. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3418. // Calculate handedness
  3419. tmp2.cross( face.vertexNormals[ i ], t );
  3420. test = tmp2.dot( tan2[ vertexIndex ] );
  3421. w = (test < 0.0) ? -1.0 : 1.0;
  3422. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3423. }
  3424. }
  3425. this.hasTangents = true;
  3426. },
  3427. computeLineDistances: function ( ) {
  3428. var d = 0;
  3429. var vertices = this.vertices;
  3430. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3431. if ( i > 0 ) {
  3432. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  3433. }
  3434. this.lineDistances[ i ] = d;
  3435. }
  3436. },
  3437. computeBoundingBox: function () {
  3438. if ( ! this.boundingBox ) {
  3439. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3440. }
  3441. if ( this.vertices.length > 0 ) {
  3442. var position, firstPosition = this.vertices[ 0 ];
  3443. this.boundingBox.min.copy( firstPosition );
  3444. this.boundingBox.max.copy( firstPosition );
  3445. var min = this.boundingBox.min,
  3446. max = this.boundingBox.max;
  3447. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3448. position = this.vertices[ v ];
  3449. if ( position.x < min.x ) {
  3450. min.x = position.x;
  3451. } else if ( position.x > max.x ) {
  3452. max.x = position.x;
  3453. }
  3454. if ( position.y < min.y ) {
  3455. min.y = position.y;
  3456. } else if ( position.y > max.y ) {
  3457. max.y = position.y;
  3458. }
  3459. if ( position.z < min.z ) {
  3460. min.z = position.z;
  3461. } else if ( position.z > max.z ) {
  3462. max.z = position.z;
  3463. }
  3464. }
  3465. } else {
  3466. this.boundingBox.min.set( 0, 0, 0 );
  3467. this.boundingBox.max.set( 0, 0, 0 );
  3468. }
  3469. },
  3470. computeBoundingSphere: function () {
  3471. var maxRadiusSq = 0;
  3472. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3473. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3474. var radiusSq = this.vertices[ i ].lengthSq();
  3475. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3476. }
  3477. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3478. },
  3479. /*
  3480. * Checks for duplicate vertices with hashmap.
  3481. * Duplicated vertices are removed
  3482. * and faces' vertices are updated.
  3483. */
  3484. mergeVertices: function () {
  3485. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3486. var unique = [], changes = [];
  3487. var v, key;
  3488. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3489. var precision = Math.pow( 10, precisionPoints );
  3490. var i,il, face;
  3491. var abcd = 'abcd', o, k, j, jl, u;
  3492. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3493. v = this.vertices[ i ];
  3494. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3495. if ( verticesMap[ key ] === undefined ) {
  3496. verticesMap[ key ] = i;
  3497. unique.push( this.vertices[ i ] );
  3498. changes[ i ] = unique.length - 1;
  3499. } else {
  3500. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3501. changes[ i ] = changes[ verticesMap[ key ] ];
  3502. }
  3503. };
  3504. // Start to patch face indices
  3505. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3506. face = this.faces[ i ];
  3507. if ( face instanceof THREE.Face3 ) {
  3508. face.a = changes[ face.a ];
  3509. face.b = changes[ face.b ];
  3510. face.c = changes[ face.c ];
  3511. } else if ( face instanceof THREE.Face4 ) {
  3512. face.a = changes[ face.a ];
  3513. face.b = changes[ face.b ];
  3514. face.c = changes[ face.c ];
  3515. face.d = changes[ face.d ];
  3516. // check dups in (a, b, c, d) and convert to -> face3
  3517. o = [ face.a, face.b, face.c, face.d ];
  3518. for ( k = 3; k > 0; k -- ) {
  3519. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3520. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3521. o.splice( k, 1 );
  3522. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3523. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3524. u = this.faceVertexUvs[ j ][ i ];
  3525. if ( u ) u.splice( k, 1 );
  3526. }
  3527. this.faces[ i ].vertexColors = face.vertexColors;
  3528. break;
  3529. }
  3530. }
  3531. }
  3532. }
  3533. // Use unique set of vertices
  3534. var diff = this.vertices.length - unique.length;
  3535. this.vertices = unique;
  3536. return diff;
  3537. },
  3538. clone: function () {
  3539. var geometry = new THREE.Geometry();
  3540. var vertices = this.vertices;
  3541. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3542. geometry.vertices.push( vertices[ i ].clone() );
  3543. }
  3544. var faces = this.faces;
  3545. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  3546. geometry.faces.push( faces[ i ].clone() );
  3547. }
  3548. var uvs = this.faceVertexUvs[ 0 ];
  3549. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  3550. var uv = uvs[ i ], uvCopy = [];
  3551. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  3552. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  3553. }
  3554. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  3555. }
  3556. return geometry;
  3557. },
  3558. deallocate: function () {
  3559. var index = THREE.GeometryLibrary.indexOf( this );
  3560. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3561. }
  3562. };
  3563. THREE.GeometryIdCount = 0;
  3564. THREE.GeometryLibrary = [];
  3565. /**
  3566. * @author alteredq / http://alteredqualia.com/
  3567. */
  3568. THREE.BufferGeometry = function () {
  3569. THREE.GeometryLibrary.push( this );
  3570. this.id = THREE.GeometryIdCount ++;
  3571. // attributes
  3572. this.attributes = {};
  3573. // attributes typed arrays are kept only if dynamic flag is set
  3574. this.dynamic = false;
  3575. // offsets for chunks when using indexed elements
  3576. this.offsets = [];
  3577. // boundings
  3578. this.boundingBox = null;
  3579. this.boundingSphere = null;
  3580. this.hasTangents = false;
  3581. // for compatibility
  3582. this.morphTargets = [];
  3583. };
  3584. THREE.BufferGeometry.prototype = {
  3585. constructor : THREE.BufferGeometry,
  3586. applyMatrix: function ( matrix ) {
  3587. var positionArray;
  3588. var normalArray;
  3589. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3590. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3591. if ( positionArray !== undefined ) {
  3592. matrix.multiplyVector3Array( positionArray );
  3593. this.verticesNeedUpdate = true;
  3594. }
  3595. if ( normalArray !== undefined ) {
  3596. var normalMatrix = new THREE.Matrix3();
  3597. normalMatrix.getInverse( matrix ).transpose();
  3598. normalMatrix.multiplyVector3Array( normalArray );
  3599. this.normalizeNormals();
  3600. this.normalsNeedUpdate = true;
  3601. }
  3602. },
  3603. computeBoundingBox: function () {
  3604. if ( ! this.boundingBox ) {
  3605. this.boundingBox = {
  3606. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3607. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3608. };
  3609. }
  3610. var positions = this.attributes[ "position" ].array;
  3611. if ( positions ) {
  3612. var bb = this.boundingBox;
  3613. var x, y, z;
  3614. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3615. x = positions[ i ];
  3616. y = positions[ i + 1 ];
  3617. z = positions[ i + 2 ];
  3618. // bounding box
  3619. if ( x < bb.min.x ) {
  3620. bb.min.x = x;
  3621. } else if ( x > bb.max.x ) {
  3622. bb.max.x = x;
  3623. }
  3624. if ( y < bb.min.y ) {
  3625. bb.min.y = y;
  3626. } else if ( y > bb.max.y ) {
  3627. bb.max.y = y;
  3628. }
  3629. if ( z < bb.min.z ) {
  3630. bb.min.z = z;
  3631. } else if ( z > bb.max.z ) {
  3632. bb.max.z = z;
  3633. }
  3634. }
  3635. }
  3636. if ( positions === undefined || positions.length === 0 ) {
  3637. this.boundingBox.min.set( 0, 0, 0 );
  3638. this.boundingBox.max.set( 0, 0, 0 );
  3639. }
  3640. },
  3641. computeBoundingSphere: function () {
  3642. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3643. var positions = this.attributes[ "position" ].array;
  3644. if ( positions ) {
  3645. var radiusSq, maxRadiusSq = 0;
  3646. var x, y, z;
  3647. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3648. x = positions[ i ];
  3649. y = positions[ i + 1 ];
  3650. z = positions[ i + 2 ];
  3651. radiusSq = x * x + y * y + z * z;
  3652. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3653. }
  3654. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3655. }
  3656. },
  3657. computeVertexNormals: function () {
  3658. if ( this.attributes[ "position" ] ) {
  3659. var i, il;
  3660. var j, jl;
  3661. var nVertexElements = this.attributes[ "position" ].array.length;
  3662. if ( this.attributes[ "normal" ] === undefined ) {
  3663. this.attributes[ "normal" ] = {
  3664. itemSize: 3,
  3665. array: new Float32Array( nVertexElements ),
  3666. numItems: nVertexElements
  3667. };
  3668. } else {
  3669. // reset existing normals to zero
  3670. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3671. this.attributes[ "normal" ].array[ i ] = 0;
  3672. }
  3673. }
  3674. var positions = this.attributes[ "position" ].array;
  3675. var normals = this.attributes[ "normal" ].array;
  3676. var vA, vB, vC, x, y, z,
  3677. pA = new THREE.Vector3(),
  3678. pB = new THREE.Vector3(),
  3679. pC = new THREE.Vector3(),
  3680. cb = new THREE.Vector3(),
  3681. ab = new THREE.Vector3();
  3682. // indexed elements
  3683. if ( this.attributes[ "index" ] ) {
  3684. var indices = this.attributes[ "index" ].array;
  3685. var offsets = this.offsets;
  3686. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3687. var start = offsets[ j ].start;
  3688. var count = offsets[ j ].count;
  3689. var index = offsets[ j ].index;
  3690. for ( i = start, il = start + count; i < il; i += 3 ) {
  3691. vA = index + indices[ i ];
  3692. vB = index + indices[ i + 1 ];
  3693. vC = index + indices[ i + 2 ];
  3694. x = positions[ vA * 3 ];
  3695. y = positions[ vA * 3 + 1 ];
  3696. z = positions[ vA * 3 + 2 ];
  3697. pA.set( x, y, z );
  3698. x = positions[ vB * 3 ];
  3699. y = positions[ vB * 3 + 1 ];
  3700. z = positions[ vB * 3 + 2 ];
  3701. pB.set( x, y, z );
  3702. x = positions[ vC * 3 ];
  3703. y = positions[ vC * 3 + 1 ];
  3704. z = positions[ vC * 3 + 2 ];
  3705. pC.set( x, y, z );
  3706. cb.sub( pC, pB );
  3707. ab.sub( pA, pB );
  3708. cb.crossSelf( ab );
  3709. normals[ vA * 3 ] += cb.x;
  3710. normals[ vA * 3 + 1 ] += cb.y;
  3711. normals[ vA * 3 + 2 ] += cb.z;
  3712. normals[ vB * 3 ] += cb.x;
  3713. normals[ vB * 3 + 1 ] += cb.y;
  3714. normals[ vB * 3 + 2 ] += cb.z;
  3715. normals[ vC * 3 ] += cb.x;
  3716. normals[ vC * 3 + 1 ] += cb.y;
  3717. normals[ vC * 3 + 2 ] += cb.z;
  3718. }
  3719. }
  3720. // non-indexed elements (unconnected triangle soup)
  3721. } else {
  3722. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  3723. x = positions[ i ];
  3724. y = positions[ i + 1 ];
  3725. z = positions[ i + 2 ];
  3726. pA.set( x, y, z );
  3727. x = positions[ i + 3 ];
  3728. y = positions[ i + 4 ];
  3729. z = positions[ i + 5 ];
  3730. pB.set( x, y, z );
  3731. x = positions[ i + 6 ];
  3732. y = positions[ i + 7 ];
  3733. z = positions[ i + 8 ];
  3734. pC.set( x, y, z );
  3735. cb.sub( pC, pB );
  3736. ab.sub( pA, pB );
  3737. cb.crossSelf( ab );
  3738. normals[ i ] = cb.x;
  3739. normals[ i + 1 ] = cb.y;
  3740. normals[ i + 2 ] = cb.z;
  3741. normals[ i + 3 ] = cb.x;
  3742. normals[ i + 4 ] = cb.y;
  3743. normals[ i + 5 ] = cb.z;
  3744. normals[ i + 6 ] = cb.x;
  3745. normals[ i + 7 ] = cb.y;
  3746. normals[ i + 8 ] = cb.z;
  3747. }
  3748. }
  3749. this.normalizeNormals();
  3750. this.normalsNeedUpdate = true;
  3751. }
  3752. },
  3753. normalizeNormals: function () {
  3754. var normals = this.attributes[ "normal" ].array;
  3755. var x, y, z, n;
  3756. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  3757. x = normals[ i ];
  3758. y = normals[ i + 1 ];
  3759. z = normals[ i + 2 ];
  3760. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3761. normals[ i ] *= n;
  3762. normals[ i + 1 ] *= n;
  3763. normals[ i + 2 ] *= n;
  3764. }
  3765. },
  3766. computeTangents: function () {
  3767. // based on http://www.terathon.com/code/tangent.html
  3768. // (per vertex tangents)
  3769. if ( this.attributes[ "index" ] === undefined ||
  3770. this.attributes[ "position" ] === undefined ||
  3771. this.attributes[ "normal" ] === undefined ||
  3772. this.attributes[ "uv" ] === undefined ) {
  3773. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3774. return;
  3775. }
  3776. var indices = this.attributes[ "index" ].array;
  3777. var positions = this.attributes[ "position" ].array;
  3778. var normals = this.attributes[ "normal" ].array;
  3779. var uvs = this.attributes[ "uv" ].array;
  3780. var nVertices = positions.length / 3;
  3781. if ( this.attributes[ "tangent" ] === undefined ) {
  3782. var nTangentElements = 4 * nVertices;
  3783. this.attributes[ "tangent" ] = {
  3784. itemSize: 4,
  3785. array: new Float32Array( nTangentElements ),
  3786. numItems: nTangentElements
  3787. };
  3788. }
  3789. var tangents = this.attributes[ "tangent" ].array;
  3790. var tan1 = [], tan2 = [];
  3791. for ( var k = 0; k < nVertices; k ++ ) {
  3792. tan1[ k ] = new THREE.Vector3();
  3793. tan2[ k ] = new THREE.Vector3();
  3794. }
  3795. var xA, yA, zA,
  3796. xB, yB, zB,
  3797. xC, yC, zC,
  3798. uA, vA,
  3799. uB, vB,
  3800. uC, vC,
  3801. x1, x2, y1, y2, z1, z2,
  3802. s1, s2, t1, t2, r;
  3803. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3804. function handleTriangle( a, b, c ) {
  3805. xA = positions[ a * 3 ];
  3806. yA = positions[ a * 3 + 1 ];
  3807. zA = positions[ a * 3 + 2 ];
  3808. xB = positions[ b * 3 ];
  3809. yB = positions[ b * 3 + 1 ];
  3810. zB = positions[ b * 3 + 2 ];
  3811. xC = positions[ c * 3 ];
  3812. yC = positions[ c * 3 + 1 ];
  3813. zC = positions[ c * 3 + 2 ];
  3814. uA = uvs[ a * 2 ];
  3815. vA = uvs[ a * 2 + 1 ];
  3816. uB = uvs[ b * 2 ];
  3817. vB = uvs[ b * 2 + 1 ];
  3818. uC = uvs[ c * 2 ];
  3819. vC = uvs[ c * 2 + 1 ];
  3820. x1 = xB - xA;
  3821. x2 = xC - xA;
  3822. y1 = yB - yA;
  3823. y2 = yC - yA;
  3824. z1 = zB - zA;
  3825. z2 = zC - zA;
  3826. s1 = uB - uA;
  3827. s2 = uC - uA;
  3828. t1 = vB - vA;
  3829. t2 = vC - vA;
  3830. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3831. sdir.set(
  3832. ( t2 * x1 - t1 * x2 ) * r,
  3833. ( t2 * y1 - t1 * y2 ) * r,
  3834. ( t2 * z1 - t1 * z2 ) * r
  3835. );
  3836. tdir.set(
  3837. ( s1 * x2 - s2 * x1 ) * r,
  3838. ( s1 * y2 - s2 * y1 ) * r,
  3839. ( s1 * z2 - s2 * z1 ) * r
  3840. );
  3841. tan1[ a ].addSelf( sdir );
  3842. tan1[ b ].addSelf( sdir );
  3843. tan1[ c ].addSelf( sdir );
  3844. tan2[ a ].addSelf( tdir );
  3845. tan2[ b ].addSelf( tdir );
  3846. tan2[ c ].addSelf( tdir );
  3847. }
  3848. var i, il;
  3849. var j, jl;
  3850. var iA, iB, iC;
  3851. var offsets = this.offsets;
  3852. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3853. var start = offsets[ j ].start;
  3854. var count = offsets[ j ].count;
  3855. var index = offsets[ j ].index;
  3856. for ( i = start, il = start + count; i < il; i += 3 ) {
  3857. iA = index + indices[ i ];
  3858. iB = index + indices[ i + 1 ];
  3859. iC = index + indices[ i + 2 ];
  3860. handleTriangle( iA, iB, iC );
  3861. }
  3862. }
  3863. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3864. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3865. var w, t, test;
  3866. var nx, ny, nz;
  3867. function handleVertex( v ) {
  3868. n.x = normals[ v * 3 ];
  3869. n.y = normals[ v * 3 + 1 ];
  3870. n.z = normals[ v * 3 + 2 ];
  3871. n2.copy( n );
  3872. t = tan1[ v ];
  3873. // Gram-Schmidt orthogonalize
  3874. tmp.copy( t );
  3875. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3876. // Calculate handedness
  3877. tmp2.cross( n2, t );
  3878. test = tmp2.dot( tan2[ v ] );
  3879. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3880. tangents[ v * 4 ] = tmp.x;
  3881. tangents[ v * 4 + 1 ] = tmp.y;
  3882. tangents[ v * 4 + 2 ] = tmp.z;
  3883. tangents[ v * 4 + 3 ] = w;
  3884. }
  3885. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3886. var start = offsets[ j ].start;
  3887. var count = offsets[ j ].count;
  3888. var index = offsets[ j ].index;
  3889. for ( i = start, il = start + count; i < il; i += 3 ) {
  3890. iA = index + indices[ i ];
  3891. iB = index + indices[ i + 1 ];
  3892. iC = index + indices[ i + 2 ];
  3893. handleVertex( iA );
  3894. handleVertex( iB );
  3895. handleVertex( iC );
  3896. }
  3897. }
  3898. this.hasTangents = true;
  3899. this.tangentsNeedUpdate = true;
  3900. },
  3901. deallocate: function () {
  3902. var index = THREE.GeometryLibrary.indexOf( this );
  3903. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3904. }
  3905. };
  3906. /**
  3907. * Spline from Tween.js, slightly optimized (and trashed)
  3908. * http://sole.github.com/tween.js/examples/05_spline.html
  3909. *
  3910. * @author mrdoob / http://mrdoob.com/
  3911. * @author alteredq / http://alteredqualia.com/
  3912. */
  3913. THREE.Spline = function ( points ) {
  3914. this.points = points;
  3915. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3916. point, intPoint, weight, w2, w3,
  3917. pa, pb, pc, pd;
  3918. this.initFromArray = function( a ) {
  3919. this.points = [];
  3920. for ( var i = 0; i < a.length; i++ ) {
  3921. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3922. }
  3923. };
  3924. this.getPoint = function ( k ) {
  3925. point = ( this.points.length - 1 ) * k;
  3926. intPoint = Math.floor( point );
  3927. weight = point - intPoint;
  3928. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3929. c[ 1 ] = intPoint;
  3930. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3931. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3932. pa = this.points[ c[ 0 ] ];
  3933. pb = this.points[ c[ 1 ] ];
  3934. pc = this.points[ c[ 2 ] ];
  3935. pd = this.points[ c[ 3 ] ];
  3936. w2 = weight * weight;
  3937. w3 = weight * w2;
  3938. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3939. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3940. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3941. return v3;
  3942. };
  3943. this.getControlPointsArray = function () {
  3944. var i, p, l = this.points.length,
  3945. coords = [];
  3946. for ( i = 0; i < l; i ++ ) {
  3947. p = this.points[ i ];
  3948. coords[ i ] = [ p.x, p.y, p.z ];
  3949. }
  3950. return coords;
  3951. };
  3952. // approximate length by summing linear segments
  3953. this.getLength = function ( nSubDivisions ) {
  3954. var i, index, nSamples, position,
  3955. point = 0, intPoint = 0, oldIntPoint = 0,
  3956. oldPosition = new THREE.Vector3(),
  3957. tmpVec = new THREE.Vector3(),
  3958. chunkLengths = [],
  3959. totalLength = 0;
  3960. // first point has 0 length
  3961. chunkLengths[ 0 ] = 0;
  3962. if ( !nSubDivisions ) nSubDivisions = 100;
  3963. nSamples = this.points.length * nSubDivisions;
  3964. oldPosition.copy( this.points[ 0 ] );
  3965. for ( i = 1; i < nSamples; i ++ ) {
  3966. index = i / nSamples;
  3967. position = this.getPoint( index );
  3968. tmpVec.copy( position );
  3969. totalLength += tmpVec.distanceTo( oldPosition );
  3970. oldPosition.copy( position );
  3971. point = ( this.points.length - 1 ) * index;
  3972. intPoint = Math.floor( point );
  3973. if ( intPoint != oldIntPoint ) {
  3974. chunkLengths[ intPoint ] = totalLength;
  3975. oldIntPoint = intPoint;
  3976. }
  3977. }
  3978. // last point ends with total length
  3979. chunkLengths[ chunkLengths.length ] = totalLength;
  3980. return { chunks: chunkLengths, total: totalLength };
  3981. };
  3982. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3983. var i, j,
  3984. index, indexCurrent, indexNext,
  3985. linearDistance, realDistance,
  3986. sampling, position,
  3987. newpoints = [],
  3988. tmpVec = new THREE.Vector3(),
  3989. sl = this.getLength();
  3990. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3991. for ( i = 1; i < this.points.length; i++ ) {
  3992. //tmpVec.copy( this.points[ i - 1 ] );
  3993. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3994. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3995. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3996. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3997. indexNext = i / ( this.points.length - 1 );
  3998. for ( j = 1; j < sampling - 1; j++ ) {
  3999. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4000. position = this.getPoint( index );
  4001. newpoints.push( tmpVec.copy( position ).clone() );
  4002. }
  4003. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4004. }
  4005. this.points = newpoints;
  4006. };
  4007. // Catmull-Rom
  4008. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4009. var v0 = ( p2 - p0 ) * 0.5,
  4010. v1 = ( p3 - p1 ) * 0.5;
  4011. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4012. };
  4013. };
  4014. /**
  4015. * @author mrdoob / http://mrdoob.com/
  4016. * @author mikael emtinger / http://gomo.se/
  4017. */
  4018. THREE.Camera = function () {
  4019. THREE.Object3D.call( this );
  4020. this.matrixWorldInverse = new THREE.Matrix4();
  4021. this.projectionMatrix = new THREE.Matrix4();
  4022. this.projectionMatrixInverse = new THREE.Matrix4();
  4023. };
  4024. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  4025. THREE.Camera.prototype.lookAt = function ( vector ) {
  4026. // TODO: Add hierarchy support.
  4027. this.matrix.lookAt( this.position, vector, this.up );
  4028. if ( this.rotationAutoUpdate === true ) {
  4029. if ( this.useQuaternion === false ) {
  4030. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  4031. } else {
  4032. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  4033. }
  4034. }
  4035. };
  4036. /**
  4037. * @author alteredq / http://alteredqualia.com/
  4038. */
  4039. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  4040. THREE.Camera.call( this );
  4041. this.left = left;
  4042. this.right = right;
  4043. this.top = top;
  4044. this.bottom = bottom;
  4045. this.near = ( near !== undefined ) ? near : 0.1;
  4046. this.far = ( far !== undefined ) ? far : 2000;
  4047. this.updateProjectionMatrix();
  4048. };
  4049. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  4050. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  4051. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  4052. };
  4053. /**
  4054. * @author mrdoob / http://mrdoob.com/
  4055. * @author greggman / http://games.greggman.com/
  4056. * @author zz85 / http://www.lab4games.net/zz85/blog
  4057. */
  4058. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  4059. THREE.Camera.call( this );
  4060. this.fov = fov !== undefined ? fov : 50;
  4061. this.aspect = aspect !== undefined ? aspect : 1;
  4062. this.near = near !== undefined ? near : 0.1;
  4063. this.far = far !== undefined ? far : 2000;
  4064. this.updateProjectionMatrix();
  4065. };
  4066. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  4067. /**
  4068. * Uses Focal Length (in mm) to estimate and set FOV
  4069. * 35mm (fullframe) camera is used if frame size is not specified;
  4070. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  4071. */
  4072. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  4073. if ( frameHeight === undefined ) frameHeight = 24;
  4074. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  4075. this.updateProjectionMatrix();
  4076. }
  4077. /**
  4078. * Sets an offset in a larger frustum. This is useful for multi-window or
  4079. * multi-monitor/multi-machine setups.
  4080. *
  4081. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  4082. * the monitors are in grid like this
  4083. *
  4084. * +---+---+---+
  4085. * | A | B | C |
  4086. * +---+---+---+
  4087. * | D | E | F |
  4088. * +---+---+---+
  4089. *
  4090. * then for each monitor you would call it like this
  4091. *
  4092. * var w = 1920;
  4093. * var h = 1080;
  4094. * var fullWidth = w * 3;
  4095. * var fullHeight = h * 2;
  4096. *
  4097. * --A--
  4098. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4099. * --B--
  4100. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4101. * --C--
  4102. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4103. * --D--
  4104. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4105. * --E--
  4106. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4107. * --F--
  4108. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4109. *
  4110. * Note there is no reason monitors have to be the same size or in a grid.
  4111. */
  4112. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4113. this.fullWidth = fullWidth;
  4114. this.fullHeight = fullHeight;
  4115. this.x = x;
  4116. this.y = y;
  4117. this.width = width;
  4118. this.height = height;
  4119. this.updateProjectionMatrix();
  4120. };
  4121. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4122. if ( this.fullWidth ) {
  4123. var aspect = this.fullWidth / this.fullHeight;
  4124. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  4125. var bottom = -top;
  4126. var left = aspect * bottom;
  4127. var right = aspect * top;
  4128. var width = Math.abs( right - left );
  4129. var height = Math.abs( top - bottom );
  4130. this.projectionMatrix.makeFrustum(
  4131. left + this.x * width / this.fullWidth,
  4132. left + ( this.x + this.width ) * width / this.fullWidth,
  4133. top - ( this.y + this.height ) * height / this.fullHeight,
  4134. top - this.y * height / this.fullHeight,
  4135. this.near,
  4136. this.far
  4137. );
  4138. } else {
  4139. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4140. }
  4141. };
  4142. /**
  4143. * @author mrdoob / http://mrdoob.com/
  4144. * @author alteredq / http://alteredqualia.com/
  4145. */
  4146. THREE.Light = function ( hex ) {
  4147. THREE.Object3D.call( this );
  4148. this.color = new THREE.Color( hex );
  4149. };
  4150. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4151. /**
  4152. * @author mrdoob / http://mrdoob.com/
  4153. */
  4154. THREE.AmbientLight = function ( hex ) {
  4155. THREE.Light.call( this, hex );
  4156. };
  4157. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4158. /**
  4159. * @author mrdoob / http://mrdoob.com/
  4160. * @author alteredq / http://alteredqualia.com/
  4161. */
  4162. THREE.DirectionalLight = function ( hex, intensity ) {
  4163. THREE.Light.call( this, hex );
  4164. this.position = new THREE.Vector3( 0, 1, 0 );
  4165. this.target = new THREE.Object3D();
  4166. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4167. this.castShadow = false;
  4168. this.onlyShadow = false;
  4169. //
  4170. this.shadowCameraNear = 50;
  4171. this.shadowCameraFar = 5000;
  4172. this.shadowCameraLeft = -500;
  4173. this.shadowCameraRight = 500;
  4174. this.shadowCameraTop = 500;
  4175. this.shadowCameraBottom = -500;
  4176. this.shadowCameraVisible = false;
  4177. this.shadowBias = 0;
  4178. this.shadowDarkness = 0.5;
  4179. this.shadowMapWidth = 512;
  4180. this.shadowMapHeight = 512;
  4181. //
  4182. this.shadowCascade = false;
  4183. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  4184. this.shadowCascadeCount = 2;
  4185. this.shadowCascadeBias = [ 0, 0, 0 ];
  4186. this.shadowCascadeWidth = [ 512, 512, 512 ];
  4187. this.shadowCascadeHeight = [ 512, 512, 512 ];
  4188. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  4189. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  4190. this.shadowCascadeArray = [];
  4191. //
  4192. this.shadowMap = null;
  4193. this.shadowMapSize = null;
  4194. this.shadowCamera = null;
  4195. this.shadowMatrix = null;
  4196. };
  4197. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  4198. /**
  4199. * @author alteredq / http://alteredqualia.com/
  4200. */
  4201. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  4202. THREE.Light.call( this, skyColorHex );
  4203. this.groundColor = new THREE.Color( groundColorHex );
  4204. this.position = new THREE.Vector3( 0, 100, 0 );
  4205. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4206. };
  4207. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  4208. /**
  4209. * @author mrdoob / http://mrdoob.com/
  4210. */
  4211. THREE.PointLight = function ( hex, intensity, distance ) {
  4212. THREE.Light.call( this, hex );
  4213. this.position = new THREE.Vector3( 0, 0, 0 );
  4214. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4215. this.distance = ( distance !== undefined ) ? distance : 0;
  4216. };
  4217. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  4218. /**
  4219. * @author alteredq / http://alteredqualia.com/
  4220. */
  4221. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  4222. THREE.Light.call( this, hex );
  4223. this.position = new THREE.Vector3( 0, 1, 0 );
  4224. this.target = new THREE.Object3D();
  4225. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4226. this.distance = ( distance !== undefined ) ? distance : 0;
  4227. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  4228. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  4229. this.castShadow = false;
  4230. this.onlyShadow = false;
  4231. //
  4232. this.shadowCameraNear = 50;
  4233. this.shadowCameraFar = 5000;
  4234. this.shadowCameraFov = 50;
  4235. this.shadowCameraVisible = false;
  4236. this.shadowBias = 0;
  4237. this.shadowDarkness = 0.5;
  4238. this.shadowMapWidth = 512;
  4239. this.shadowMapHeight = 512;
  4240. //
  4241. this.shadowMap = null;
  4242. this.shadowMapSize = null;
  4243. this.shadowCamera = null;
  4244. this.shadowMatrix = null;
  4245. };
  4246. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4247. /**
  4248. * @author alteredq / http://alteredqualia.com/
  4249. */
  4250. THREE.Loader = function ( showStatus ) {
  4251. this.showStatus = showStatus;
  4252. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4253. this.onLoadStart = function () {};
  4254. this.onLoadProgress = function () {};
  4255. this.onLoadComplete = function () {};
  4256. };
  4257. THREE.Loader.prototype = {
  4258. constructor: THREE.Loader,
  4259. crossOrigin: 'anonymous',
  4260. addStatusElement: function () {
  4261. var e = document.createElement( "div" );
  4262. e.style.position = "absolute";
  4263. e.style.right = "0px";
  4264. e.style.top = "0px";
  4265. e.style.fontSize = "0.8em";
  4266. e.style.textAlign = "left";
  4267. e.style.background = "rgba(0,0,0,0.25)";
  4268. e.style.color = "#fff";
  4269. e.style.width = "120px";
  4270. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4271. e.style.zIndex = 1000;
  4272. e.innerHTML = "Loading ...";
  4273. return e;
  4274. },
  4275. updateProgress: function ( progress ) {
  4276. var message = "Loaded ";
  4277. if ( progress.total ) {
  4278. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4279. } else {
  4280. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4281. }
  4282. this.statusDomElement.innerHTML = message;
  4283. },
  4284. extractUrlBase: function ( url ) {
  4285. var parts = url.split( '/' );
  4286. parts.pop();
  4287. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4288. },
  4289. initMaterials: function ( materials, texturePath ) {
  4290. var array = [];
  4291. for ( var i = 0; i < materials.length; ++ i ) {
  4292. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4293. }
  4294. return array;
  4295. },
  4296. needsTangents: function ( materials ) {
  4297. for( var i = 0, il = materials.length; i < il; i ++ ) {
  4298. var m = materials[ i ];
  4299. if ( m instanceof THREE.ShaderMaterial ) return true;
  4300. }
  4301. return false;
  4302. },
  4303. createMaterial: function ( m, texturePath ) {
  4304. var _this = this;
  4305. function is_pow2( n ) {
  4306. var l = Math.log( n ) / Math.LN2;
  4307. return Math.floor( l ) == l;
  4308. }
  4309. function nearest_pow2( n ) {
  4310. var l = Math.log( n ) / Math.LN2;
  4311. return Math.pow( 2, Math.round( l ) );
  4312. }
  4313. function load_image( where, url ) {
  4314. var image = new Image();
  4315. image.onload = function () {
  4316. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4317. var width = nearest_pow2( this.width );
  4318. var height = nearest_pow2( this.height );
  4319. where.image.width = width;
  4320. where.image.height = height;
  4321. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4322. } else {
  4323. where.image = this;
  4324. }
  4325. where.needsUpdate = true;
  4326. };
  4327. image.crossOrigin = _this.crossOrigin;
  4328. image.src = url;
  4329. }
  4330. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4331. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4332. var fullPath = texturePath + "/" + sourceFile;
  4333. if ( isCompressed ) {
  4334. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4335. where[ name ] = texture;
  4336. } else {
  4337. var texture = document.createElement( 'canvas' );
  4338. where[ name ] = new THREE.Texture( texture );
  4339. }
  4340. where[ name ].sourceFile = sourceFile;
  4341. if( repeat ) {
  4342. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4343. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4344. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4345. }
  4346. if ( offset ) {
  4347. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4348. }
  4349. if ( wrap ) {
  4350. var wrapMap = {
  4351. "repeat": THREE.RepeatWrapping,
  4352. "mirror": THREE.MirroredRepeatWrapping
  4353. }
  4354. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4355. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4356. }
  4357. if ( anisotropy ) {
  4358. where[ name ].anisotropy = anisotropy;
  4359. }
  4360. if ( ! isCompressed ) {
  4361. load_image( where[ name ], fullPath );
  4362. }
  4363. }
  4364. function rgb2hex( rgb ) {
  4365. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4366. }
  4367. // defaults
  4368. var mtype = "MeshLambertMaterial";
  4369. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4370. // parameters from model file
  4371. if ( m.shading ) {
  4372. var shading = m.shading.toLowerCase();
  4373. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4374. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4375. }
  4376. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4377. mpars.blending = THREE[ m.blending ];
  4378. }
  4379. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4380. mpars.transparent = m.transparent;
  4381. }
  4382. if ( m.depthTest !== undefined ) {
  4383. mpars.depthTest = m.depthTest;
  4384. }
  4385. if ( m.depthWrite !== undefined ) {
  4386. mpars.depthWrite = m.depthWrite;
  4387. }
  4388. if ( m.visible !== undefined ) {
  4389. mpars.visible = m.visible;
  4390. }
  4391. if ( m.flipSided !== undefined ) {
  4392. mpars.side = THREE.BackSide;
  4393. }
  4394. if ( m.doubleSided !== undefined ) {
  4395. mpars.side = THREE.DoubleSide;
  4396. }
  4397. if ( m.wireframe !== undefined ) {
  4398. mpars.wireframe = m.wireframe;
  4399. }
  4400. if ( m.vertexColors !== undefined ) {
  4401. if ( m.vertexColors === "face" ) {
  4402. mpars.vertexColors = THREE.FaceColors;
  4403. } else if ( m.vertexColors ) {
  4404. mpars.vertexColors = THREE.VertexColors;
  4405. }
  4406. }
  4407. // colors
  4408. if ( m.colorDiffuse ) {
  4409. mpars.color = rgb2hex( m.colorDiffuse );
  4410. } else if ( m.DbgColor ) {
  4411. mpars.color = m.DbgColor;
  4412. }
  4413. if ( m.colorSpecular ) {
  4414. mpars.specular = rgb2hex( m.colorSpecular );
  4415. }
  4416. if ( m.colorAmbient ) {
  4417. mpars.ambient = rgb2hex( m.colorAmbient );
  4418. }
  4419. // modifiers
  4420. if ( m.transparency ) {
  4421. mpars.opacity = m.transparency;
  4422. }
  4423. if ( m.specularCoef ) {
  4424. mpars.shininess = m.specularCoef;
  4425. }
  4426. // textures
  4427. if ( m.mapDiffuse && texturePath ) {
  4428. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  4429. }
  4430. if ( m.mapLight && texturePath ) {
  4431. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  4432. }
  4433. if ( m.mapBump && texturePath ) {
  4434. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  4435. }
  4436. if ( m.mapNormal && texturePath ) {
  4437. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  4438. }
  4439. if ( m.mapSpecular && texturePath ) {
  4440. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  4441. }
  4442. //
  4443. if ( m.mapBumpScale ) {
  4444. mpars.bumpScale = m.mapBumpScale;
  4445. }
  4446. // special case for normal mapped material
  4447. if ( m.mapNormal ) {
  4448. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4449. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4450. uniforms[ "tNormal" ].value = mpars.normalMap;
  4451. if ( m.mapNormalFactor ) {
  4452. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  4453. }
  4454. if ( mpars.map ) {
  4455. uniforms[ "tDiffuse" ].value = mpars.map;
  4456. uniforms[ "enableDiffuse" ].value = true;
  4457. }
  4458. if ( mpars.specularMap ) {
  4459. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4460. uniforms[ "enableSpecular" ].value = true;
  4461. }
  4462. if ( mpars.lightMap ) {
  4463. uniforms[ "tAO" ].value = mpars.lightMap;
  4464. uniforms[ "enableAO" ].value = true;
  4465. }
  4466. // for the moment don't handle displacement texture
  4467. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4468. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4469. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4470. uniforms[ "uShininess" ].value = mpars.shininess;
  4471. if ( mpars.opacity !== undefined ) {
  4472. uniforms[ "uOpacity" ].value = mpars.opacity;
  4473. }
  4474. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4475. var material = new THREE.ShaderMaterial( parameters );
  4476. } else {
  4477. var material = new THREE[ mtype ]( mpars );
  4478. }
  4479. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4480. return material;
  4481. }
  4482. };
  4483. /**
  4484. * @author alteredq / http://alteredqualia.com/
  4485. */
  4486. THREE.BinaryLoader = function ( showStatus ) {
  4487. THREE.Loader.call( this, showStatus );
  4488. };
  4489. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4490. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4491. // - binary models consist of two files: JS and BIN
  4492. // - parameters
  4493. // - url (required)
  4494. // - callback (required)
  4495. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4496. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4497. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4498. // todo: unify load API to for easier SceneLoader use
  4499. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4500. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  4501. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4502. this.onLoadStart();
  4503. // #1 load JS part via web worker
  4504. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4505. };
  4506. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4507. var xhr = new XMLHttpRequest();
  4508. xhr.onreadystatechange = function () {
  4509. if ( xhr.readyState == 4 ) {
  4510. if ( xhr.status == 200 || xhr.status == 0 ) {
  4511. var json = JSON.parse( xhr.responseText );
  4512. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4513. } else {
  4514. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4515. }
  4516. }
  4517. };
  4518. xhr.open( "GET", url, true );
  4519. xhr.send( null );
  4520. };
  4521. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4522. var xhr = new XMLHttpRequest(),
  4523. url = binaryPath + "/" + json.buffers;
  4524. var length = 0;
  4525. xhr.onreadystatechange = function () {
  4526. if ( xhr.readyState == 4 ) {
  4527. if ( xhr.status == 200 || xhr.status == 0 ) {
  4528. var buffer = xhr.response;
  4529. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4530. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4531. } else {
  4532. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4533. }
  4534. } else if ( xhr.readyState == 3 ) {
  4535. if ( callbackProgress ) {
  4536. if ( length == 0 ) {
  4537. length = xhr.getResponseHeader( "Content-Length" );
  4538. }
  4539. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4540. }
  4541. } else if ( xhr.readyState == 2 ) {
  4542. length = xhr.getResponseHeader( "Content-Length" );
  4543. }
  4544. };
  4545. xhr.open( "GET", url, true );
  4546. xhr.responseType = "arraybuffer";
  4547. xhr.send( null );
  4548. };
  4549. // Binary AJAX parser
  4550. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  4551. var Model = function ( texturePath ) {
  4552. var scope = this,
  4553. currentOffset = 0,
  4554. md,
  4555. normals = [],
  4556. uvs = [],
  4557. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4558. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4559. tri_size, quad_size,
  4560. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4561. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4562. THREE.Geometry.call( this );
  4563. md = parseMetaData( data, currentOffset );
  4564. currentOffset += md.header_bytes;
  4565. /*
  4566. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4567. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4568. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4569. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4570. */
  4571. // buffers sizes
  4572. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4573. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4574. len_tri_flat = md.ntri_flat * ( tri_size );
  4575. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4576. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4577. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4578. len_quad_flat = md.nquad_flat * ( quad_size );
  4579. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4580. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4581. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4582. // read buffers
  4583. currentOffset += init_vertices( currentOffset );
  4584. currentOffset += init_normals( currentOffset );
  4585. currentOffset += handlePadding( md.nnormals * 3 );
  4586. currentOffset += init_uvs( currentOffset );
  4587. start_tri_flat = currentOffset;
  4588. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4589. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4590. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4591. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4592. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4593. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4594. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4595. // have to first process faces with uvs
  4596. // so that face and uv indices match
  4597. init_triangles_flat_uv( start_tri_flat_uv );
  4598. init_triangles_smooth_uv( start_tri_smooth_uv );
  4599. init_quads_flat_uv( start_quad_flat_uv );
  4600. init_quads_smooth_uv( start_quad_smooth_uv );
  4601. // now we can process untextured faces
  4602. init_triangles_flat( start_tri_flat );
  4603. init_triangles_smooth( start_tri_smooth );
  4604. init_quads_flat( start_quad_flat );
  4605. init_quads_smooth( start_quad_smooth );
  4606. this.computeCentroids();
  4607. this.computeFaceNormals();
  4608. function handlePadding( n ) {
  4609. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4610. };
  4611. function parseMetaData( data, offset ) {
  4612. var metaData = {
  4613. 'signature' :parseString( data, offset, 12 ),
  4614. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4615. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4616. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4617. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4618. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4619. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4620. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4621. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4622. 'nvertices' :parseUInt32( data, offset + 20 ),
  4623. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4624. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4625. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4626. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4627. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4628. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4629. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4630. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4631. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4632. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4633. };
  4634. /*
  4635. console.log( "signature: " + metaData.signature );
  4636. console.log( "header_bytes: " + metaData.header_bytes );
  4637. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4638. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4639. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4640. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4641. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4642. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4643. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4644. console.log( "nvertices: " + metaData.nvertices );
  4645. console.log( "nnormals: " + metaData.nnormals );
  4646. console.log( "nuvs: " + metaData.nuvs );
  4647. console.log( "ntri_flat: " + metaData.ntri_flat );
  4648. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4649. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4650. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4651. console.log( "nquad_flat: " + metaData.nquad_flat );
  4652. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4653. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4654. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4655. var total = metaData.header_bytes
  4656. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4657. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4658. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4659. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4660. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4661. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4662. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4663. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4664. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4665. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4666. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4667. console.log( "total bytes: " + total );
  4668. */
  4669. return metaData;
  4670. };
  4671. function parseString( data, offset, length ) {
  4672. var charArray = new Uint8Array( data, offset, length );
  4673. var text = "";
  4674. for ( var i = 0; i < length; i ++ ) {
  4675. text += String.fromCharCode( charArray[ offset + i ] );
  4676. }
  4677. return text;
  4678. };
  4679. function parseUChar8( data, offset ) {
  4680. var charArray = new Uint8Array( data, offset, 1 );
  4681. return charArray[ 0 ];
  4682. };
  4683. function parseUInt32( data, offset ) {
  4684. var intArray = new Uint32Array( data, offset, 1 );
  4685. return intArray[ 0 ];
  4686. };
  4687. function init_vertices( start ) {
  4688. var nElements = md.nvertices;
  4689. var coordArray = new Float32Array( data, start, nElements * 3 );
  4690. var i, x, y, z;
  4691. for( i = 0; i < nElements; i ++ ) {
  4692. x = coordArray[ i * 3 ];
  4693. y = coordArray[ i * 3 + 1 ];
  4694. z = coordArray[ i * 3 + 2 ];
  4695. vertex( scope, x, y, z );
  4696. }
  4697. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4698. };
  4699. function init_normals( start ) {
  4700. var nElements = md.nnormals;
  4701. if ( nElements ) {
  4702. var normalArray = new Int8Array( data, start, nElements * 3 );
  4703. var i, x, y, z;
  4704. for( i = 0; i < nElements; i ++ ) {
  4705. x = normalArray[ i * 3 ];
  4706. y = normalArray[ i * 3 + 1 ];
  4707. z = normalArray[ i * 3 + 2 ];
  4708. normals.push( x/127, y/127, z/127 );
  4709. }
  4710. }
  4711. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4712. };
  4713. function init_uvs( start ) {
  4714. var nElements = md.nuvs;
  4715. if ( nElements ) {
  4716. var uvArray = new Float32Array( data, start, nElements * 2 );
  4717. var i, u, v;
  4718. for( i = 0; i < nElements; i ++ ) {
  4719. u = uvArray[ i * 2 ];
  4720. v = uvArray[ i * 2 + 1 ];
  4721. uvs.push( u, v );
  4722. }
  4723. }
  4724. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4725. };
  4726. function init_uvs3( nElements, offset ) {
  4727. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4728. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4729. for( i = 0; i < nElements; i ++ ) {
  4730. uva = uvIndexBuffer[ i * 3 ];
  4731. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4732. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4733. u1 = uvs[ uva*2 ];
  4734. v1 = uvs[ uva*2 + 1 ];
  4735. u2 = uvs[ uvb*2 ];
  4736. v2 = uvs[ uvb*2 + 1 ];
  4737. u3 = uvs[ uvc*2 ];
  4738. v3 = uvs[ uvc*2 + 1 ];
  4739. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4740. }
  4741. };
  4742. function init_uvs4( nElements, offset ) {
  4743. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4744. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4745. for( i = 0; i < nElements; i ++ ) {
  4746. uva = uvIndexBuffer[ i * 4 ];
  4747. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4748. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4749. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4750. u1 = uvs[ uva*2 ];
  4751. v1 = uvs[ uva*2 + 1 ];
  4752. u2 = uvs[ uvb*2 ];
  4753. v2 = uvs[ uvb*2 + 1 ];
  4754. u3 = uvs[ uvc*2 ];
  4755. v3 = uvs[ uvc*2 + 1 ];
  4756. u4 = uvs[ uvd*2 ];
  4757. v4 = uvs[ uvd*2 + 1 ];
  4758. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4759. }
  4760. };
  4761. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4762. var i, a, b, c, m;
  4763. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4764. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4765. for( i = 0; i < nElements; i ++ ) {
  4766. a = vertexIndexBuffer[ i * 3 ];
  4767. b = vertexIndexBuffer[ i * 3 + 1 ];
  4768. c = vertexIndexBuffer[ i * 3 + 2 ];
  4769. m = materialIndexBuffer[ i ];
  4770. f3( scope, a, b, c, m );
  4771. }
  4772. };
  4773. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4774. var i, a, b, c, d, m;
  4775. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4776. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4777. for( i = 0; i < nElements; i ++ ) {
  4778. a = vertexIndexBuffer[ i * 4 ];
  4779. b = vertexIndexBuffer[ i * 4 + 1 ];
  4780. c = vertexIndexBuffer[ i * 4 + 2 ];
  4781. d = vertexIndexBuffer[ i * 4 + 3 ];
  4782. m = materialIndexBuffer[ i ];
  4783. f4( scope, a, b, c, d, m );
  4784. }
  4785. };
  4786. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4787. var i, a, b, c, m;
  4788. var na, nb, nc;
  4789. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4790. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4791. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4792. for( i = 0; i < nElements; i ++ ) {
  4793. a = vertexIndexBuffer[ i * 3 ];
  4794. b = vertexIndexBuffer[ i * 3 + 1 ];
  4795. c = vertexIndexBuffer[ i * 3 + 2 ];
  4796. na = normalIndexBuffer[ i * 3 ];
  4797. nb = normalIndexBuffer[ i * 3 + 1 ];
  4798. nc = normalIndexBuffer[ i * 3 + 2 ];
  4799. m = materialIndexBuffer[ i ];
  4800. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4801. }
  4802. };
  4803. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4804. var i, a, b, c, d, m;
  4805. var na, nb, nc, nd;
  4806. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4807. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4808. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4809. for( i = 0; i < nElements; i ++ ) {
  4810. a = vertexIndexBuffer[ i * 4 ];
  4811. b = vertexIndexBuffer[ i * 4 + 1 ];
  4812. c = vertexIndexBuffer[ i * 4 + 2 ];
  4813. d = vertexIndexBuffer[ i * 4 + 3 ];
  4814. na = normalIndexBuffer[ i * 4 ];
  4815. nb = normalIndexBuffer[ i * 4 + 1 ];
  4816. nc = normalIndexBuffer[ i * 4 + 2 ];
  4817. nd = normalIndexBuffer[ i * 4 + 3 ];
  4818. m = materialIndexBuffer[ i ];
  4819. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4820. }
  4821. };
  4822. function init_triangles_flat( start ) {
  4823. var nElements = md.ntri_flat;
  4824. if ( nElements ) {
  4825. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4826. init_faces3_flat( nElements, start, offsetMaterials );
  4827. }
  4828. };
  4829. function init_triangles_flat_uv( start ) {
  4830. var nElements = md.ntri_flat_uv;
  4831. if ( nElements ) {
  4832. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4833. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4834. init_faces3_flat( nElements, start, offsetMaterials );
  4835. init_uvs3( nElements, offsetUvs );
  4836. }
  4837. };
  4838. function init_triangles_smooth( start ) {
  4839. var nElements = md.ntri_smooth;
  4840. if ( nElements ) {
  4841. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4842. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4843. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4844. }
  4845. };
  4846. function init_triangles_smooth_uv( start ) {
  4847. var nElements = md.ntri_smooth_uv;
  4848. if ( nElements ) {
  4849. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4850. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4851. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4852. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4853. init_uvs3( nElements, offsetUvs );
  4854. }
  4855. };
  4856. function init_quads_flat( start ) {
  4857. var nElements = md.nquad_flat;
  4858. if ( nElements ) {
  4859. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4860. init_faces4_flat( nElements, start, offsetMaterials );
  4861. }
  4862. };
  4863. function init_quads_flat_uv( start ) {
  4864. var nElements = md.nquad_flat_uv;
  4865. if ( nElements ) {
  4866. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4867. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4868. init_faces4_flat( nElements, start, offsetMaterials );
  4869. init_uvs4( nElements, offsetUvs );
  4870. }
  4871. };
  4872. function init_quads_smooth( start ) {
  4873. var nElements = md.nquad_smooth;
  4874. if ( nElements ) {
  4875. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4876. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4877. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4878. }
  4879. };
  4880. function init_quads_smooth_uv( start ) {
  4881. var nElements = md.nquad_smooth_uv;
  4882. if ( nElements ) {
  4883. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4884. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4885. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4886. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4887. init_uvs4( nElements, offsetUvs );
  4888. }
  4889. };
  4890. };
  4891. function vertex ( scope, x, y, z ) {
  4892. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4893. };
  4894. function f3 ( scope, a, b, c, mi ) {
  4895. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4896. };
  4897. function f4 ( scope, a, b, c, d, mi ) {
  4898. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4899. };
  4900. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4901. var nax = normals[ na*3 ],
  4902. nay = normals[ na*3 + 1 ],
  4903. naz = normals[ na*3 + 2 ],
  4904. nbx = normals[ nb*3 ],
  4905. nby = normals[ nb*3 + 1 ],
  4906. nbz = normals[ nb*3 + 2 ],
  4907. ncx = normals[ nc*3 ],
  4908. ncy = normals[ nc*3 + 1 ],
  4909. ncz = normals[ nc*3 + 2 ];
  4910. scope.faces.push( new THREE.Face3( a, b, c,
  4911. [new THREE.Vector3( nax, nay, naz ),
  4912. new THREE.Vector3( nbx, nby, nbz ),
  4913. new THREE.Vector3( ncx, ncy, ncz )],
  4914. null,
  4915. mi ) );
  4916. };
  4917. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4918. var nax = normals[ na*3 ],
  4919. nay = normals[ na*3 + 1 ],
  4920. naz = normals[ na*3 + 2 ],
  4921. nbx = normals[ nb*3 ],
  4922. nby = normals[ nb*3 + 1 ],
  4923. nbz = normals[ nb*3 + 2 ],
  4924. ncx = normals[ nc*3 ],
  4925. ncy = normals[ nc*3 + 1 ],
  4926. ncz = normals[ nc*3 + 2 ],
  4927. ndx = normals[ nd*3 ],
  4928. ndy = normals[ nd*3 + 1 ],
  4929. ndz = normals[ nd*3 + 2 ];
  4930. scope.faces.push( new THREE.Face4( a, b, c, d,
  4931. [new THREE.Vector3( nax, nay, naz ),
  4932. new THREE.Vector3( nbx, nby, nbz ),
  4933. new THREE.Vector3( ncx, ncy, ncz ),
  4934. new THREE.Vector3( ndx, ndy, ndz )],
  4935. null,
  4936. mi ) );
  4937. };
  4938. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4939. where.push( [
  4940. new THREE.UV( u1, v1 ),
  4941. new THREE.UV( u2, v2 ),
  4942. new THREE.UV( u3, v3 )
  4943. ] );
  4944. };
  4945. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4946. where.push( [
  4947. new THREE.UV( u1, v1 ),
  4948. new THREE.UV( u2, v2 ),
  4949. new THREE.UV( u3, v3 ),
  4950. new THREE.UV( u4, v4 )
  4951. ] );
  4952. };
  4953. Model.prototype = Object.create( THREE.Geometry.prototype );
  4954. var geometry = new Model( texturePath );
  4955. var materials = this.initMaterials( jsonMaterials, texturePath );
  4956. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  4957. callback( geometry, materials );
  4958. };
  4959. /**
  4960. * @author mrdoob / http://mrdoob.com/
  4961. */
  4962. THREE.ImageLoader = function () {
  4963. THREE.EventTarget.call( this );
  4964. this.crossOrigin = null;
  4965. };
  4966. THREE.ImageLoader.prototype = {
  4967. constructor: THREE.ImageLoader,
  4968. load: function ( url, image ) {
  4969. var scope = this;
  4970. if ( image === undefined ) image = new Image();
  4971. image.addEventListener( 'load', function () {
  4972. scope.dispatchEvent( { type: 'load', content: image } );
  4973. }, false );
  4974. image.addEventListener( 'error', function () {
  4975. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4976. }, false );
  4977. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4978. image.src = url;
  4979. }
  4980. }
  4981. /**
  4982. * @author mrdoob / http://mrdoob.com/
  4983. * @author alteredq / http://alteredqualia.com/
  4984. */
  4985. THREE.JSONLoader = function ( showStatus ) {
  4986. THREE.Loader.call( this, showStatus );
  4987. this.withCredentials = false;
  4988. };
  4989. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4990. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4991. var scope = this;
  4992. // todo: unify load API to for easier SceneLoader use
  4993. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4994. this.onLoadStart();
  4995. this.loadAjaxJSON( this, url, callback, texturePath );
  4996. };
  4997. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4998. var xhr = new XMLHttpRequest();
  4999. var length = 0;
  5000. xhr.withCredentials = this.withCredentials;
  5001. xhr.onreadystatechange = function () {
  5002. if ( xhr.readyState === xhr.DONE ) {
  5003. if ( xhr.status === 200 || xhr.status === 0 ) {
  5004. if ( xhr.responseText ) {
  5005. var json = JSON.parse( xhr.responseText );
  5006. context.createModel( json, callback, texturePath );
  5007. } else {
  5008. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5009. }
  5010. // in context of more complex asset initialization
  5011. // do not block on single failed file
  5012. // maybe should go even one more level up
  5013. context.onLoadComplete();
  5014. } else {
  5015. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5016. }
  5017. } else if ( xhr.readyState === xhr.LOADING ) {
  5018. if ( callbackProgress ) {
  5019. if ( length === 0 ) {
  5020. length = xhr.getResponseHeader( "Content-Length" );
  5021. }
  5022. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5023. }
  5024. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5025. length = xhr.getResponseHeader( "Content-Length" );
  5026. }
  5027. };
  5028. xhr.open( "GET", url, true );
  5029. xhr.send( null );
  5030. };
  5031. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5032. var scope = this,
  5033. geometry = new THREE.Geometry(),
  5034. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5035. parseModel( scale );
  5036. parseSkin();
  5037. parseMorphing( scale );
  5038. geometry.computeCentroids();
  5039. geometry.computeFaceNormals();
  5040. function parseModel( scale ) {
  5041. function isBitSet( value, position ) {
  5042. return value & ( 1 << position );
  5043. }
  5044. var i, j, fi,
  5045. offset, zLength, nVertices,
  5046. colorIndex, normalIndex, uvIndex, materialIndex,
  5047. type,
  5048. isQuad,
  5049. hasMaterial,
  5050. hasFaceUv, hasFaceVertexUv,
  5051. hasFaceNormal, hasFaceVertexNormal,
  5052. hasFaceColor, hasFaceVertexColor,
  5053. vertex, face, color, normal,
  5054. uvLayer, uvs, u, v,
  5055. faces = json.faces,
  5056. vertices = json.vertices,
  5057. normals = json.normals,
  5058. colors = json.colors,
  5059. nUvLayers = 0;
  5060. // disregard empty arrays
  5061. for ( i = 0; i < json.uvs.length; i++ ) {
  5062. if ( json.uvs[ i ].length ) nUvLayers ++;
  5063. }
  5064. for ( i = 0; i < nUvLayers; i++ ) {
  5065. geometry.faceUvs[ i ] = [];
  5066. geometry.faceVertexUvs[ i ] = [];
  5067. }
  5068. offset = 0;
  5069. zLength = vertices.length;
  5070. while ( offset < zLength ) {
  5071. vertex = new THREE.Vector3();
  5072. vertex.x = vertices[ offset ++ ] * scale;
  5073. vertex.y = vertices[ offset ++ ] * scale;
  5074. vertex.z = vertices[ offset ++ ] * scale;
  5075. geometry.vertices.push( vertex );
  5076. }
  5077. offset = 0;
  5078. zLength = faces.length;
  5079. while ( offset < zLength ) {
  5080. type = faces[ offset ++ ];
  5081. isQuad = isBitSet( type, 0 );
  5082. hasMaterial = isBitSet( type, 1 );
  5083. hasFaceUv = isBitSet( type, 2 );
  5084. hasFaceVertexUv = isBitSet( type, 3 );
  5085. hasFaceNormal = isBitSet( type, 4 );
  5086. hasFaceVertexNormal = isBitSet( type, 5 );
  5087. hasFaceColor = isBitSet( type, 6 );
  5088. hasFaceVertexColor = isBitSet( type, 7 );
  5089. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5090. if ( isQuad ) {
  5091. face = new THREE.Face4();
  5092. face.a = faces[ offset ++ ];
  5093. face.b = faces[ offset ++ ];
  5094. face.c = faces[ offset ++ ];
  5095. face.d = faces[ offset ++ ];
  5096. nVertices = 4;
  5097. } else {
  5098. face = new THREE.Face3();
  5099. face.a = faces[ offset ++ ];
  5100. face.b = faces[ offset ++ ];
  5101. face.c = faces[ offset ++ ];
  5102. nVertices = 3;
  5103. }
  5104. if ( hasMaterial ) {
  5105. materialIndex = faces[ offset ++ ];
  5106. face.materialIndex = materialIndex;
  5107. }
  5108. // to get face <=> uv index correspondence
  5109. fi = geometry.faces.length;
  5110. if ( hasFaceUv ) {
  5111. for ( i = 0; i < nUvLayers; i++ ) {
  5112. uvLayer = json.uvs[ i ];
  5113. uvIndex = faces[ offset ++ ];
  5114. u = uvLayer[ uvIndex * 2 ];
  5115. v = uvLayer[ uvIndex * 2 + 1 ];
  5116. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5117. }
  5118. }
  5119. if ( hasFaceVertexUv ) {
  5120. for ( i = 0; i < nUvLayers; i++ ) {
  5121. uvLayer = json.uvs[ i ];
  5122. uvs = [];
  5123. for ( j = 0; j < nVertices; j ++ ) {
  5124. uvIndex = faces[ offset ++ ];
  5125. u = uvLayer[ uvIndex * 2 ];
  5126. v = uvLayer[ uvIndex * 2 + 1 ];
  5127. uvs[ j ] = new THREE.UV( u, v );
  5128. }
  5129. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5130. }
  5131. }
  5132. if ( hasFaceNormal ) {
  5133. normalIndex = faces[ offset ++ ] * 3;
  5134. normal = new THREE.Vector3();
  5135. normal.x = normals[ normalIndex ++ ];
  5136. normal.y = normals[ normalIndex ++ ];
  5137. normal.z = normals[ normalIndex ];
  5138. face.normal = normal;
  5139. }
  5140. if ( hasFaceVertexNormal ) {
  5141. for ( i = 0; i < nVertices; i++ ) {
  5142. normalIndex = faces[ offset ++ ] * 3;
  5143. normal = new THREE.Vector3();
  5144. normal.x = normals[ normalIndex ++ ];
  5145. normal.y = normals[ normalIndex ++ ];
  5146. normal.z = normals[ normalIndex ];
  5147. face.vertexNormals.push( normal );
  5148. }
  5149. }
  5150. if ( hasFaceColor ) {
  5151. colorIndex = faces[ offset ++ ];
  5152. color = new THREE.Color( colors[ colorIndex ] );
  5153. face.color = color;
  5154. }
  5155. if ( hasFaceVertexColor ) {
  5156. for ( i = 0; i < nVertices; i++ ) {
  5157. colorIndex = faces[ offset ++ ];
  5158. color = new THREE.Color( colors[ colorIndex ] );
  5159. face.vertexColors.push( color );
  5160. }
  5161. }
  5162. geometry.faces.push( face );
  5163. }
  5164. };
  5165. function parseSkin() {
  5166. var i, l, x, y, z, w, a, b, c, d;
  5167. if ( json.skinWeights ) {
  5168. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5169. x = json.skinWeights[ i ];
  5170. y = json.skinWeights[ i + 1 ];
  5171. z = 0;
  5172. w = 0;
  5173. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5174. }
  5175. }
  5176. if ( json.skinIndices ) {
  5177. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5178. a = json.skinIndices[ i ];
  5179. b = json.skinIndices[ i + 1 ];
  5180. c = 0;
  5181. d = 0;
  5182. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5183. }
  5184. }
  5185. geometry.bones = json.bones;
  5186. geometry.animation = json.animation;
  5187. };
  5188. function parseMorphing( scale ) {
  5189. if ( json.morphTargets !== undefined ) {
  5190. var i, l, v, vl, dstVertices, srcVertices;
  5191. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5192. geometry.morphTargets[ i ] = {};
  5193. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5194. geometry.morphTargets[ i ].vertices = [];
  5195. dstVertices = geometry.morphTargets[ i ].vertices;
  5196. srcVertices = json.morphTargets [ i ].vertices;
  5197. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5198. var vertex = new THREE.Vector3();
  5199. vertex.x = srcVertices[ v ] * scale;
  5200. vertex.y = srcVertices[ v + 1 ] * scale;
  5201. vertex.z = srcVertices[ v + 2 ] * scale;
  5202. dstVertices.push( vertex );
  5203. }
  5204. }
  5205. }
  5206. if ( json.morphColors !== undefined ) {
  5207. var i, l, c, cl, dstColors, srcColors, color;
  5208. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5209. geometry.morphColors[ i ] = {};
  5210. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5211. geometry.morphColors[ i ].colors = [];
  5212. dstColors = geometry.morphColors[ i ].colors;
  5213. srcColors = json.morphColors [ i ].colors;
  5214. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5215. color = new THREE.Color( 0xffaa00 );
  5216. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5217. dstColors.push( color );
  5218. }
  5219. }
  5220. }
  5221. };
  5222. var materials = this.initMaterials( json.materials, texturePath );
  5223. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5224. callback( geometry, materials );
  5225. };
  5226. /**
  5227. * @author mrdoob / http://mrdoob.com/
  5228. */
  5229. THREE.LoadingMonitor = function () {
  5230. THREE.EventTarget.call( this );
  5231. var scope = this;
  5232. var loaded = 0;
  5233. var total = 0;
  5234. var onLoad = function ( event ) {
  5235. loaded ++;
  5236. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5237. if ( loaded === total ) {
  5238. scope.dispatchEvent( { type: 'load' } );
  5239. }
  5240. };
  5241. this.add = function ( loader ) {
  5242. total ++;
  5243. loader.addEventListener( 'load', onLoad, false );
  5244. };
  5245. };
  5246. /**
  5247. * @author alteredq / http://alteredqualia.com/
  5248. */
  5249. THREE.SceneLoader = function () {
  5250. this.onLoadStart = function () {};
  5251. this.onLoadProgress = function() {};
  5252. this.onLoadComplete = function () {};
  5253. this.callbackSync = function () {};
  5254. this.callbackProgress = function () {};
  5255. this.geometryHandlerMap = {};
  5256. this.hierarchyHandlerMap = {};
  5257. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5258. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5259. };
  5260. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5261. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5262. var scope = this;
  5263. var xhr = new XMLHttpRequest();
  5264. xhr.onreadystatechange = function () {
  5265. if ( xhr.readyState === 4 ) {
  5266. if ( xhr.status === 200 || xhr.status === 0 ) {
  5267. var json = JSON.parse( xhr.responseText );
  5268. scope.parse( json, callbackFinished, url );
  5269. } else {
  5270. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5271. }
  5272. }
  5273. };
  5274. xhr.open( "GET", url, true );
  5275. xhr.send( null );
  5276. };
  5277. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5278. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5279. };
  5280. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5281. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5282. };
  5283. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5284. var scope = this;
  5285. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5286. var geometry, material, camera, fog,
  5287. texture, images, color,
  5288. light, hex, intensity,
  5289. counter_models, counter_textures,
  5290. total_models, total_textures,
  5291. result;
  5292. var target_array = [];
  5293. var data = json;
  5294. // async geometry loaders
  5295. for ( var typeID in this.geometryHandlerMap ) {
  5296. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5297. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5298. }
  5299. // async hierachy loaders
  5300. for ( var typeID in this.hierarchyHandlerMap ) {
  5301. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5302. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5303. }
  5304. counter_models = 0;
  5305. counter_textures = 0;
  5306. result = {
  5307. scene: new THREE.Scene(),
  5308. geometries: {},
  5309. face_materials: {},
  5310. materials: {},
  5311. textures: {},
  5312. objects: {},
  5313. cameras: {},
  5314. lights: {},
  5315. fogs: {},
  5316. empties: {}
  5317. };
  5318. if ( data.transform ) {
  5319. var position = data.transform.position,
  5320. rotation = data.transform.rotation,
  5321. scale = data.transform.scale;
  5322. if ( position )
  5323. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5324. if ( rotation )
  5325. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5326. if ( scale )
  5327. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5328. if ( position || rotation || scale ) {
  5329. result.scene.updateMatrix();
  5330. result.scene.updateMatrixWorld();
  5331. }
  5332. }
  5333. function get_url( source_url, url_type ) {
  5334. if ( url_type == "relativeToHTML" ) {
  5335. return source_url;
  5336. } else {
  5337. return urlBase + "/" + source_url;
  5338. }
  5339. };
  5340. // toplevel loader function, delegates to handle_children
  5341. function handle_objects() {
  5342. handle_children( result.scene, data.objects );
  5343. }
  5344. // handle all the children from the loaded json and attach them to given parent
  5345. function handle_children( parent, children ) {
  5346. var mat, dst, pos, rot, scl, quat;
  5347. for ( var objID in children ) {
  5348. // check by id if child has already been handled,
  5349. // if not, create new object
  5350. if ( result.objects[ objID ] === undefined ) {
  5351. var objJSON = children[ objID ];
  5352. var object = null;
  5353. // meshes
  5354. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) && objJSON.loading === undefined ) {
  5355. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  5356. "position": 1, "rotation": 1, "scale" : 1,
  5357. "visible": 1, "children": 1, "properties": 1,
  5358. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  5359. var loaderParameters = {};
  5360. for ( var parType in objJSON ) {
  5361. if ( ! ( parType in reservedTypes ) ) {
  5362. loaderParameters[ parType ] = objJSON[ parType ];
  5363. }
  5364. }
  5365. material = result.materials[ objJSON.material ];
  5366. objJSON.loading = true;
  5367. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  5368. // OBJLoader
  5369. if ( loader.addEventListener ) {
  5370. loader.addEventListener( 'load', create_callback_hierachy( objID, parent, material, objJSON ) );
  5371. loader.load( get_url( objJSON.url, data.urlBaseType ) );
  5372. } else {
  5373. // ColladaLoader
  5374. if ( loader.options ) {
  5375. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  5376. // UTF8Loader
  5377. } else {
  5378. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  5379. }
  5380. }
  5381. } else if ( objJSON.geometry !== undefined ) {
  5382. geometry = result.geometries[ objJSON.geometry ];
  5383. // geometry already loaded
  5384. if ( geometry ) {
  5385. var needsTangents = false;
  5386. material = result.materials[ objJSON.material ];
  5387. needsTangents = material instanceof THREE.ShaderMaterial;
  5388. pos = objJSON.position;
  5389. rot = objJSON.rotation;
  5390. scl = objJSON.scale;
  5391. mat = objJSON.matrix;
  5392. quat = objJSON.quaternion;
  5393. // turn off quaternions, for the moment
  5394. quat = 0;
  5395. // use materials from the model file
  5396. // if there is no material specified in the object
  5397. if ( ! objJSON.material ) {
  5398. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  5399. }
  5400. // use materials from the model file
  5401. // if there is just empty face material
  5402. // (must create new material as each model has its own face material)
  5403. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  5404. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  5405. }
  5406. if ( material instanceof THREE.MeshFaceMaterial ) {
  5407. for ( var i = 0; i < material.materials.length; i ++ ) {
  5408. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  5409. }
  5410. }
  5411. if ( needsTangents ) {
  5412. geometry.computeTangents();
  5413. }
  5414. if ( objJSON.skin ) {
  5415. object = new THREE.SkinnedMesh( geometry, material );
  5416. } else if ( objJSON.morph ) {
  5417. object = new THREE.MorphAnimMesh( geometry, material );
  5418. if ( objJSON.duration !== undefined ) {
  5419. object.duration = objJSON.duration;
  5420. }
  5421. if ( objJSON.time !== undefined ) {
  5422. object.time = objJSON.time;
  5423. }
  5424. if ( objJSON.mirroredLoop !== undefined ) {
  5425. object.mirroredLoop = objJSON.mirroredLoop;
  5426. }
  5427. if ( material.morphNormals ) {
  5428. geometry.computeMorphNormals();
  5429. }
  5430. } else {
  5431. object = new THREE.Mesh( geometry, material );
  5432. }
  5433. object.name = objID;
  5434. if ( mat ) {
  5435. object.matrixAutoUpdate = false;
  5436. object.matrix.set(
  5437. mat[0], mat[1], mat[2], mat[3],
  5438. mat[4], mat[5], mat[6], mat[7],
  5439. mat[8], mat[9], mat[10], mat[11],
  5440. mat[12], mat[13], mat[14], mat[15]
  5441. );
  5442. } else {
  5443. object.position.set( pos[0], pos[1], pos[2] );
  5444. if ( quat ) {
  5445. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  5446. object.useQuaternion = true;
  5447. } else {
  5448. object.rotation.set( rot[0], rot[1], rot[2] );
  5449. }
  5450. object.scale.set( scl[0], scl[1], scl[2] );
  5451. }
  5452. object.visible = objJSON.visible;
  5453. object.castShadow = objJSON.castShadow;
  5454. object.receiveShadow = objJSON.receiveShadow;
  5455. parent.add( object );
  5456. result.objects[ objID ] = object;
  5457. }
  5458. // lights
  5459. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  5460. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  5461. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  5462. if ( objJSON.type === "DirectionalLight" ) {
  5463. pos = objJSON.direction;
  5464. light = new THREE.DirectionalLight( hex, intensity );
  5465. light.position.set( pos[0], pos[1], pos[2] );
  5466. if ( objJSON.target ) {
  5467. target_array.push( { "object": light, "targetName" : objJSON.target } );
  5468. // kill existing default target
  5469. // otherwise it gets added to scene when parent gets added
  5470. light.target = null;
  5471. }
  5472. } else if ( objJSON.type === "PointLight" ) {
  5473. pos = objJSON.position;
  5474. dst = objJSON.distance;
  5475. light = new THREE.PointLight( hex, intensity, dst );
  5476. light.position.set( pos[0], pos[1], pos[2] );
  5477. } else if ( objJSON.type === "AmbientLight" ) {
  5478. light = new THREE.AmbientLight( hex );
  5479. }
  5480. parent.add( light );
  5481. light.name = objID;
  5482. result.lights[ objID ] = light;
  5483. result.objects[ objID ] = light;
  5484. // cameras
  5485. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  5486. if ( objJSON.type === "PerspectiveCamera" ) {
  5487. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  5488. } else if ( objJSON.type === "OrthographicCamera" ) {
  5489. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  5490. }
  5491. pos = objJSON.position;
  5492. camera.position.set( pos[0], pos[1], pos[2] );
  5493. parent.add( camera );
  5494. camera.name = objID;
  5495. result.cameras[ objID ] = camera;
  5496. result.objects[ objID ] = camera;
  5497. // pure Object3D
  5498. } else {
  5499. pos = objJSON.position;
  5500. rot = objJSON.rotation;
  5501. scl = objJSON.scale;
  5502. quat = objJSON.quaternion;
  5503. // turn off quaternions, for the moment
  5504. quat = 0;
  5505. object = new THREE.Object3D();
  5506. object.name = objID;
  5507. object.position.set( pos[0], pos[1], pos[2] );
  5508. if ( quat ) {
  5509. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  5510. object.useQuaternion = true;
  5511. } else {
  5512. object.rotation.set( rot[0], rot[1], rot[2] );
  5513. }
  5514. object.scale.set( scl[0], scl[1], scl[2] );
  5515. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  5516. parent.add( object );
  5517. result.objects[ objID ] = object;
  5518. result.empties[ objID ] = object;
  5519. }
  5520. if ( object ) {
  5521. if ( objJSON.properties !== undefined ) {
  5522. for ( var key in objJSON.properties ) {
  5523. var value = objJSON.properties[ key ];
  5524. object.properties[ key ] = value;
  5525. }
  5526. }
  5527. if ( objJSON.children !== undefined ) {
  5528. handle_children( object, objJSON.children );
  5529. }
  5530. }
  5531. }
  5532. }
  5533. };
  5534. function handle_mesh( geo, mat, id ) {
  5535. result.geometries[ id ] = geo;
  5536. result.face_materials[ id ] = mat;
  5537. handle_objects();
  5538. };
  5539. function handle_hierarchy( node, id, parent, material, obj ) {
  5540. var p = obj.position;
  5541. var r = obj.rotation;
  5542. var q = obj.quaternion;
  5543. var s = obj.scale;
  5544. node.position.set( p[0], p[1], p[2] );
  5545. if ( q ) {
  5546. node.quaternion.set( q[0], q[1], q[2], q[3] );
  5547. node.useQuaternion = true;
  5548. } else {
  5549. node.rotation.set( r[0], r[1], r[2] );
  5550. }
  5551. node.scale.set( s[0], s[1], s[2] );
  5552. if ( material ) {
  5553. node.traverse( function ( child ) {
  5554. child.material = material;
  5555. } );
  5556. }
  5557. parent.add( node );
  5558. result.objects[ id ] = node;
  5559. handle_objects();
  5560. };
  5561. function create_callback_geometry( id ) {
  5562. return function( geo, mat ) {
  5563. handle_mesh( geo, mat, id );
  5564. counter_models -= 1;
  5565. scope.onLoadComplete();
  5566. async_callback_gate();
  5567. }
  5568. };
  5569. function create_callback_hierachy( id, parent, material, obj ) {
  5570. return function( event ) {
  5571. var result;
  5572. // loaders which use EventTarget
  5573. if ( event.content ) {
  5574. result = event.content;
  5575. // ColladaLoader
  5576. } else if ( event.dae ) {
  5577. result = event.scene;
  5578. // UTF8Loader
  5579. } else {
  5580. result = event;
  5581. }
  5582. handle_hierarchy( result, id, parent, material, obj );
  5583. counter_models -= 1;
  5584. scope.onLoadComplete();
  5585. async_callback_gate();
  5586. }
  5587. };
  5588. function create_callback_embed( id ) {
  5589. return function( geo, mat ) {
  5590. result.geometries[ id ] = geo;
  5591. result.face_materials[ id ] = mat;
  5592. }
  5593. };
  5594. function async_callback_gate() {
  5595. var progress = {
  5596. totalModels : total_models,
  5597. totalTextures : total_textures,
  5598. loadedModels : total_models - counter_models,
  5599. loadedTextures : total_textures - counter_textures
  5600. };
  5601. scope.callbackProgress( progress, result );
  5602. scope.onLoadProgress();
  5603. if ( counter_models === 0 && counter_textures === 0 ) {
  5604. finalize();
  5605. callbackFinished( result );
  5606. }
  5607. };
  5608. function finalize() {
  5609. // take care of targets which could be asynchronously loaded objects
  5610. for ( var i = 0; i < target_array.length; i ++ ) {
  5611. var ta = target_array[ i ];
  5612. var target = result.objects[ ta.targetName ];
  5613. if ( target ) {
  5614. ta.object.target = target;
  5615. } else {
  5616. // if there was error and target of specified name doesn't exist in the scene file
  5617. // create instead dummy target
  5618. // (target must be added to scene explicitly as parent is already added)
  5619. ta.object.target = new THREE.Object3D();
  5620. result.scene.add( ta.object.target );
  5621. }
  5622. ta.object.target.properties.targetInverse = ta.object;
  5623. }
  5624. };
  5625. var callbackTexture = function ( count ) {
  5626. counter_textures -= count;
  5627. async_callback_gate();
  5628. scope.onLoadComplete();
  5629. };
  5630. // must use this instead of just directly calling callbackTexture
  5631. // because of closure in the calling context loop
  5632. var generateTextureCallback = function ( count ) {
  5633. return function() {
  5634. callbackTexture( count );
  5635. };
  5636. };
  5637. // first go synchronous elements
  5638. // fogs
  5639. var fogID, fogJSON;
  5640. for ( fogID in data.fogs ) {
  5641. fogJSON = data.fogs[ fogID ];
  5642. if ( fogJSON.type === "linear" ) {
  5643. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  5644. } else if ( fogJSON.type === "exp2" ) {
  5645. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  5646. }
  5647. color = fogJSON.color;
  5648. fog.color.setRGB( color[0], color[1], color[2] );
  5649. result.fogs[ fogID ] = fog;
  5650. }
  5651. // now come potentially asynchronous elements
  5652. // geometries
  5653. // count how many geometries will be loaded asynchronously
  5654. var geoID, geoJSON;
  5655. for ( geoID in data.geometries ) {
  5656. geoJSON = data.geometries[ geoID ];
  5657. if ( geoJSON.type in this.geometryHandlerMap ) {
  5658. counter_models += 1;
  5659. scope.onLoadStart();
  5660. }
  5661. }
  5662. // count how many hierarchies will be loaded asynchronously
  5663. var objID, objJSON;
  5664. for ( objID in data.objects ) {
  5665. objJSON = data.objects[ objID ];
  5666. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  5667. counter_models += 1;
  5668. scope.onLoadStart();
  5669. }
  5670. }
  5671. total_models = counter_models;
  5672. for ( geoID in data.geometries ) {
  5673. geoJSON = data.geometries[ geoID ];
  5674. if ( geoJSON.type === "cube" ) {
  5675. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  5676. result.geometries[ geoID ] = geometry;
  5677. } else if ( geoJSON.type === "plane" ) {
  5678. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  5679. result.geometries[ geoID ] = geometry;
  5680. } else if ( geoJSON.type === "sphere" ) {
  5681. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  5682. result.geometries[ geoID ] = geometry;
  5683. } else if ( geoJSON.type === "cylinder" ) {
  5684. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  5685. result.geometries[ geoID ] = geometry;
  5686. } else if ( geoJSON.type === "torus" ) {
  5687. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  5688. result.geometries[ geoID ] = geometry;
  5689. } else if ( geoJSON.type === "icosahedron" ) {
  5690. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  5691. result.geometries[ geoID ] = geometry;
  5692. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  5693. var loaderParameters = {};
  5694. for ( var parType in geoJSON ) {
  5695. if ( parType !== "type" && parType !== "url" ) {
  5696. loaderParameters[ parType ] = geoJSON[ parType ];
  5697. }
  5698. }
  5699. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  5700. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  5701. } else if ( geoJSON.type === "embedded" ) {
  5702. var modelJson = data.embeds[ geoJSON.id ],
  5703. texture_path = "";
  5704. // pass metadata along to jsonLoader so it knows the format version
  5705. modelJson.metadata = data.metadata;
  5706. if ( modelJson ) {
  5707. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  5708. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  5709. }
  5710. }
  5711. }
  5712. // textures
  5713. // count how many textures will be loaded asynchronously
  5714. var textureID, textureJSON;
  5715. for ( textureID in data.textures ) {
  5716. textureJSON = data.textures[ textureID ];
  5717. if ( textureJSON.url instanceof Array ) {
  5718. counter_textures += textureJSON.url.length;
  5719. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  5720. scope.onLoadStart();
  5721. }
  5722. } else {
  5723. counter_textures += 1;
  5724. scope.onLoadStart();
  5725. }
  5726. }
  5727. total_textures = counter_textures;
  5728. for ( textureID in data.textures ) {
  5729. textureJSON = data.textures[ textureID ];
  5730. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  5731. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  5732. }
  5733. if ( textureJSON.url instanceof Array ) {
  5734. var count = textureJSON.url.length;
  5735. var url_array = [];
  5736. for( var i = 0; i < count; i ++ ) {
  5737. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  5738. }
  5739. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  5740. if ( isCompressed ) {
  5741. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  5742. } else {
  5743. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  5744. }
  5745. } else {
  5746. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  5747. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  5748. var textureCallback = generateTextureCallback( 1 );
  5749. if ( isCompressed ) {
  5750. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  5751. } else {
  5752. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  5753. }
  5754. if ( THREE[ textureJSON.minFilter ] !== undefined )
  5755. texture.minFilter = THREE[ textureJSON.minFilter ];
  5756. if ( THREE[ textureJSON.magFilter ] !== undefined )
  5757. texture.magFilter = THREE[ textureJSON.magFilter ];
  5758. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  5759. if ( textureJSON.repeat ) {
  5760. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  5761. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5762. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5763. }
  5764. if ( textureJSON.offset ) {
  5765. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  5766. }
  5767. // handle wrap after repeat so that default repeat can be overriden
  5768. if ( textureJSON.wrap ) {
  5769. var wrapMap = {
  5770. "repeat" : THREE.RepeatWrapping,
  5771. "mirror" : THREE.MirroredRepeatWrapping
  5772. }
  5773. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  5774. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  5775. }
  5776. }
  5777. result.textures[ textureID ] = texture;
  5778. }
  5779. // materials
  5780. var matID, matJSON;
  5781. var parID;
  5782. for ( matID in data.materials ) {
  5783. matJSON = data.materials[ matID ];
  5784. for ( parID in matJSON.parameters ) {
  5785. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  5786. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  5787. } else if ( parID === "shading" ) {
  5788. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5789. } else if ( parID === "side" ) {
  5790. if ( matJSON.parameters[ parID ] == "double" ) {
  5791. matJSON.parameters[ parID ] = THREE.DoubleSide;
  5792. } else if ( matJSON.parameters[ parID ] == "back" ) {
  5793. matJSON.parameters[ parID ] = THREE.BackSide;
  5794. } else {
  5795. matJSON.parameters[ parID ] = THREE.FrontSide;
  5796. }
  5797. } else if ( parID === "blending" ) {
  5798. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  5799. } else if ( parID === "combine" ) {
  5800. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5801. } else if ( parID === "vertexColors" ) {
  5802. if ( matJSON.parameters[ parID ] == "face" ) {
  5803. matJSON.parameters[ parID ] = THREE.FaceColors;
  5804. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5805. } else if ( matJSON.parameters[ parID ] ) {
  5806. matJSON.parameters[ parID ] = THREE.VertexColors;
  5807. }
  5808. } else if ( parID === "wrapRGB" ) {
  5809. var v3 = matJSON.parameters[ parID ];
  5810. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  5811. }
  5812. }
  5813. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  5814. matJSON.parameters.transparent = true;
  5815. }
  5816. if ( matJSON.parameters.normalMap ) {
  5817. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5818. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5819. var diffuse = matJSON.parameters.color;
  5820. var specular = matJSON.parameters.specular;
  5821. var ambient = matJSON.parameters.ambient;
  5822. var shininess = matJSON.parameters.shininess;
  5823. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  5824. if ( matJSON.parameters.normalScale ) {
  5825. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  5826. }
  5827. if ( matJSON.parameters.map ) {
  5828. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  5829. uniforms[ "enableDiffuse" ].value = true;
  5830. }
  5831. if ( matJSON.parameters.envMap ) {
  5832. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  5833. uniforms[ "enableReflection" ].value = true;
  5834. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  5835. }
  5836. if ( matJSON.parameters.lightMap ) {
  5837. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  5838. uniforms[ "enableAO" ].value = true;
  5839. }
  5840. if ( matJSON.parameters.specularMap ) {
  5841. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  5842. uniforms[ "enableSpecular" ].value = true;
  5843. }
  5844. if ( matJSON.parameters.displacementMap ) {
  5845. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  5846. uniforms[ "enableDisplacement" ].value = true;
  5847. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  5848. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  5849. }
  5850. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5851. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5852. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5853. uniforms[ "uShininess" ].value = shininess;
  5854. if ( matJSON.parameters.opacity ) {
  5855. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  5856. }
  5857. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5858. material = new THREE.ShaderMaterial( parameters );
  5859. } else {
  5860. material = new THREE[ matJSON.type ]( matJSON.parameters );
  5861. }
  5862. result.materials[ matID ] = material;
  5863. }
  5864. // second pass through all materials to initialize MeshFaceMaterials
  5865. // that could be referring to other materials out of order
  5866. for ( matID in data.materials ) {
  5867. matJSON = data.materials[ matID ];
  5868. if ( matJSON.parameters.materials ) {
  5869. var materialArray = [];
  5870. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  5871. var label = matJSON.parameters.materials[ i ];
  5872. materialArray.push( result.materials[ label ] );
  5873. }
  5874. result.materials[ matID ].materials = materialArray;
  5875. }
  5876. }
  5877. // objects ( synchronous init of procedural primitives )
  5878. handle_objects();
  5879. // defaults
  5880. if ( result.cameras && data.defaults.camera ) {
  5881. result.currentCamera = result.cameras[ data.defaults.camera ];
  5882. }
  5883. if ( result.fogs && data.defaults.fog ) {
  5884. result.scene.fog = result.fogs[ data.defaults.fog ];
  5885. }
  5886. color = data.defaults.bgcolor;
  5887. result.bgColor = new THREE.Color();
  5888. result.bgColor.setRGB( color[0], color[1], color[2] );
  5889. result.bgColorAlpha = data.defaults.bgalpha;
  5890. // synchronous callback
  5891. scope.callbackSync( result );
  5892. // just in case there are no async elements
  5893. async_callback_gate();
  5894. };
  5895. /**
  5896. * @author mrdoob / http://mrdoob.com/
  5897. */
  5898. THREE.TextureLoader = function () {
  5899. THREE.EventTarget.call( this );
  5900. this.crossOrigin = null;
  5901. };
  5902. THREE.TextureLoader.prototype = {
  5903. constructor: THREE.TextureLoader,
  5904. load: function ( url ) {
  5905. var scope = this;
  5906. var image = new Image();
  5907. image.addEventListener( 'load', function () {
  5908. var texture = new THREE.Texture( image );
  5909. texture.needsUpdate = true;
  5910. scope.dispatchEvent( { type: 'load', content: texture } );
  5911. }, false );
  5912. image.addEventListener( 'error', function () {
  5913. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5914. }, false );
  5915. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5916. image.src = url;
  5917. }
  5918. }
  5919. /**
  5920. * @author mrdoob / http://mrdoob.com/
  5921. * @author alteredq / http://alteredqualia.com/
  5922. */
  5923. THREE.Material = function () {
  5924. THREE.MaterialLibrary.push( this );
  5925. this.id = THREE.MaterialIdCount ++;
  5926. this.name = '';
  5927. this.side = THREE.FrontSide;
  5928. this.opacity = 1;
  5929. this.transparent = false;
  5930. this.blending = THREE.NormalBlending;
  5931. this.blendSrc = THREE.SrcAlphaFactor;
  5932. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5933. this.blendEquation = THREE.AddEquation;
  5934. this.depthTest = true;
  5935. this.depthWrite = true;
  5936. this.polygonOffset = false;
  5937. this.polygonOffsetFactor = 0;
  5938. this.polygonOffsetUnits = 0;
  5939. this.alphaTest = 0;
  5940. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5941. this.visible = true;
  5942. this.needsUpdate = true;
  5943. };
  5944. THREE.Material.prototype.setValues = function ( values ) {
  5945. if ( values === undefined ) return;
  5946. for ( var key in values ) {
  5947. var newValue = values[ key ];
  5948. if ( newValue === undefined ) {
  5949. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5950. continue;
  5951. }
  5952. if ( key in this ) {
  5953. var currentValue = this[ key ];
  5954. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5955. currentValue.copy( newValue );
  5956. } else if ( currentValue instanceof THREE.Color ) {
  5957. currentValue.set( newValue );
  5958. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5959. currentValue.copy( newValue );
  5960. } else {
  5961. this[ key ] = newValue;
  5962. }
  5963. }
  5964. }
  5965. };
  5966. THREE.Material.prototype.clone = function ( material ) {
  5967. if ( material === undefined ) material = new THREE.Material();
  5968. material.name = this.name;
  5969. material.side = this.side;
  5970. material.opacity = this.opacity;
  5971. material.transparent = this.transparent;
  5972. material.blending = this.blending;
  5973. material.blendSrc = this.blendSrc;
  5974. material.blendDst = this.blendDst;
  5975. material.blendEquation = this.blendEquation;
  5976. material.depthTest = this.depthTest;
  5977. material.depthWrite = this.depthWrite;
  5978. material.polygonOffset = this.polygonOffset;
  5979. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5980. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5981. material.alphaTest = this.alphaTest;
  5982. material.overdraw = this.overdraw;
  5983. material.visible = this.visible;
  5984. return material;
  5985. };
  5986. THREE.Material.prototype.deallocate = function () {
  5987. var index = THREE.MaterialLibrary.indexOf( this );
  5988. if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
  5989. };
  5990. THREE.MaterialIdCount = 0;
  5991. THREE.MaterialLibrary = [];
  5992. /**
  5993. * @author mrdoob / http://mrdoob.com/
  5994. * @author alteredq / http://alteredqualia.com/
  5995. *
  5996. * parameters = {
  5997. * color: <hex>,
  5998. * opacity: <float>,
  5999. *
  6000. * blending: THREE.NormalBlending,
  6001. * depthTest: <bool>,
  6002. * depthWrite: <bool>,
  6003. *
  6004. * linewidth: <float>,
  6005. * linecap: "round",
  6006. * linejoin: "round",
  6007. *
  6008. * vertexColors: <bool>
  6009. *
  6010. * fog: <bool>
  6011. * }
  6012. */
  6013. THREE.LineBasicMaterial = function ( parameters ) {
  6014. THREE.Material.call( this );
  6015. this.color = new THREE.Color( 0xffffff );
  6016. this.linewidth = 1;
  6017. this.linecap = 'round';
  6018. this.linejoin = 'round';
  6019. this.vertexColors = false;
  6020. this.fog = true;
  6021. this.setValues( parameters );
  6022. };
  6023. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6024. THREE.LineBasicMaterial.prototype.clone = function () {
  6025. var material = new THREE.LineBasicMaterial();
  6026. THREE.Material.prototype.clone.call( this, material );
  6027. material.color.copy( this.color );
  6028. material.linewidth = this.linewidth;
  6029. material.linecap = this.linecap;
  6030. material.linejoin = this.linejoin;
  6031. material.vertexColors = this.vertexColors;
  6032. material.fog = this.fog;
  6033. return material;
  6034. };
  6035. /**
  6036. * @author alteredq / http://alteredqualia.com/
  6037. *
  6038. * parameters = {
  6039. * color: <hex>,
  6040. * opacity: <float>,
  6041. *
  6042. * blending: THREE.NormalBlending,
  6043. * depthTest: <bool>,
  6044. * depthWrite: <bool>,
  6045. *
  6046. * linewidth: <float>,
  6047. *
  6048. * scale: <float>,
  6049. * dashSize: <float>,
  6050. * gapSize: <float>,
  6051. *
  6052. * vertexColors: <bool>
  6053. *
  6054. * fog: <bool>
  6055. * }
  6056. */
  6057. THREE.LineDashedMaterial = function ( parameters ) {
  6058. THREE.Material.call( this );
  6059. this.color = new THREE.Color( 0xffffff );
  6060. this.linewidth = 1;
  6061. this.scale = 1;
  6062. this.dashSize = 3;
  6063. this.gapSize = 1;
  6064. this.vertexColors = false;
  6065. this.fog = true;
  6066. this.setValues( parameters );
  6067. };
  6068. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6069. THREE.LineDashedMaterial.prototype.clone = function () {
  6070. var material = new THREE.LineDashedMaterial();
  6071. THREE.Material.prototype.clone.call( this, material );
  6072. material.color.copy( this.color );
  6073. material.linewidth = this.linewidth;
  6074. material.scale = this.scale;
  6075. material.dashSize = this.dashSize;
  6076. material.gapSize = this.gapSize;
  6077. material.vertexColors = this.vertexColors;
  6078. material.fog = this.fog;
  6079. return material;
  6080. };
  6081. /**
  6082. * @author mrdoob / http://mrdoob.com/
  6083. * @author alteredq / http://alteredqualia.com/
  6084. *
  6085. * parameters = {
  6086. * color: <hex>,
  6087. * opacity: <float>,
  6088. * map: new THREE.Texture( <Image> ),
  6089. *
  6090. * lightMap: new THREE.Texture( <Image> ),
  6091. *
  6092. * specularMap: new THREE.Texture( <Image> ),
  6093. *
  6094. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6095. * combine: THREE.Multiply,
  6096. * reflectivity: <float>,
  6097. * refractionRatio: <float>,
  6098. *
  6099. * shading: THREE.SmoothShading,
  6100. * blending: THREE.NormalBlending,
  6101. * depthTest: <bool>,
  6102. * depthWrite: <bool>,
  6103. *
  6104. * wireframe: <boolean>,
  6105. * wireframeLinewidth: <float>,
  6106. *
  6107. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6108. *
  6109. * skinning: <bool>,
  6110. * morphTargets: <bool>,
  6111. *
  6112. * fog: <bool>
  6113. * }
  6114. */
  6115. THREE.MeshBasicMaterial = function ( parameters ) {
  6116. THREE.Material.call( this );
  6117. this.color = new THREE.Color( 0xffffff ); // emissive
  6118. this.map = null;
  6119. this.lightMap = null;
  6120. this.specularMap = null;
  6121. this.envMap = null;
  6122. this.combine = THREE.MultiplyOperation;
  6123. this.reflectivity = 1;
  6124. this.refractionRatio = 0.98;
  6125. this.fog = true;
  6126. this.shading = THREE.SmoothShading;
  6127. this.wireframe = false;
  6128. this.wireframeLinewidth = 1;
  6129. this.wireframeLinecap = 'round';
  6130. this.wireframeLinejoin = 'round';
  6131. this.vertexColors = THREE.NoColors;
  6132. this.skinning = false;
  6133. this.morphTargets = false;
  6134. this.setValues( parameters );
  6135. };
  6136. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6137. THREE.MeshBasicMaterial.prototype.clone = function () {
  6138. var material = new THREE.MeshBasicMaterial();
  6139. THREE.Material.prototype.clone.call( this, material );
  6140. material.color.copy( this.color );
  6141. material.map = this.map;
  6142. material.lightMap = this.lightMap;
  6143. material.specularMap = this.specularMap;
  6144. material.envMap = this.envMap;
  6145. material.combine = this.combine;
  6146. material.reflectivity = this.reflectivity;
  6147. material.refractionRatio = this.refractionRatio;
  6148. material.fog = this.fog;
  6149. material.shading = this.shading;
  6150. material.wireframe = this.wireframe;
  6151. material.wireframeLinewidth = this.wireframeLinewidth;
  6152. material.wireframeLinecap = this.wireframeLinecap;
  6153. material.wireframeLinejoin = this.wireframeLinejoin;
  6154. material.vertexColors = this.vertexColors;
  6155. material.skinning = this.skinning;
  6156. material.morphTargets = this.morphTargets;
  6157. return material;
  6158. };
  6159. /**
  6160. * @author mrdoob / http://mrdoob.com/
  6161. * @author alteredq / http://alteredqualia.com/
  6162. *
  6163. * parameters = {
  6164. * color: <hex>,
  6165. * ambient: <hex>,
  6166. * emissive: <hex>,
  6167. * opacity: <float>,
  6168. *
  6169. * map: new THREE.Texture( <Image> ),
  6170. *
  6171. * lightMap: new THREE.Texture( <Image> ),
  6172. *
  6173. * specularMap: new THREE.Texture( <Image> ),
  6174. *
  6175. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6176. * combine: THREE.Multiply,
  6177. * reflectivity: <float>,
  6178. * refractionRatio: <float>,
  6179. *
  6180. * shading: THREE.SmoothShading,
  6181. * blending: THREE.NormalBlending,
  6182. * depthTest: <bool>,
  6183. * depthWrite: <bool>,
  6184. *
  6185. * wireframe: <boolean>,
  6186. * wireframeLinewidth: <float>,
  6187. *
  6188. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6189. *
  6190. * skinning: <bool>,
  6191. * morphTargets: <bool>,
  6192. * morphNormals: <bool>,
  6193. *
  6194. * fog: <bool>
  6195. * }
  6196. */
  6197. THREE.MeshLambertMaterial = function ( parameters ) {
  6198. THREE.Material.call( this );
  6199. this.color = new THREE.Color( 0xffffff ); // diffuse
  6200. this.ambient = new THREE.Color( 0xffffff );
  6201. this.emissive = new THREE.Color( 0x000000 );
  6202. this.wrapAround = false;
  6203. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6204. this.map = null;
  6205. this.lightMap = null;
  6206. this.specularMap = null;
  6207. this.envMap = null;
  6208. this.combine = THREE.MultiplyOperation;
  6209. this.reflectivity = 1;
  6210. this.refractionRatio = 0.98;
  6211. this.fog = true;
  6212. this.shading = THREE.SmoothShading;
  6213. this.wireframe = false;
  6214. this.wireframeLinewidth = 1;
  6215. this.wireframeLinecap = 'round';
  6216. this.wireframeLinejoin = 'round';
  6217. this.vertexColors = THREE.NoColors;
  6218. this.skinning = false;
  6219. this.morphTargets = false;
  6220. this.morphNormals = false;
  6221. this.setValues( parameters );
  6222. };
  6223. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6224. THREE.MeshLambertMaterial.prototype.clone = function () {
  6225. var material = new THREE.MeshLambertMaterial();
  6226. THREE.Material.prototype.clone.call( this, material );
  6227. material.color.copy( this.color );
  6228. material.ambient.copy( this.ambient );
  6229. material.emissive.copy( this.emissive );
  6230. material.wrapAround = this.wrapAround;
  6231. material.wrapRGB.copy( this.wrapRGB );
  6232. material.map = this.map;
  6233. material.lightMap = this.lightMap;
  6234. material.specularMap = this.specularMap;
  6235. material.envMap = this.envMap;
  6236. material.combine = this.combine;
  6237. material.reflectivity = this.reflectivity;
  6238. material.refractionRatio = this.refractionRatio;
  6239. material.fog = this.fog;
  6240. material.shading = this.shading;
  6241. material.wireframe = this.wireframe;
  6242. material.wireframeLinewidth = this.wireframeLinewidth;
  6243. material.wireframeLinecap = this.wireframeLinecap;
  6244. material.wireframeLinejoin = this.wireframeLinejoin;
  6245. material.vertexColors = this.vertexColors;
  6246. material.skinning = this.skinning;
  6247. material.morphTargets = this.morphTargets;
  6248. material.morphNormals = this.morphNormals;
  6249. return material;
  6250. };
  6251. /**
  6252. * @author mrdoob / http://mrdoob.com/
  6253. * @author alteredq / http://alteredqualia.com/
  6254. *
  6255. * parameters = {
  6256. * color: <hex>,
  6257. * ambient: <hex>,
  6258. * emissive: <hex>,
  6259. * specular: <hex>,
  6260. * shininess: <float>,
  6261. * opacity: <float>,
  6262. *
  6263. * map: new THREE.Texture( <Image> ),
  6264. *
  6265. * lightMap: new THREE.Texture( <Image> ),
  6266. *
  6267. * bumpMap: new THREE.Texture( <Image> ),
  6268. * bumpScale: <float>,
  6269. *
  6270. * normalMap: new THREE.Texture( <Image> ),
  6271. * normalScale: <Vector2>,
  6272. *
  6273. * specularMap: new THREE.Texture( <Image> ),
  6274. *
  6275. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6276. * combine: THREE.Multiply,
  6277. * reflectivity: <float>,
  6278. * refractionRatio: <float>,
  6279. *
  6280. * shading: THREE.SmoothShading,
  6281. * blending: THREE.NormalBlending,
  6282. * depthTest: <bool>,
  6283. * depthWrite: <bool>,
  6284. *
  6285. * wireframe: <boolean>,
  6286. * wireframeLinewidth: <float>,
  6287. *
  6288. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6289. *
  6290. * skinning: <bool>,
  6291. * morphTargets: <bool>,
  6292. * morphNormals: <bool>,
  6293. *
  6294. * fog: <bool>
  6295. * }
  6296. */
  6297. THREE.MeshPhongMaterial = function ( parameters ) {
  6298. THREE.Material.call( this );
  6299. this.color = new THREE.Color( 0xffffff ); // diffuse
  6300. this.ambient = new THREE.Color( 0xffffff );
  6301. this.emissive = new THREE.Color( 0x000000 );
  6302. this.specular = new THREE.Color( 0x111111 );
  6303. this.shininess = 30;
  6304. this.metal = false;
  6305. this.perPixel = true;
  6306. this.wrapAround = false;
  6307. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6308. this.map = null;
  6309. this.lightMap = null;
  6310. this.bumpMap = null;
  6311. this.bumpScale = 1;
  6312. this.normalMap = null;
  6313. this.normalScale = new THREE.Vector2( 1, 1 );
  6314. this.specularMap = null;
  6315. this.envMap = null;
  6316. this.combine = THREE.MultiplyOperation;
  6317. this.reflectivity = 1;
  6318. this.refractionRatio = 0.98;
  6319. this.fog = true;
  6320. this.shading = THREE.SmoothShading;
  6321. this.wireframe = false;
  6322. this.wireframeLinewidth = 1;
  6323. this.wireframeLinecap = 'round';
  6324. this.wireframeLinejoin = 'round';
  6325. this.vertexColors = THREE.NoColors;
  6326. this.skinning = false;
  6327. this.morphTargets = false;
  6328. this.morphNormals = false;
  6329. this.setValues( parameters );
  6330. };
  6331. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6332. THREE.MeshPhongMaterial.prototype.clone = function () {
  6333. var material = new THREE.MeshPhongMaterial();
  6334. THREE.Material.prototype.clone.call( this, material );
  6335. material.color.copy( this.color );
  6336. material.ambient.copy( this.ambient );
  6337. material.emissive.copy( this.emissive );
  6338. material.specular.copy( this.specular );
  6339. material.shininess = this.shininess;
  6340. material.metal = this.metal;
  6341. material.perPixel = this.perPixel;
  6342. material.wrapAround = this.wrapAround;
  6343. material.wrapRGB.copy( this.wrapRGB );
  6344. material.map = this.map;
  6345. material.lightMap = this.lightMap;
  6346. material.bumpMap = this.bumpMap;
  6347. material.bumpScale = this.bumpScale;
  6348. material.normalMap = this.normalMap;
  6349. material.normalScale.copy( this.normalScale );
  6350. material.specularMap = this.specularMap;
  6351. material.envMap = this.envMap;
  6352. material.combine = this.combine;
  6353. material.reflectivity = this.reflectivity;
  6354. material.refractionRatio = this.refractionRatio;
  6355. material.fog = this.fog;
  6356. material.shading = this.shading;
  6357. material.wireframe = this.wireframe;
  6358. material.wireframeLinewidth = this.wireframeLinewidth;
  6359. material.wireframeLinecap = this.wireframeLinecap;
  6360. material.wireframeLinejoin = this.wireframeLinejoin;
  6361. material.vertexColors = this.vertexColors;
  6362. material.skinning = this.skinning;
  6363. material.morphTargets = this.morphTargets;
  6364. material.morphNormals = this.morphNormals;
  6365. return material;
  6366. };
  6367. /**
  6368. * @author mrdoob / http://mrdoob.com/
  6369. * @author alteredq / http://alteredqualia.com/
  6370. *
  6371. * parameters = {
  6372. * opacity: <float>,
  6373. *
  6374. * blending: THREE.NormalBlending,
  6375. * depthTest: <bool>,
  6376. * depthWrite: <bool>,
  6377. *
  6378. * wireframe: <boolean>,
  6379. * wireframeLinewidth: <float>
  6380. * }
  6381. */
  6382. THREE.MeshDepthMaterial = function ( parameters ) {
  6383. THREE.Material.call( this );
  6384. this.wireframe = false;
  6385. this.wireframeLinewidth = 1;
  6386. this.setValues( parameters );
  6387. };
  6388. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6389. THREE.MeshDepthMaterial.prototype.clone = function () {
  6390. var material = new THREE.LineBasicMaterial();
  6391. THREE.Material.prototype.clone.call( this, material );
  6392. material.wireframe = this.wireframe;
  6393. material.wireframeLinewidth = this.wireframeLinewidth;
  6394. return material;
  6395. };
  6396. /**
  6397. * @author mrdoob / http://mrdoob.com/
  6398. *
  6399. * parameters = {
  6400. * opacity: <float>,
  6401. *
  6402. * shading: THREE.FlatShading,
  6403. * blending: THREE.NormalBlending,
  6404. * depthTest: <bool>,
  6405. * depthWrite: <bool>,
  6406. *
  6407. * wireframe: <boolean>,
  6408. * wireframeLinewidth: <float>
  6409. * }
  6410. */
  6411. THREE.MeshNormalMaterial = function ( parameters ) {
  6412. THREE.Material.call( this, parameters );
  6413. this.shading = THREE.FlatShading;
  6414. this.wireframe = false;
  6415. this.wireframeLinewidth = 1;
  6416. this.setValues( parameters );
  6417. };
  6418. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6419. THREE.MeshNormalMaterial.prototype.clone = function () {
  6420. var material = new THREE.MeshNormalMaterial();
  6421. THREE.Material.prototype.clone.call( this, material );
  6422. material.shading = this.shading;
  6423. material.wireframe = this.wireframe;
  6424. material.wireframeLinewidth = this.wireframeLinewidth;
  6425. return material;
  6426. };
  6427. /**
  6428. * @author mrdoob / http://mrdoob.com/
  6429. */
  6430. THREE.MeshFaceMaterial = function ( materials ) {
  6431. this.materials = materials instanceof Array ? materials : [];
  6432. };
  6433. THREE.MeshFaceMaterial.prototype.clone = function () {
  6434. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  6435. };
  6436. /**
  6437. * @author mrdoob / http://mrdoob.com/
  6438. * @author alteredq / http://alteredqualia.com/
  6439. *
  6440. * parameters = {
  6441. * color: <hex>,
  6442. * opacity: <float>,
  6443. * map: new THREE.Texture( <Image> ),
  6444. *
  6445. * size: <float>,
  6446. *
  6447. * blending: THREE.NormalBlending,
  6448. * depthTest: <bool>,
  6449. * depthWrite: <bool>,
  6450. *
  6451. * vertexColors: <bool>,
  6452. *
  6453. * fog: <bool>
  6454. * }
  6455. */
  6456. THREE.ParticleBasicMaterial = function ( parameters ) {
  6457. THREE.Material.call( this );
  6458. this.color = new THREE.Color( 0xffffff );
  6459. this.map = null;
  6460. this.size = 1;
  6461. this.sizeAttenuation = true;
  6462. this.vertexColors = false;
  6463. this.fog = true;
  6464. this.setValues( parameters );
  6465. };
  6466. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6467. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6468. var material = new THREE.ParticleBasicMaterial();
  6469. THREE.Material.prototype.clone.call( this, material );
  6470. material.color.copy( this.color );
  6471. material.map = this.map;
  6472. material.size = this.size;
  6473. material.sizeAttenuation = this.sizeAttenuation;
  6474. material.vertexColors = this.vertexColors;
  6475. material.fog = this.fog;
  6476. return material;
  6477. };
  6478. /**
  6479. * @author mrdoob / http://mrdoob.com/
  6480. *
  6481. * parameters = {
  6482. * color: <hex>,
  6483. * program: <function>,
  6484. * opacity: <float>,
  6485. * blending: THREE.NormalBlending
  6486. * }
  6487. */
  6488. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6489. THREE.Material.call( this );
  6490. this.color = new THREE.Color( 0xffffff );
  6491. this.program = function ( context, color ) {};
  6492. this.setValues( parameters );
  6493. };
  6494. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6495. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6496. var material = new THREE.ParticleCanvasMaterial();
  6497. THREE.Material.prototype.clone.call( this, material );
  6498. material.color.copy( this.color );
  6499. material.program = this.program;
  6500. return material;
  6501. };
  6502. /**
  6503. * @author mrdoob / http://mrdoob.com/
  6504. */
  6505. THREE.ParticleDOMMaterial = function ( element ) {
  6506. this.element = element;
  6507. };
  6508. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6509. return new THREE.ParticleDOMMaterial( this.element );
  6510. };
  6511. /**
  6512. * @author alteredq / http://alteredqualia.com/
  6513. *
  6514. * parameters = {
  6515. * fragmentShader: <string>,
  6516. * vertexShader: <string>,
  6517. *
  6518. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6519. *
  6520. * defines: { "label" : "value" },
  6521. *
  6522. * shading: THREE.SmoothShading,
  6523. * blending: THREE.NormalBlending,
  6524. * depthTest: <bool>,
  6525. * depthWrite: <bool>,
  6526. *
  6527. * wireframe: <boolean>,
  6528. * wireframeLinewidth: <float>,
  6529. *
  6530. * lights: <bool>,
  6531. *
  6532. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6533. *
  6534. * skinning: <bool>,
  6535. * morphTargets: <bool>,
  6536. * morphNormals: <bool>,
  6537. *
  6538. * fog: <bool>
  6539. * }
  6540. */
  6541. THREE.ShaderMaterial = function ( parameters ) {
  6542. THREE.Material.call( this );
  6543. this.fragmentShader = "void main() {}";
  6544. this.vertexShader = "void main() {}";
  6545. this.uniforms = {};
  6546. this.defines = {};
  6547. this.attributes = null;
  6548. this.shading = THREE.SmoothShading;
  6549. this.wireframe = false;
  6550. this.wireframeLinewidth = 1;
  6551. this.fog = false; // set to use scene fog
  6552. this.lights = false; // set to use scene lights
  6553. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6554. this.skinning = false; // set to use skinning attribute streams
  6555. this.morphTargets = false; // set to use morph targets
  6556. this.morphNormals = false; // set to use morph normals
  6557. this.setValues( parameters );
  6558. };
  6559. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6560. THREE.ShaderMaterial.prototype.clone = function () {
  6561. var material = new THREE.ShaderMaterial();
  6562. THREE.Material.prototype.clone.call( this, material );
  6563. material.fragmentShader = this.fragmentShader;
  6564. material.vertexShader = this.vertexShader;
  6565. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  6566. material.attributes = this.attributes;
  6567. material.defines = this.defines;
  6568. material.shading = this.shading;
  6569. material.wireframe = this.wireframe;
  6570. material.wireframeLinewidth = this.wireframeLinewidth;
  6571. material.fog = this.fog;
  6572. material.lights = this.lights;
  6573. material.vertexColors = this.vertexColors;
  6574. material.skinning = this.skinning;
  6575. material.morphTargets = this.morphTargets;
  6576. material.morphNormals = this.morphNormals;
  6577. return material;
  6578. };
  6579. /**
  6580. * @author alteredq / http://alteredqualia.com/
  6581. *
  6582. * parameters = {
  6583. * color: <hex>,
  6584. * opacity: <float>,
  6585. * map: new THREE.Texture( <Image> ),
  6586. *
  6587. * blending: THREE.NormalBlending,
  6588. * depthTest: <bool>,
  6589. * depthWrite: <bool>,
  6590. *
  6591. * useScreenCoordinates: <bool>,
  6592. * sizeAttenuation: <bool>,
  6593. * scaleByViewport: <bool>,
  6594. * alignment: THREE.SpriteAlignment.center,
  6595. *
  6596. * uvOffset: new THREE.Vector2(),
  6597. * uvScale: new THREE.Vector2(),
  6598. *
  6599. * fog: <bool>
  6600. * }
  6601. */
  6602. THREE.SpriteMaterial = function ( parameters ) {
  6603. THREE.Material.call( this );
  6604. // defaults
  6605. this.color = new THREE.Color( 0xffffff );
  6606. this.map = new THREE.Texture();
  6607. this.useScreenCoordinates = true;
  6608. this.depthTest = !this.useScreenCoordinates;
  6609. this.sizeAttenuation = !this.useScreenCoordinates;
  6610. this.scaleByViewport = !this.sizeAttenuation;
  6611. this.alignment = THREE.SpriteAlignment.center.clone();
  6612. this.fog = false;
  6613. this.uvOffset = new THREE.Vector2( 0, 0 );
  6614. this.uvScale = new THREE.Vector2( 1, 1 );
  6615. // set parameters
  6616. this.setValues( parameters );
  6617. // override coupled defaults if not specified explicitly by parameters
  6618. parameters = parameters || {};
  6619. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  6620. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  6621. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  6622. };
  6623. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  6624. THREE.SpriteMaterial.prototype.clone = function () {
  6625. var material = new THREE.SpriteMaterial();
  6626. THREE.Material.prototype.clone.call( this, material );
  6627. material.color.copy( this.color );
  6628. material.map = this.map;
  6629. material.useScreenCoordinates = this.useScreenCoordinates;
  6630. material.sizeAttenuation = this.sizeAttenuation;
  6631. material.scaleByViewport = this.scaleByViewport;
  6632. material.alignment.copy( this.alignment );
  6633. material.uvOffset.copy( this.uvOffset );
  6634. material.uvScale.copy( this.uvScale );
  6635. material.fog = this.fog;
  6636. return material;
  6637. };
  6638. // Alignment enums
  6639. THREE.SpriteAlignment = {};
  6640. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  6641. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  6642. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  6643. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  6644. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  6645. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  6646. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  6647. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  6648. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  6649. /**
  6650. * @author mrdoob / http://mrdoob.com/
  6651. * @author alteredq / http://alteredqualia.com/
  6652. * @author szimek / https://github.com/szimek/
  6653. */
  6654. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6655. THREE.TextureLibrary.push( this );
  6656. this.id = THREE.TextureIdCount ++;
  6657. this.name = '';
  6658. this.image = image;
  6659. this.mipmaps = [];
  6660. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6661. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6662. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6663. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6664. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6665. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6666. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6667. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6668. this.offset = new THREE.Vector2( 0, 0 );
  6669. this.repeat = new THREE.Vector2( 1, 1 );
  6670. this.generateMipmaps = true;
  6671. this.premultiplyAlpha = false;
  6672. this.flipY = true;
  6673. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  6674. this.needsUpdate = false;
  6675. this.onUpdate = null;
  6676. };
  6677. THREE.Texture.prototype = {
  6678. constructor: THREE.Texture,
  6679. clone: function ( texture ) {
  6680. if ( texture === undefined ) texture = new THREE.Texture();
  6681. texture.image = this.image;
  6682. texture.mipmaps = this.mipmaps.slice(0);
  6683. texture.mapping = this.mapping;
  6684. texture.wrapS = this.wrapS;
  6685. texture.wrapT = this.wrapT;
  6686. texture.magFilter = this.magFilter;
  6687. texture.minFilter = this.minFilter;
  6688. texture.anisotropy = this.anisotropy;
  6689. texture.format = this.format;
  6690. texture.type = this.type;
  6691. texture.offset.copy( this.offset );
  6692. texture.repeat.copy( this.repeat );
  6693. texture.generateMipmaps = this.generateMipmaps;
  6694. texture.premultiplyAlpha = this.premultiplyAlpha;
  6695. texture.flipY = this.flipY;
  6696. texture.unpackAlignment = this.unpackAlignment;
  6697. return texture;
  6698. },
  6699. deallocate: function () {
  6700. var index = THREE.TextureLibrary.indexOf( this );
  6701. if ( index !== -1 ) THREE.TextureLibrary.splice( index, 1 );
  6702. }
  6703. };
  6704. THREE.TextureIdCount = 0;
  6705. THREE.TextureLibrary = [];
  6706. /**
  6707. * @author alteredq / http://alteredqualia.com/
  6708. */
  6709. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  6710. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  6711. this.image = { width: width, height: height };
  6712. this.mipmaps = mipmaps;
  6713. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  6714. };
  6715. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  6716. THREE.CompressedTexture.prototype.clone = function () {
  6717. var texture = new THREE.CompressedTexture();
  6718. THREE.Texture.prototype.clone.call( this, texture );
  6719. return texture;
  6720. };
  6721. /**
  6722. * @author alteredq / http://alteredqualia.com/
  6723. */
  6724. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  6725. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  6726. this.image = { data: data, width: width, height: height };
  6727. };
  6728. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6729. THREE.DataTexture.prototype.clone = function () {
  6730. var texture = new THREE.DataTexture();
  6731. THREE.Texture.prototype.clone.call( this, texture );
  6732. return texture;
  6733. };
  6734. /**
  6735. * @author mrdoob / http://mrdoob.com/
  6736. */
  6737. THREE.Particle = function ( material ) {
  6738. THREE.Object3D.call( this );
  6739. this.material = material;
  6740. };
  6741. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6742. THREE.Particle.prototype.clone = function ( object ) {
  6743. if ( object === undefined ) object = new THREE.Particle( this.material );
  6744. THREE.Object3D.prototype.clone.call( this, object );
  6745. return object;
  6746. };
  6747. /**
  6748. * @author alteredq / http://alteredqualia.com/
  6749. */
  6750. THREE.ParticleSystem = function ( geometry, material ) {
  6751. THREE.Object3D.call( this );
  6752. this.geometry = geometry;
  6753. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6754. this.sortParticles = false;
  6755. if ( this.geometry ) {
  6756. // calc bound radius
  6757. if( this.geometry.boundingSphere === null ) {
  6758. this.geometry.computeBoundingSphere();
  6759. }
  6760. this.boundRadius = geometry.boundingSphere.radius;
  6761. }
  6762. this.frustumCulled = false;
  6763. };
  6764. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6765. THREE.ParticleSystem.prototype.clone = function ( object ) {
  6766. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  6767. object.sortParticles = this.sortParticles;
  6768. THREE.Object3D.prototype.clone.call( this, object );
  6769. return object;
  6770. };
  6771. /**
  6772. * @author mrdoob / http://mrdoob.com/
  6773. */
  6774. THREE.Line = function ( geometry, material, type ) {
  6775. THREE.Object3D.call( this );
  6776. this.geometry = geometry;
  6777. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6778. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6779. if ( this.geometry ) {
  6780. if ( ! this.geometry.boundingSphere ) {
  6781. this.geometry.computeBoundingSphere();
  6782. }
  6783. }
  6784. };
  6785. THREE.LineStrip = 0;
  6786. THREE.LinePieces = 1;
  6787. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6788. THREE.Line.prototype.clone = function ( object ) {
  6789. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  6790. THREE.Object3D.prototype.clone.call( this, object );
  6791. return object;
  6792. };
  6793. /**
  6794. * @author mrdoob / http://mrdoob.com/
  6795. * @author alteredq / http://alteredqualia.com/
  6796. * @author mikael emtinger / http://gomo.se/
  6797. */
  6798. THREE.Mesh = function ( geometry, material ) {
  6799. THREE.Object3D.call( this );
  6800. this.geometry = geometry;
  6801. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6802. if ( this.geometry ) {
  6803. // calc bound radius
  6804. if ( this.geometry.boundingSphere === null ) {
  6805. this.geometry.computeBoundingSphere();
  6806. }
  6807. this.boundRadius = geometry.boundingSphere.radius;
  6808. // setup morph targets
  6809. if ( this.geometry.morphTargets.length ) {
  6810. this.morphTargetBase = -1;
  6811. this.morphTargetForcedOrder = [];
  6812. this.morphTargetInfluences = [];
  6813. this.morphTargetDictionary = {};
  6814. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6815. this.morphTargetInfluences.push( 0 );
  6816. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6817. }
  6818. }
  6819. }
  6820. }
  6821. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6822. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  6823. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6824. return this.morphTargetDictionary[ name ];
  6825. }
  6826. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6827. return 0;
  6828. };
  6829. THREE.Mesh.prototype.clone = function ( object ) {
  6830. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  6831. THREE.Object3D.prototype.clone.call( this, object );
  6832. return object;
  6833. };
  6834. /**
  6835. * @author mikael emtinger / http://gomo.se/
  6836. * @author alteredq / http://alteredqualia.com/
  6837. */
  6838. THREE.Bone = function( belongsToSkin ) {
  6839. THREE.Object3D.call( this );
  6840. this.skin = belongsToSkin;
  6841. this.skinMatrix = new THREE.Matrix4();
  6842. };
  6843. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6844. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6845. // update local
  6846. if ( this.matrixAutoUpdate ) {
  6847. forceUpdate |= this.updateMatrix();
  6848. }
  6849. // update skin matrix
  6850. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6851. if( parentSkinMatrix ) {
  6852. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6853. } else {
  6854. this.skinMatrix.copy( this.matrix );
  6855. }
  6856. this.matrixWorldNeedsUpdate = false;
  6857. forceUpdate = true;
  6858. }
  6859. // update children
  6860. var child, i, l = this.children.length;
  6861. for ( i = 0; i < l; i ++ ) {
  6862. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6863. }
  6864. };
  6865. /**
  6866. * @author mikael emtinger / http://gomo.se/
  6867. * @author alteredq / http://alteredqualia.com/
  6868. */
  6869. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6870. THREE.Mesh.call( this, geometry, material );
  6871. //
  6872. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6873. // init bones
  6874. this.identityMatrix = new THREE.Matrix4();
  6875. this.bones = [];
  6876. this.boneMatrices = [];
  6877. var b, bone, gbone, p, q, s;
  6878. if ( this.geometry && this.geometry.bones !== undefined ) {
  6879. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6880. gbone = this.geometry.bones[ b ];
  6881. p = gbone.pos;
  6882. q = gbone.rotq;
  6883. s = gbone.scl;
  6884. bone = this.addBone();
  6885. bone.name = gbone.name;
  6886. bone.position.set( p[0], p[1], p[2] );
  6887. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6888. bone.useQuaternion = true;
  6889. if ( s !== undefined ) {
  6890. bone.scale.set( s[0], s[1], s[2] );
  6891. } else {
  6892. bone.scale.set( 1, 1, 1 );
  6893. }
  6894. }
  6895. for ( b = 0; b < this.bones.length; b ++ ) {
  6896. gbone = this.geometry.bones[ b ];
  6897. bone = this.bones[ b ];
  6898. if ( gbone.parent === -1 ) {
  6899. this.add( bone );
  6900. } else {
  6901. this.bones[ gbone.parent ].add( bone );
  6902. }
  6903. }
  6904. //
  6905. var nBones = this.bones.length;
  6906. if ( this.useVertexTexture ) {
  6907. // layout (1 matrix = 4 pixels)
  6908. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6909. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6910. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6911. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6912. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6913. var size;
  6914. if ( nBones > 256 )
  6915. size = 64;
  6916. else if ( nBones > 64 )
  6917. size = 32;
  6918. else if ( nBones > 16 )
  6919. size = 16;
  6920. else
  6921. size = 8;
  6922. this.boneTextureWidth = size;
  6923. this.boneTextureHeight = size;
  6924. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6925. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6926. this.boneTexture.minFilter = THREE.NearestFilter;
  6927. this.boneTexture.magFilter = THREE.NearestFilter;
  6928. this.boneTexture.generateMipmaps = false;
  6929. this.boneTexture.flipY = false;
  6930. } else {
  6931. this.boneMatrices = new Float32Array( 16 * nBones );
  6932. }
  6933. this.pose();
  6934. }
  6935. };
  6936. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6937. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6938. if ( bone === undefined ) {
  6939. bone = new THREE.Bone( this );
  6940. }
  6941. this.bones.push( bone );
  6942. return bone;
  6943. };
  6944. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6945. this.matrixAutoUpdate && this.updateMatrix();
  6946. // update matrixWorld
  6947. if ( this.matrixWorldNeedsUpdate || force ) {
  6948. if ( this.parent ) {
  6949. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6950. } else {
  6951. this.matrixWorld.copy( this.matrix );
  6952. }
  6953. this.matrixWorldNeedsUpdate = false;
  6954. force = true;
  6955. }
  6956. // update children
  6957. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6958. var child = this.children[ i ];
  6959. if ( child instanceof THREE.Bone ) {
  6960. child.update( this.identityMatrix, false );
  6961. } else {
  6962. child.updateMatrixWorld( true );
  6963. }
  6964. }
  6965. // make a snapshot of the bones' rest position
  6966. if ( this.boneInverses == undefined ) {
  6967. this.boneInverses = [];
  6968. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6969. var inverse = new THREE.Matrix4();
  6970. inverse.getInverse( this.bones[ b ].skinMatrix );
  6971. this.boneInverses.push( inverse );
  6972. }
  6973. }
  6974. // flatten bone matrices to array
  6975. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6976. // compute the offset between the current and the original transform;
  6977. //TODO: we could get rid of this multiplication step if the skinMatrix
  6978. // was already representing the offset; however, this requires some
  6979. // major changes to the animation system
  6980. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6981. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6982. }
  6983. if ( this.useVertexTexture ) {
  6984. this.boneTexture.needsUpdate = true;
  6985. }
  6986. };
  6987. THREE.SkinnedMesh.prototype.pose = function() {
  6988. this.updateMatrixWorld( true );
  6989. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6990. // normalize weights
  6991. var sw = this.geometry.skinWeights[ i ];
  6992. var scale = 1.0 / sw.lengthManhattan();
  6993. if ( scale !== Infinity ) {
  6994. sw.multiplyScalar( scale );
  6995. } else {
  6996. sw.set( 1 ); // this will be normalized by the shader anyway
  6997. }
  6998. }
  6999. };
  7000. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7001. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7002. THREE.Mesh.prototype.clone.call( this, object );
  7003. return object;
  7004. };
  7005. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7006. /**
  7007. * @author alteredq / http://alteredqualia.com/
  7008. */
  7009. THREE.MorphAnimMesh = function ( geometry, material ) {
  7010. THREE.Mesh.call( this, geometry, material );
  7011. // API
  7012. this.duration = 1000; // milliseconds
  7013. this.mirroredLoop = false;
  7014. this.time = 0;
  7015. // internals
  7016. this.lastKeyframe = 0;
  7017. this.currentKeyframe = 0;
  7018. this.direction = 1;
  7019. this.directionBackwards = false;
  7020. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7021. };
  7022. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7023. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7024. this.startKeyframe = start;
  7025. this.endKeyframe = end;
  7026. this.length = this.endKeyframe - this.startKeyframe + 1;
  7027. };
  7028. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7029. this.direction = 1;
  7030. this.directionBackwards = false;
  7031. };
  7032. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7033. this.direction = -1;
  7034. this.directionBackwards = true;
  7035. };
  7036. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7037. var geometry = this.geometry;
  7038. if ( ! geometry.animations ) geometry.animations = {};
  7039. var firstAnimation, animations = geometry.animations;
  7040. var pattern = /([a-z]+)(\d+)/;
  7041. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7042. var morph = geometry.morphTargets[ i ];
  7043. var parts = morph.name.match( pattern );
  7044. if ( parts && parts.length > 1 ) {
  7045. var label = parts[ 1 ];
  7046. var num = parts[ 2 ];
  7047. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7048. var animation = animations[ label ];
  7049. if ( i < animation.start ) animation.start = i;
  7050. if ( i > animation.end ) animation.end = i;
  7051. if ( ! firstAnimation ) firstAnimation = label;
  7052. }
  7053. }
  7054. geometry.firstAnimation = firstAnimation;
  7055. };
  7056. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7057. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7058. this.geometry.animations[ label ] = { start: start, end: end };
  7059. };
  7060. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7061. var animation = this.geometry.animations[ label ];
  7062. if ( animation ) {
  7063. this.setFrameRange( animation.start, animation.end );
  7064. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7065. this.time = 0;
  7066. } else {
  7067. console.warn( "animation[" + label + "] undefined" );
  7068. }
  7069. };
  7070. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7071. var frameTime = this.duration / this.length;
  7072. this.time += this.direction * delta;
  7073. if ( this.mirroredLoop ) {
  7074. if ( this.time > this.duration || this.time < 0 ) {
  7075. this.direction *= -1;
  7076. if ( this.time > this.duration ) {
  7077. this.time = this.duration;
  7078. this.directionBackwards = true;
  7079. }
  7080. if ( this.time < 0 ) {
  7081. this.time = 0;
  7082. this.directionBackwards = false;
  7083. }
  7084. }
  7085. } else {
  7086. this.time = this.time % this.duration;
  7087. if ( this.time < 0 ) this.time += this.duration;
  7088. }
  7089. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7090. if ( keyframe !== this.currentKeyframe ) {
  7091. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7092. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7093. this.morphTargetInfluences[ keyframe ] = 0;
  7094. this.lastKeyframe = this.currentKeyframe;
  7095. this.currentKeyframe = keyframe;
  7096. }
  7097. var mix = ( this.time % frameTime ) / frameTime;
  7098. if ( this.directionBackwards ) {
  7099. mix = 1 - mix;
  7100. }
  7101. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7102. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7103. };
  7104. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7105. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7106. object.duration = this.duration;
  7107. object.mirroredLoop = this.mirroredLoop;
  7108. object.time = this.time;
  7109. object.lastKeyframe = this.lastKeyframe;
  7110. object.currentKeyframe = this.currentKeyframe;
  7111. object.direction = this.direction;
  7112. object.directionBackwards = this.directionBackwards;
  7113. THREE.Mesh.prototype.clone.call( this, object );
  7114. return object;
  7115. };
  7116. /**
  7117. * @author alteredq / http://alteredqualia.com/
  7118. */
  7119. THREE.Ribbon = function ( geometry, material ) {
  7120. THREE.Object3D.call( this );
  7121. this.geometry = geometry;
  7122. this.material = material;
  7123. };
  7124. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7125. THREE.Ribbon.prototype.clone = function ( object ) {
  7126. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7127. THREE.Object3D.prototype.clone.call( this, object );
  7128. return object;
  7129. };
  7130. /**
  7131. * @author mikael emtinger / http://gomo.se/
  7132. * @author alteredq / http://alteredqualia.com/
  7133. * @author mrdoob / http://mrdoob.com/
  7134. */
  7135. THREE.LOD = function () {
  7136. THREE.Object3D.call( this );
  7137. this.LODs = [];
  7138. };
  7139. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7140. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7141. if ( visibleAtDistance === undefined ) {
  7142. visibleAtDistance = 0;
  7143. }
  7144. visibleAtDistance = Math.abs( visibleAtDistance );
  7145. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7146. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7147. break;
  7148. }
  7149. }
  7150. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7151. this.add( object3D );
  7152. };
  7153. THREE.LOD.prototype.update = function ( camera ) {
  7154. if ( this.LODs.length > 1 ) {
  7155. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7156. var inverse = camera.matrixWorldInverse;
  7157. var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );
  7158. this.LODs[ 0 ].object3D.visible = true;
  7159. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7160. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7161. this.LODs[ l - 1 ].object3D.visible = false;
  7162. this.LODs[ l ].object3D.visible = true;
  7163. } else {
  7164. break;
  7165. }
  7166. }
  7167. for( ; l < this.LODs.length; l ++ ) {
  7168. this.LODs[ l ].object3D.visible = false;
  7169. }
  7170. }
  7171. };
  7172. THREE.LOD.prototype.clone = function () {
  7173. // TODO
  7174. };
  7175. /**
  7176. * @author mikael emtinger / http://gomo.se/
  7177. * @author alteredq / http://alteredqualia.com/
  7178. */
  7179. THREE.Sprite = function ( material ) {
  7180. THREE.Object3D.call( this );
  7181. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7182. this.rotation3d = this.rotation;
  7183. this.rotation = 0;
  7184. };
  7185. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7186. /*
  7187. * Custom update matrix
  7188. */
  7189. THREE.Sprite.prototype.updateMatrix = function () {
  7190. this.matrix.setPosition( this.position );
  7191. this.rotation3d.set( 0, 0, this.rotation );
  7192. this.matrix.setRotationFromEuler( this.rotation3d );
  7193. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7194. this.matrix.scale( this.scale );
  7195. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  7196. }
  7197. this.matrixWorldNeedsUpdate = true;
  7198. };
  7199. THREE.Sprite.prototype.clone = function ( object ) {
  7200. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7201. THREE.Object3D.prototype.clone.call( this, object );
  7202. return object;
  7203. };
  7204. /**
  7205. * @author mrdoob / http://mrdoob.com/
  7206. */
  7207. THREE.Scene = function () {
  7208. THREE.Object3D.call( this );
  7209. this.fog = null;
  7210. this.overrideMaterial = null;
  7211. this.matrixAutoUpdate = false;
  7212. this.__objects = [];
  7213. this.__lights = [];
  7214. this.__objectsAdded = [];
  7215. this.__objectsRemoved = [];
  7216. };
  7217. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7218. THREE.Scene.prototype.__addObject = function ( object ) {
  7219. if ( object instanceof THREE.Light ) {
  7220. if ( this.__lights.indexOf( object ) === - 1 ) {
  7221. this.__lights.push( object );
  7222. }
  7223. if ( object.target && object.target.parent === undefined ) {
  7224. this.add( object.target );
  7225. }
  7226. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7227. if ( this.__objects.indexOf( object ) === - 1 ) {
  7228. this.__objects.push( object );
  7229. this.__objectsAdded.push( object );
  7230. // check if previously removed
  7231. var i = this.__objectsRemoved.indexOf( object );
  7232. if ( i !== -1 ) {
  7233. this.__objectsRemoved.splice( i, 1 );
  7234. }
  7235. }
  7236. }
  7237. for ( var c = 0; c < object.children.length; c ++ ) {
  7238. this.__addObject( object.children[ c ] );
  7239. }
  7240. };
  7241. THREE.Scene.prototype.__removeObject = function ( object ) {
  7242. if ( object instanceof THREE.Light ) {
  7243. var i = this.__lights.indexOf( object );
  7244. if ( i !== -1 ) {
  7245. this.__lights.splice( i, 1 );
  7246. }
  7247. } else if ( !( object instanceof THREE.Camera ) ) {
  7248. var i = this.__objects.indexOf( object );
  7249. if( i !== -1 ) {
  7250. this.__objects.splice( i, 1 );
  7251. this.__objectsRemoved.push( object );
  7252. // check if previously added
  7253. var ai = this.__objectsAdded.indexOf( object );
  7254. if ( ai !== -1 ) {
  7255. this.__objectsAdded.splice( ai, 1 );
  7256. }
  7257. }
  7258. }
  7259. for ( var c = 0; c < object.children.length; c ++ ) {
  7260. this.__removeObject( object.children[ c ] );
  7261. }
  7262. };
  7263. /**
  7264. * @author mrdoob / http://mrdoob.com/
  7265. * @author alteredq / http://alteredqualia.com/
  7266. */
  7267. THREE.Fog = function ( hex, near, far ) {
  7268. this.name = '';
  7269. this.color = new THREE.Color( hex );
  7270. this.near = ( near !== undefined ) ? near : 1;
  7271. this.far = ( far !== undefined ) ? far : 1000;
  7272. };
  7273. THREE.Fog.prototype.clone = function () {
  7274. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7275. };
  7276. /**
  7277. * @author mrdoob / http://mrdoob.com/
  7278. * @author alteredq / http://alteredqualia.com/
  7279. */
  7280. THREE.FogExp2 = function ( hex, density ) {
  7281. this.name = '';
  7282. this.color = new THREE.Color( hex );
  7283. this.density = ( density !== undefined ) ? density : 0.00025;
  7284. };
  7285. THREE.FogExp2.prototype.clone = function () {
  7286. return new THREE.FogExp2( this.color.getHex(), this.density );
  7287. };
  7288. /**
  7289. * @author mrdoob / http://mrdoob.com/
  7290. */
  7291. THREE.CanvasRenderer = function ( parameters ) {
  7292. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7293. parameters = parameters || {};
  7294. var _this = this,
  7295. _renderData, _elements, _lights,
  7296. _projector = new THREE.Projector(),
  7297. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7298. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7299. _context = _canvas.getContext( '2d' ),
  7300. _clearColor = new THREE.Color( 0x000000 ),
  7301. _clearOpacity = 0,
  7302. _contextGlobalAlpha = 1,
  7303. _contextGlobalCompositeOperation = 0,
  7304. _contextStrokeStyle = null,
  7305. _contextFillStyle = null,
  7306. _contextLineWidth = null,
  7307. _contextLineCap = null,
  7308. _contextLineJoin = null,
  7309. _v1, _v2, _v3, _v4,
  7310. _v5 = new THREE.RenderableVertex(),
  7311. _v6 = new THREE.RenderableVertex(),
  7312. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7313. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7314. _color = new THREE.Color(),
  7315. _color1 = new THREE.Color(),
  7316. _color2 = new THREE.Color(),
  7317. _color3 = new THREE.Color(),
  7318. _color4 = new THREE.Color(),
  7319. _diffuseColor = new THREE.Color(),
  7320. _emissiveColor = new THREE.Color(),
  7321. _patterns = {}, _imagedatas = {},
  7322. _near, _far,
  7323. _image, _uvs,
  7324. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7325. _clipRect = new THREE.Rectangle(),
  7326. _clearRect = new THREE.Rectangle(),
  7327. _bboxRect = new THREE.Rectangle(),
  7328. _enableLighting = false,
  7329. _ambientLight = new THREE.Color(),
  7330. _directionalLights = new THREE.Color(),
  7331. _pointLights = new THREE.Color(),
  7332. _pi2 = Math.PI * 2,
  7333. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7334. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7335. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7336. _pixelMap = document.createElement( 'canvas' );
  7337. _pixelMap.width = _pixelMap.height = 2;
  7338. _pixelMapContext = _pixelMap.getContext( '2d' );
  7339. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7340. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7341. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7342. _pixelMapData = _pixelMapImage.data;
  7343. _gradientMap = document.createElement( 'canvas' );
  7344. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7345. _gradientMapContext = _gradientMap.getContext( '2d' );
  7346. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7347. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7348. _gradientMapQuality --; // Fix UVs
  7349. this.domElement = _canvas;
  7350. this.autoClear = true;
  7351. this.sortObjects = true;
  7352. this.sortElements = true;
  7353. this.info = {
  7354. render: {
  7355. vertices: 0,
  7356. faces: 0
  7357. }
  7358. }
  7359. this.setSize = function ( width, height ) {
  7360. _canvasWidth = width;
  7361. _canvasHeight = height;
  7362. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7363. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7364. _canvas.width = _canvasWidth;
  7365. _canvas.height = _canvasHeight;
  7366. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7367. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7368. _contextGlobalAlpha = 1;
  7369. _contextGlobalCompositeOperation = 0;
  7370. _contextStrokeStyle = null;
  7371. _contextFillStyle = null;
  7372. _contextLineWidth = null;
  7373. _contextLineCap = null;
  7374. _contextLineJoin = null;
  7375. };
  7376. this.setClearColor = function ( color, opacity ) {
  7377. _clearColor.copy( color );
  7378. _clearOpacity = opacity !== undefined ? opacity : 1;
  7379. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7380. };
  7381. this.setClearColorHex = function ( hex, opacity ) {
  7382. _clearColor.setHex( hex );
  7383. _clearOpacity = opacity !== undefined ? opacity : 1;
  7384. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7385. };
  7386. this.getMaxAnisotropy = function () {
  7387. return 0;
  7388. };
  7389. this.clear = function () {
  7390. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7391. if ( _clearRect.isEmpty() === false ) {
  7392. _clearRect.minSelf( _clipRect );
  7393. _clearRect.inflate( 2 );
  7394. if ( _clearOpacity < 1 ) {
  7395. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7396. }
  7397. if ( _clearOpacity > 0 ) {
  7398. setBlending( THREE.NormalBlending );
  7399. setOpacity( 1 );
  7400. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7401. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7402. }
  7403. _clearRect.empty();
  7404. }
  7405. };
  7406. this.render = function ( scene, camera ) {
  7407. if ( camera instanceof THREE.Camera === false ) {
  7408. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7409. return;
  7410. }
  7411. var e, el, element, material;
  7412. this.autoClear === true
  7413. ? this.clear()
  7414. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7415. _this.info.render.vertices = 0;
  7416. _this.info.render.faces = 0;
  7417. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7418. _elements = _renderData.elements;
  7419. _lights = _renderData.lights;
  7420. /* DEBUG
  7421. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7422. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7423. */
  7424. _enableLighting = _lights.length > 0;
  7425. if ( _enableLighting === true ) {
  7426. calculateLights();
  7427. }
  7428. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7429. element = _elements[ e ];
  7430. material = element.material;
  7431. if ( material === undefined || material.visible === false ) continue;
  7432. _bboxRect.empty();
  7433. if ( element instanceof THREE.RenderableParticle ) {
  7434. _v1 = element;
  7435. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7436. renderParticle( _v1, element, material, scene );
  7437. } else if ( element instanceof THREE.RenderableLine ) {
  7438. _v1 = element.v1; _v2 = element.v2;
  7439. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7440. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7441. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7442. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7443. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7444. renderLine( _v1, _v2, element, material, scene );
  7445. }
  7446. } else if ( element instanceof THREE.RenderableFace3 ) {
  7447. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7448. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7449. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7450. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7451. if ( material.overdraw === true ) {
  7452. expand( _v1.positionScreen, _v2.positionScreen );
  7453. expand( _v2.positionScreen, _v3.positionScreen );
  7454. expand( _v3.positionScreen, _v1.positionScreen );
  7455. }
  7456. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7457. _v2.positionScreen.x, _v2.positionScreen.y,
  7458. _v3.positionScreen.x, _v3.positionScreen.y );
  7459. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7460. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7461. }
  7462. } else if ( element instanceof THREE.RenderableFace4 ) {
  7463. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7464. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7465. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7466. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7467. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7468. _v5.positionScreen.copy( _v2.positionScreen );
  7469. _v6.positionScreen.copy( _v4.positionScreen );
  7470. if ( material.overdraw === true ) {
  7471. expand( _v1.positionScreen, _v2.positionScreen );
  7472. expand( _v2.positionScreen, _v4.positionScreen );
  7473. expand( _v4.positionScreen, _v1.positionScreen );
  7474. expand( _v3.positionScreen, _v5.positionScreen );
  7475. expand( _v3.positionScreen, _v6.positionScreen );
  7476. }
  7477. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7478. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7479. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7480. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7481. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7482. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7483. }
  7484. }
  7485. /* DEBUG
  7486. _context.lineWidth = 1;
  7487. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7488. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7489. */
  7490. _clearRect.addRectangle( _bboxRect );
  7491. }
  7492. /* DEBUG
  7493. _context.lineWidth = 1;
  7494. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7495. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7496. */
  7497. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7498. //
  7499. function calculateLights() {
  7500. _ambientLight.setRGB( 0, 0, 0 );
  7501. _directionalLights.setRGB( 0, 0, 0 );
  7502. _pointLights.setRGB( 0, 0, 0 );
  7503. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7504. var light = _lights[ l ];
  7505. var lightColor = light.color;
  7506. if ( light instanceof THREE.AmbientLight ) {
  7507. _ambientLight.r += lightColor.r;
  7508. _ambientLight.g += lightColor.g;
  7509. _ambientLight.b += lightColor.b;
  7510. } else if ( light instanceof THREE.DirectionalLight ) {
  7511. // for particles
  7512. _directionalLights.r += lightColor.r;
  7513. _directionalLights.g += lightColor.g;
  7514. _directionalLights.b += lightColor.b;
  7515. } else if ( light instanceof THREE.PointLight ) {
  7516. // for particles
  7517. _pointLights.r += lightColor.r;
  7518. _pointLights.g += lightColor.g;
  7519. _pointLights.b += lightColor.b;
  7520. }
  7521. }
  7522. }
  7523. function calculateLight( position, normal, color ) {
  7524. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7525. var light = _lights[ l ];
  7526. var lightColor = light.color;
  7527. if ( light instanceof THREE.DirectionalLight ) {
  7528. var lightPosition = light.matrixWorld.getPosition().normalize();
  7529. var amount = normal.dot( lightPosition );
  7530. if ( amount <= 0 ) continue;
  7531. amount *= light.intensity;
  7532. color.r += lightColor.r * amount;
  7533. color.g += lightColor.g * amount;
  7534. color.b += lightColor.b * amount;
  7535. } else if ( light instanceof THREE.PointLight ) {
  7536. var lightPosition = light.matrixWorld.getPosition();
  7537. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7538. if ( amount <= 0 ) continue;
  7539. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7540. if ( amount == 0 ) continue;
  7541. amount *= light.intensity;
  7542. color.r += lightColor.r * amount;
  7543. color.g += lightColor.g * amount;
  7544. color.b += lightColor.b * amount;
  7545. }
  7546. }
  7547. }
  7548. function renderParticle( v1, element, material, scene ) {
  7549. setOpacity( material.opacity );
  7550. setBlending( material.blending );
  7551. var width, height, scaleX, scaleY,
  7552. bitmap, bitmapWidth, bitmapHeight;
  7553. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7554. if ( material.map === null ) {
  7555. scaleX = element.object.scale.x;
  7556. scaleY = element.object.scale.y;
  7557. // TODO: Be able to disable this
  7558. scaleX *= element.scale.x * _canvasWidthHalf;
  7559. scaleY *= element.scale.y * _canvasHeightHalf;
  7560. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7561. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7562. return;
  7563. }
  7564. setFillStyle( material.color.getStyle() );
  7565. _context.save();
  7566. _context.translate( v1.x, v1.y );
  7567. _context.rotate( - element.rotation );
  7568. _context.scale( scaleX, scaleY );
  7569. _context.fillRect( -1, -1, 2, 2 );
  7570. _context.restore();
  7571. } else {
  7572. bitmap = material.map.image;
  7573. bitmapWidth = bitmap.width >> 1;
  7574. bitmapHeight = bitmap.height >> 1;
  7575. scaleX = element.scale.x * _canvasWidthHalf;
  7576. scaleY = element.scale.y * _canvasHeightHalf;
  7577. width = scaleX * bitmapWidth;
  7578. height = scaleY * bitmapHeight;
  7579. // TODO: Rotations break this...
  7580. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7581. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7582. return;
  7583. }
  7584. _context.save();
  7585. _context.translate( v1.x, v1.y );
  7586. _context.rotate( - element.rotation );
  7587. _context.scale( scaleX, - scaleY );
  7588. _context.translate( - bitmapWidth, - bitmapHeight );
  7589. _context.drawImage( bitmap, 0, 0 );
  7590. _context.restore();
  7591. }
  7592. /* DEBUG
  7593. setStrokeStyle( 'rgb(255,255,0)' );
  7594. _context.beginPath();
  7595. _context.moveTo( v1.x - 10, v1.y );
  7596. _context.lineTo( v1.x + 10, v1.y );
  7597. _context.moveTo( v1.x, v1.y - 10 );
  7598. _context.lineTo( v1.x, v1.y + 10 );
  7599. _context.stroke();
  7600. */
  7601. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7602. width = element.scale.x * _canvasWidthHalf;
  7603. height = element.scale.y * _canvasHeightHalf;
  7604. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7605. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7606. return;
  7607. }
  7608. setStrokeStyle( material.color.getStyle() );
  7609. setFillStyle( material.color.getStyle() );
  7610. _context.save();
  7611. _context.translate( v1.x, v1.y );
  7612. _context.rotate( - element.rotation );
  7613. _context.scale( width, height );
  7614. material.program( _context );
  7615. _context.restore();
  7616. }
  7617. }
  7618. function renderLine( v1, v2, element, material, scene ) {
  7619. setOpacity( material.opacity );
  7620. setBlending( material.blending );
  7621. _context.beginPath();
  7622. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7623. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7624. if ( material instanceof THREE.LineBasicMaterial ) {
  7625. setLineWidth( material.linewidth );
  7626. setLineCap( material.linecap );
  7627. setLineJoin( material.linejoin );
  7628. setStrokeStyle( material.color.getStyle() );
  7629. _context.stroke();
  7630. _bboxRect.inflate( material.linewidth * 2 );
  7631. }
  7632. }
  7633. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7634. _this.info.render.vertices += 3;
  7635. _this.info.render.faces ++;
  7636. setOpacity( material.opacity );
  7637. setBlending( material.blending );
  7638. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7639. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7640. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7641. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7642. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  7643. _diffuseColor.copy( material.color );
  7644. _emissiveColor.copy( material.emissive );
  7645. if ( material.vertexColors === THREE.FaceColors ) {
  7646. _diffuseColor.r *= element.color.r;
  7647. _diffuseColor.g *= element.color.g;
  7648. _diffuseColor.b *= element.color.b;
  7649. }
  7650. if ( _enableLighting === true ) {
  7651. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7652. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7653. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7654. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7655. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7656. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7657. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7658. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7659. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7660. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7661. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7662. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7663. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7664. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7665. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7666. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7667. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7668. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7669. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7670. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7671. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7672. } else {
  7673. _color.r = _ambientLight.r;
  7674. _color.g = _ambientLight.g;
  7675. _color.b = _ambientLight.b;
  7676. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7677. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7678. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7679. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7680. material.wireframe === true
  7681. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7682. : fillPath( _color );
  7683. }
  7684. } else {
  7685. material.wireframe === true
  7686. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7687. : fillPath( material.color );
  7688. }
  7689. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7690. if ( material.map !== null ) {
  7691. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7692. _uvs = element.uvs[ 0 ];
  7693. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].u, _uvs[ uv1 ].v, _uvs[ uv2 ].u, _uvs[ uv2 ].v, _uvs[ uv3 ].u, _uvs[ uv3 ].v, material.map );
  7694. }
  7695. } else if ( material.envMap !== null ) {
  7696. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7697. var cameraMatrix = camera.matrixWorldInverse;
  7698. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7699. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7700. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7701. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7702. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7703. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7704. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7705. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7706. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7707. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7708. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7709. }*/
  7710. } else {
  7711. _color.copy( material.color );
  7712. if ( material.vertexColors === THREE.FaceColors ) {
  7713. _color.r *= element.color.r;
  7714. _color.g *= element.color.g;
  7715. _color.b *= element.color.b;
  7716. }
  7717. material.wireframe === true
  7718. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7719. : fillPath( _color );
  7720. }
  7721. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7722. _near = camera.near;
  7723. _far = camera.far;
  7724. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7725. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7726. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7727. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7728. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7729. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7730. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7731. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7732. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7733. _color.r = normalToComponent( element.normalWorld.x );
  7734. _color.g = normalToComponent( element.normalWorld.y );
  7735. _color.b = normalToComponent( element.normalWorld.z );
  7736. material.wireframe === true
  7737. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7738. : fillPath( _color );
  7739. }
  7740. }
  7741. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7742. _this.info.render.vertices += 4;
  7743. _this.info.render.faces ++;
  7744. setOpacity( material.opacity );
  7745. setBlending( material.blending );
  7746. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7747. // Let renderFace3() handle this
  7748. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7749. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7750. return;
  7751. }
  7752. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7753. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7754. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7755. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7756. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7757. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7758. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7759. _diffuseColor.copy( material.color );
  7760. _emissiveColor.copy( material.emissive );
  7761. if ( material.vertexColors === THREE.FaceColors ) {
  7762. _diffuseColor.r *= element.color.r;
  7763. _diffuseColor.g *= element.color.g;
  7764. _diffuseColor.b *= element.color.b;
  7765. }
  7766. if ( _enableLighting === true ) {
  7767. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7768. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7769. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7770. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7771. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7772. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7773. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7774. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7775. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7776. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7777. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7778. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7779. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7780. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7781. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7782. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7783. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7784. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  7785. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  7786. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  7787. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7788. // TODO: UVs are incorrect, v4->v3?
  7789. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7790. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7791. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7792. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7793. } else {
  7794. _color.r = _ambientLight.r;
  7795. _color.g = _ambientLight.g;
  7796. _color.b = _ambientLight.b;
  7797. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7798. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7799. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7800. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7801. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7802. material.wireframe === true
  7803. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7804. : fillPath( _color );
  7805. }
  7806. } else {
  7807. _color.r = _diffuseColor.r + _emissiveColor.r;
  7808. _color.g = _diffuseColor.g + _emissiveColor.g;
  7809. _color.b = _diffuseColor.b + _emissiveColor.b;
  7810. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7811. material.wireframe === true
  7812. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7813. : fillPath( _color );
  7814. }
  7815. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  7816. _color.copy( material.color );
  7817. if ( material.vertexColors === THREE.FaceColors ) {
  7818. _color.r *= element.color.r;
  7819. _color.g *= element.color.g;
  7820. _color.b *= element.color.b;
  7821. }
  7822. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7823. material.wireframe === true
  7824. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7825. : fillPath( _color );
  7826. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7827. _color.r = normalToComponent( element.normalWorld.x );
  7828. _color.g = normalToComponent( element.normalWorld.y );
  7829. _color.b = normalToComponent( element.normalWorld.z );
  7830. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7831. material.wireframe === true
  7832. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7833. : fillPath( _color );
  7834. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7835. _near = camera.near;
  7836. _far = camera.far;
  7837. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7838. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7839. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7840. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7841. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7842. // TODO: UVs are incorrect, v4->v3?
  7843. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7844. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7845. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7846. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7847. }
  7848. }
  7849. //
  7850. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7851. _context.beginPath();
  7852. _context.moveTo( x0, y0 );
  7853. _context.lineTo( x1, y1 );
  7854. _context.lineTo( x2, y2 );
  7855. _context.closePath();
  7856. }
  7857. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7858. _context.beginPath();
  7859. _context.moveTo( x0, y0 );
  7860. _context.lineTo( x1, y1 );
  7861. _context.lineTo( x2, y2 );
  7862. _context.lineTo( x3, y3 );
  7863. _context.closePath();
  7864. }
  7865. function strokePath( color, linewidth, linecap, linejoin ) {
  7866. setLineWidth( linewidth );
  7867. setLineCap( linecap );
  7868. setLineJoin( linejoin );
  7869. setStrokeStyle( color.getStyle() );
  7870. _context.stroke();
  7871. _bboxRect.inflate( linewidth * 2 );
  7872. }
  7873. function fillPath( color ) {
  7874. setFillStyle( color.getStyle() );
  7875. _context.fill();
  7876. }
  7877. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7878. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  7879. if ( texture.needsUpdate === true ) {
  7880. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7881. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7882. _patterns[ texture.id ] = _context.createPattern(
  7883. texture.image, repeatX === true && repeatY === true
  7884. ? 'repeat'
  7885. : repeatX === true && repeatY === false
  7886. ? 'repeat-x'
  7887. : repeatX === false && repeatY === true
  7888. ? 'repeat-y'
  7889. : 'no-repeat'
  7890. );
  7891. texture.needsUpdate = false;
  7892. }
  7893. _patterns[ texture.id ] === undefined
  7894. ? setFillStyle( 'rgba(0,0,0,1)' )
  7895. : setFillStyle( _patterns[ texture.id ] );
  7896. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7897. var a, b, c, d, e, f, det, idet,
  7898. offsetX = texture.offset.x / texture.repeat.x,
  7899. offsetY = texture.offset.y / texture.repeat.y,
  7900. width = texture.image.width * texture.repeat.x,
  7901. height = texture.image.height * texture.repeat.y;
  7902. u0 = ( u0 + offsetX ) * width;
  7903. v0 = ( 1.0 - v0 + offsetY ) * height;
  7904. u1 = ( u1 + offsetX ) * width;
  7905. v1 = ( 1.0 - v1 + offsetY ) * height;
  7906. u2 = ( u2 + offsetX ) * width;
  7907. v2 = ( 1.0 - v2 + offsetY ) * height;
  7908. x1 -= x0; y1 -= y0;
  7909. x2 -= x0; y2 -= y0;
  7910. u1 -= u0; v1 -= v0;
  7911. u2 -= u0; v2 -= v0;
  7912. det = u1 * v2 - u2 * v1;
  7913. if ( det === 0 ) {
  7914. if ( _imagedatas[ texture.id ] === undefined ) {
  7915. var canvas = document.createElement( 'canvas' )
  7916. canvas.width = texture.image.width;
  7917. canvas.height = texture.image.height;
  7918. var context = canvas.getContext( '2d' );
  7919. context.drawImage( texture.image, 0, 0 );
  7920. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7921. }
  7922. var data = _imagedatas[ texture.id ];
  7923. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7924. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7925. fillPath( _color );
  7926. return;
  7927. }
  7928. idet = 1 / det;
  7929. a = ( v2 * x1 - v1 * x2 ) * idet;
  7930. b = ( v2 * y1 - v1 * y2 ) * idet;
  7931. c = ( u1 * x2 - u2 * x1 ) * idet;
  7932. d = ( u1 * y2 - u2 * y1 ) * idet;
  7933. e = x0 - a * u0 - c * v0;
  7934. f = y0 - b * u0 - d * v0;
  7935. _context.save();
  7936. _context.transform( a, b, c, d, e, f );
  7937. _context.fill();
  7938. _context.restore();
  7939. }
  7940. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7941. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7942. var a, b, c, d, e, f, det, idet,
  7943. width = image.width - 1,
  7944. height = image.height - 1;
  7945. u0 *= width; v0 *= height;
  7946. u1 *= width; v1 *= height;
  7947. u2 *= width; v2 *= height;
  7948. x1 -= x0; y1 -= y0;
  7949. x2 -= x0; y2 -= y0;
  7950. u1 -= u0; v1 -= v0;
  7951. u2 -= u0; v2 -= v0;
  7952. det = u1 * v2 - u2 * v1;
  7953. idet = 1 / det;
  7954. a = ( v2 * x1 - v1 * x2 ) * idet;
  7955. b = ( v2 * y1 - v1 * y2 ) * idet;
  7956. c = ( u1 * x2 - u2 * x1 ) * idet;
  7957. d = ( u1 * y2 - u2 * y1 ) * idet;
  7958. e = x0 - a * u0 - c * v0;
  7959. f = y0 - b * u0 - d * v0;
  7960. _context.save();
  7961. _context.transform( a, b, c, d, e, f );
  7962. _context.clip();
  7963. _context.drawImage( image, 0, 0 );
  7964. _context.restore();
  7965. }
  7966. function getGradientTexture( color1, color2, color3, color4 ) {
  7967. // http://mrdoob.com/blog/post/710
  7968. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  7969. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  7970. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  7971. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  7972. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  7973. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  7974. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  7975. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  7976. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  7977. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  7978. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  7979. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  7980. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7981. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7982. return _gradientMap;
  7983. }
  7984. function smoothstep( value, min, max ) {
  7985. var x = ( value - min ) / ( max - min );
  7986. return x * x * ( 3 - 2 * x );
  7987. }
  7988. function normalToComponent( normal ) {
  7989. var component = ( normal + 1 ) * 0.5;
  7990. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7991. }
  7992. // Hide anti-alias gaps
  7993. function expand( v1, v2 ) {
  7994. var x = v2.x - v1.x, y = v2.y - v1.y,
  7995. det = x * x + y * y, idet;
  7996. if ( det === 0 ) return;
  7997. idet = 1 / Math.sqrt( det );
  7998. x *= idet; y *= idet;
  7999. v2.x += x; v2.y += y;
  8000. v1.x -= x; v1.y -= y;
  8001. }
  8002. };
  8003. // Context cached methods.
  8004. function setOpacity( value ) {
  8005. if ( _contextGlobalAlpha !== value ) {
  8006. _context.globalAlpha = value;
  8007. _contextGlobalAlpha = value;
  8008. }
  8009. }
  8010. function setBlending( value ) {
  8011. if ( _contextGlobalCompositeOperation !== value ) {
  8012. if ( value === THREE.NormalBlending ) {
  8013. _context.globalCompositeOperation = 'source-over';
  8014. } else if ( value === THREE.AdditiveBlending ) {
  8015. _context.globalCompositeOperation = 'lighter';
  8016. } else if ( value === THREE.SubtractiveBlending ) {
  8017. _context.globalCompositeOperation = 'darker';
  8018. }
  8019. _contextGlobalCompositeOperation = value;
  8020. }
  8021. }
  8022. function setLineWidth( value ) {
  8023. if ( _contextLineWidth !== value ) {
  8024. _context.lineWidth = value;
  8025. _contextLineWidth = value;
  8026. }
  8027. }
  8028. function setLineCap( value ) {
  8029. // "butt", "round", "square"
  8030. if ( _contextLineCap !== value ) {
  8031. _context.lineCap = value;
  8032. _contextLineCap = value;
  8033. }
  8034. }
  8035. function setLineJoin( value ) {
  8036. // "round", "bevel", "miter"
  8037. if ( _contextLineJoin !== value ) {
  8038. _context.lineJoin = value;
  8039. _contextLineJoin = value;
  8040. }
  8041. }
  8042. function setStrokeStyle( value ) {
  8043. if ( _contextStrokeStyle !== value ) {
  8044. _context.strokeStyle = value;
  8045. _contextStrokeStyle = value;
  8046. }
  8047. }
  8048. function setFillStyle( value ) {
  8049. if ( _contextFillStyle !== value ) {
  8050. _context.fillStyle = value;
  8051. _contextFillStyle = value;
  8052. }
  8053. }
  8054. };
  8055. /**
  8056. * @author alteredq / http://alteredqualia.com/
  8057. * @author mrdoob / http://mrdoob.com/
  8058. * @author mikael emtinger / http://gomo.se/
  8059. */
  8060. THREE.ShaderChunk = {
  8061. // FOG
  8062. fog_pars_fragment: [
  8063. "#ifdef USE_FOG",
  8064. "uniform vec3 fogColor;",
  8065. "#ifdef FOG_EXP2",
  8066. "uniform float fogDensity;",
  8067. "#else",
  8068. "uniform float fogNear;",
  8069. "uniform float fogFar;",
  8070. "#endif",
  8071. "#endif"
  8072. ].join("\n"),
  8073. fog_fragment: [
  8074. "#ifdef USE_FOG",
  8075. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8076. "#ifdef FOG_EXP2",
  8077. "const float LOG2 = 1.442695;",
  8078. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8079. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8080. "#else",
  8081. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8082. "#endif",
  8083. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8084. "#endif"
  8085. ].join("\n"),
  8086. // ENVIRONMENT MAP
  8087. envmap_pars_fragment: [
  8088. "#ifdef USE_ENVMAP",
  8089. "uniform float reflectivity;",
  8090. "uniform samplerCube envMap;",
  8091. "uniform float flipEnvMap;",
  8092. "uniform int combine;",
  8093. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8094. "uniform bool useRefract;",
  8095. "uniform float refractionRatio;",
  8096. "#else",
  8097. "varying vec3 vReflect;",
  8098. "#endif",
  8099. "#endif"
  8100. ].join("\n"),
  8101. envmap_fragment: [
  8102. "#ifdef USE_ENVMAP",
  8103. "vec3 reflectVec;",
  8104. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8105. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8106. "if ( useRefract ) {",
  8107. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8108. "} else { ",
  8109. "reflectVec = reflect( cameraToVertex, normal );",
  8110. "}",
  8111. "#else",
  8112. "reflectVec = vReflect;",
  8113. "#endif",
  8114. "#ifdef DOUBLE_SIDED",
  8115. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8116. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8117. "#else",
  8118. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8119. "#endif",
  8120. "#ifdef GAMMA_INPUT",
  8121. "cubeColor.xyz *= cubeColor.xyz;",
  8122. "#endif",
  8123. "if ( combine == 1 ) {",
  8124. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8125. "} else if ( combine == 2 ) {",
  8126. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8127. "} else {",
  8128. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8129. "}",
  8130. "#endif"
  8131. ].join("\n"),
  8132. envmap_pars_vertex: [
  8133. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8134. "varying vec3 vReflect;",
  8135. "uniform float refractionRatio;",
  8136. "uniform bool useRefract;",
  8137. "#endif"
  8138. ].join("\n"),
  8139. worldpos_vertex : [
  8140. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8141. "#ifdef USE_SKINNING",
  8142. "vec4 worldPosition = modelMatrix * skinned;",
  8143. "#endif",
  8144. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8145. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8146. "#endif",
  8147. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8148. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8149. "#endif",
  8150. "#endif"
  8151. ].join("\n"),
  8152. envmap_vertex : [
  8153. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8154. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8155. "worldNormal = normalize( worldNormal );",
  8156. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8157. "if ( useRefract ) {",
  8158. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8159. "} else {",
  8160. "vReflect = reflect( cameraToVertex, worldNormal );",
  8161. "}",
  8162. "#endif"
  8163. ].join("\n"),
  8164. // COLOR MAP (particles)
  8165. map_particle_pars_fragment: [
  8166. "#ifdef USE_MAP",
  8167. "uniform sampler2D map;",
  8168. "#endif"
  8169. ].join("\n"),
  8170. map_particle_fragment: [
  8171. "#ifdef USE_MAP",
  8172. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8173. "#endif"
  8174. ].join("\n"),
  8175. // COLOR MAP (triangles)
  8176. map_pars_vertex: [
  8177. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8178. "varying vec2 vUv;",
  8179. "uniform vec4 offsetRepeat;",
  8180. "#endif"
  8181. ].join("\n"),
  8182. map_pars_fragment: [
  8183. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8184. "varying vec2 vUv;",
  8185. "#endif",
  8186. "#ifdef USE_MAP",
  8187. "uniform sampler2D map;",
  8188. "#endif"
  8189. ].join("\n"),
  8190. map_vertex: [
  8191. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8192. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8193. "#endif"
  8194. ].join("\n"),
  8195. map_fragment: [
  8196. "#ifdef USE_MAP",
  8197. "#ifdef GAMMA_INPUT",
  8198. "vec4 texelColor = texture2D( map, vUv );",
  8199. "texelColor.xyz *= texelColor.xyz;",
  8200. "gl_FragColor = gl_FragColor * texelColor;",
  8201. "#else",
  8202. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  8203. "#endif",
  8204. "#endif"
  8205. ].join("\n"),
  8206. // LIGHT MAP
  8207. lightmap_pars_fragment: [
  8208. "#ifdef USE_LIGHTMAP",
  8209. "varying vec2 vUv2;",
  8210. "uniform sampler2D lightMap;",
  8211. "#endif"
  8212. ].join("\n"),
  8213. lightmap_pars_vertex: [
  8214. "#ifdef USE_LIGHTMAP",
  8215. "varying vec2 vUv2;",
  8216. "#endif"
  8217. ].join("\n"),
  8218. lightmap_fragment: [
  8219. "#ifdef USE_LIGHTMAP",
  8220. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8221. "#endif"
  8222. ].join("\n"),
  8223. lightmap_vertex: [
  8224. "#ifdef USE_LIGHTMAP",
  8225. "vUv2 = uv2;",
  8226. "#endif"
  8227. ].join("\n"),
  8228. // BUMP MAP
  8229. bumpmap_pars_fragment: [
  8230. "#ifdef USE_BUMPMAP",
  8231. "uniform sampler2D bumpMap;",
  8232. "uniform float bumpScale;",
  8233. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8234. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8235. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8236. "vec2 dHdxy_fwd() {",
  8237. "vec2 dSTdx = dFdx( vUv );",
  8238. "vec2 dSTdy = dFdy( vUv );",
  8239. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8240. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8241. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8242. "return vec2( dBx, dBy );",
  8243. "}",
  8244. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8245. "vec3 vSigmaX = dFdx( surf_pos );",
  8246. "vec3 vSigmaY = dFdy( surf_pos );",
  8247. "vec3 vN = surf_norm;", // normalized
  8248. "vec3 R1 = cross( vSigmaY, vN );",
  8249. "vec3 R2 = cross( vN, vSigmaX );",
  8250. "float fDet = dot( vSigmaX, R1 );",
  8251. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8252. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8253. "}",
  8254. "#endif"
  8255. ].join("\n"),
  8256. // NORMAL MAP
  8257. normalmap_pars_fragment: [
  8258. "#ifdef USE_NORMALMAP",
  8259. "uniform sampler2D normalMap;",
  8260. "uniform vec2 normalScale;",
  8261. // Per-Pixel Tangent Space Normal Mapping
  8262. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8263. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8264. "vec3 q0 = dFdx( eye_pos.xyz );",
  8265. "vec3 q1 = dFdy( eye_pos.xyz );",
  8266. "vec2 st0 = dFdx( vUv.st );",
  8267. "vec2 st1 = dFdy( vUv.st );",
  8268. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8269. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8270. "vec3 N = normalize( surf_norm );",
  8271. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8272. "mapN.xy = normalScale * mapN.xy;",
  8273. "mat3 tsn = mat3( S, T, N );",
  8274. "return normalize( tsn * mapN );",
  8275. "}",
  8276. "#endif"
  8277. ].join("\n"),
  8278. // SPECULAR MAP
  8279. specularmap_pars_fragment: [
  8280. "#ifdef USE_SPECULARMAP",
  8281. "uniform sampler2D specularMap;",
  8282. "#endif"
  8283. ].join("\n"),
  8284. specularmap_fragment: [
  8285. "float specularStrength;",
  8286. "#ifdef USE_SPECULARMAP",
  8287. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8288. "specularStrength = texelSpecular.r;",
  8289. "#else",
  8290. "specularStrength = 1.0;",
  8291. "#endif"
  8292. ].join("\n"),
  8293. // LIGHTS LAMBERT
  8294. lights_lambert_pars_vertex: [
  8295. "uniform vec3 ambient;",
  8296. "uniform vec3 diffuse;",
  8297. "uniform vec3 emissive;",
  8298. "uniform vec3 ambientLightColor;",
  8299. "#if MAX_DIR_LIGHTS > 0",
  8300. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8301. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8302. "#endif",
  8303. "#if MAX_HEMI_LIGHTS > 0",
  8304. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8305. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8306. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8307. "#endif",
  8308. "#if MAX_POINT_LIGHTS > 0",
  8309. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8310. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8311. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8312. "#endif",
  8313. "#if MAX_SPOT_LIGHTS > 0",
  8314. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8315. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8316. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8317. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8318. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8319. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8320. "#endif",
  8321. "#ifdef WRAP_AROUND",
  8322. "uniform vec3 wrapRGB;",
  8323. "#endif"
  8324. ].join("\n"),
  8325. lights_lambert_vertex: [
  8326. "vLightFront = vec3( 0.0 );",
  8327. "#ifdef DOUBLE_SIDED",
  8328. "vLightBack = vec3( 0.0 );",
  8329. "#endif",
  8330. "transformedNormal = normalize( transformedNormal );",
  8331. "#if MAX_DIR_LIGHTS > 0",
  8332. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8333. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8334. "vec3 dirVector = normalize( lDirection.xyz );",
  8335. "float dotProduct = dot( transformedNormal, dirVector );",
  8336. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8337. "#ifdef DOUBLE_SIDED",
  8338. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8339. "#ifdef WRAP_AROUND",
  8340. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8341. "#endif",
  8342. "#endif",
  8343. "#ifdef WRAP_AROUND",
  8344. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8345. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8346. "#ifdef DOUBLE_SIDED",
  8347. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8348. "#endif",
  8349. "#endif",
  8350. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8351. "#ifdef DOUBLE_SIDED",
  8352. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8353. "#endif",
  8354. "}",
  8355. "#endif",
  8356. "#if MAX_POINT_LIGHTS > 0",
  8357. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8358. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8359. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8360. "float lDistance = 1.0;",
  8361. "if ( pointLightDistance[ i ] > 0.0 )",
  8362. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8363. "lVector = normalize( lVector );",
  8364. "float dotProduct = dot( transformedNormal, lVector );",
  8365. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8366. "#ifdef DOUBLE_SIDED",
  8367. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8368. "#ifdef WRAP_AROUND",
  8369. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8370. "#endif",
  8371. "#endif",
  8372. "#ifdef WRAP_AROUND",
  8373. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8374. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8375. "#ifdef DOUBLE_SIDED",
  8376. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8377. "#endif",
  8378. "#endif",
  8379. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8380. "#ifdef DOUBLE_SIDED",
  8381. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8382. "#endif",
  8383. "}",
  8384. "#endif",
  8385. "#if MAX_SPOT_LIGHTS > 0",
  8386. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8387. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8388. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8389. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8390. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8391. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8392. "float lDistance = 1.0;",
  8393. "if ( spotLightDistance[ i ] > 0.0 )",
  8394. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8395. "lVector = normalize( lVector );",
  8396. "float dotProduct = dot( transformedNormal, lVector );",
  8397. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8398. "#ifdef DOUBLE_SIDED",
  8399. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8400. "#ifdef WRAP_AROUND",
  8401. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8402. "#endif",
  8403. "#endif",
  8404. "#ifdef WRAP_AROUND",
  8405. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8406. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8407. "#ifdef DOUBLE_SIDED",
  8408. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8409. "#endif",
  8410. "#endif",
  8411. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8412. "#ifdef DOUBLE_SIDED",
  8413. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8414. "#endif",
  8415. "}",
  8416. "}",
  8417. "#endif",
  8418. "#if MAX_HEMI_LIGHTS > 0",
  8419. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8420. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8421. "vec3 lVector = normalize( lDirection.xyz );",
  8422. "float dotProduct = dot( transformedNormal, lVector );",
  8423. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8424. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8425. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8426. "#ifdef DOUBLE_SIDED",
  8427. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8428. "#endif",
  8429. "}",
  8430. "#endif",
  8431. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8432. "#ifdef DOUBLE_SIDED",
  8433. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8434. "#endif"
  8435. ].join("\n"),
  8436. // LIGHTS PHONG
  8437. lights_phong_pars_vertex: [
  8438. "#ifndef PHONG_PER_PIXEL",
  8439. "#if MAX_POINT_LIGHTS > 0",
  8440. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8441. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8442. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8443. "#endif",
  8444. "#if MAX_SPOT_LIGHTS > 0",
  8445. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8446. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8447. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8448. "#endif",
  8449. "#endif",
  8450. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8451. "varying vec3 vWorldPosition;",
  8452. "#endif"
  8453. ].join("\n"),
  8454. lights_phong_vertex: [
  8455. "#ifndef PHONG_PER_PIXEL",
  8456. "#if MAX_POINT_LIGHTS > 0",
  8457. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8458. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8459. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8460. "float lDistance = 1.0;",
  8461. "if ( pointLightDistance[ i ] > 0.0 )",
  8462. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8463. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8464. "}",
  8465. "#endif",
  8466. "#if MAX_SPOT_LIGHTS > 0",
  8467. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8468. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8469. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8470. "float lDistance = 1.0;",
  8471. "if ( spotLightDistance[ i ] > 0.0 )",
  8472. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8473. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8474. "}",
  8475. "#endif",
  8476. "#endif",
  8477. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8478. "vWorldPosition = worldPosition.xyz;",
  8479. "#endif"
  8480. ].join("\n"),
  8481. lights_phong_pars_fragment: [
  8482. "uniform vec3 ambientLightColor;",
  8483. "#if MAX_DIR_LIGHTS > 0",
  8484. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8485. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8486. "#endif",
  8487. "#if MAX_HEMI_LIGHTS > 0",
  8488. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8489. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8490. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8491. "#endif",
  8492. "#if MAX_POINT_LIGHTS > 0",
  8493. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8494. "#ifdef PHONG_PER_PIXEL",
  8495. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8496. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8497. "#else",
  8498. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8499. "#endif",
  8500. "#endif",
  8501. "#if MAX_SPOT_LIGHTS > 0",
  8502. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8503. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8504. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8505. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8506. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8507. "#ifdef PHONG_PER_PIXEL",
  8508. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8509. "#else",
  8510. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8511. "#endif",
  8512. "#endif",
  8513. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8514. "varying vec3 vWorldPosition;",
  8515. "#endif",
  8516. "#ifdef WRAP_AROUND",
  8517. "uniform vec3 wrapRGB;",
  8518. "#endif",
  8519. "varying vec3 vViewPosition;",
  8520. "varying vec3 vNormal;"
  8521. ].join("\n"),
  8522. lights_phong_fragment: [
  8523. "vec3 normal = normalize( vNormal );",
  8524. "vec3 viewPosition = normalize( vViewPosition );",
  8525. "#ifdef DOUBLE_SIDED",
  8526. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8527. "#endif",
  8528. "#ifdef USE_NORMALMAP",
  8529. "normal = perturbNormal2Arb( -viewPosition, normal );",
  8530. "#elif defined( USE_BUMPMAP )",
  8531. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8532. "#endif",
  8533. "#if MAX_POINT_LIGHTS > 0",
  8534. "vec3 pointDiffuse = vec3( 0.0 );",
  8535. "vec3 pointSpecular = vec3( 0.0 );",
  8536. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8537. "#ifdef PHONG_PER_PIXEL",
  8538. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8539. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8540. "float lDistance = 1.0;",
  8541. "if ( pointLightDistance[ i ] > 0.0 )",
  8542. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8543. "lVector = normalize( lVector );",
  8544. "#else",
  8545. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8546. "float lDistance = vPointLight[ i ].w;",
  8547. "#endif",
  8548. // diffuse
  8549. "float dotProduct = dot( normal, lVector );",
  8550. "#ifdef WRAP_AROUND",
  8551. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8552. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8553. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8554. "#else",
  8555. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8556. "#endif",
  8557. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8558. // specular
  8559. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8560. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8561. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8562. "#ifdef PHYSICALLY_BASED_SHADING",
  8563. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8564. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8565. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8566. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8567. "#else",
  8568. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8569. "#endif",
  8570. "}",
  8571. "#endif",
  8572. "#if MAX_SPOT_LIGHTS > 0",
  8573. "vec3 spotDiffuse = vec3( 0.0 );",
  8574. "vec3 spotSpecular = vec3( 0.0 );",
  8575. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8576. "#ifdef PHONG_PER_PIXEL",
  8577. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8578. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8579. "float lDistance = 1.0;",
  8580. "if ( spotLightDistance[ i ] > 0.0 )",
  8581. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8582. "lVector = normalize( lVector );",
  8583. "#else",
  8584. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8585. "float lDistance = vSpotLight[ i ].w;",
  8586. "#endif",
  8587. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8588. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8589. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8590. // diffuse
  8591. "float dotProduct = dot( normal, lVector );",
  8592. "#ifdef WRAP_AROUND",
  8593. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8594. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8595. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8596. "#else",
  8597. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8598. "#endif",
  8599. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8600. // specular
  8601. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8602. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8603. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8604. "#ifdef PHYSICALLY_BASED_SHADING",
  8605. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8606. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8607. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8608. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8609. "#else",
  8610. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8611. "#endif",
  8612. "}",
  8613. "}",
  8614. "#endif",
  8615. "#if MAX_DIR_LIGHTS > 0",
  8616. "vec3 dirDiffuse = vec3( 0.0 );",
  8617. "vec3 dirSpecular = vec3( 0.0 );" ,
  8618. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8619. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8620. "vec3 dirVector = normalize( lDirection.xyz );",
  8621. // diffuse
  8622. "float dotProduct = dot( normal, dirVector );",
  8623. "#ifdef WRAP_AROUND",
  8624. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8625. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8626. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8627. "#else",
  8628. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8629. "#endif",
  8630. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8631. // specular
  8632. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8633. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8634. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8635. "#ifdef PHYSICALLY_BASED_SHADING",
  8636. /*
  8637. // fresnel term from skin shader
  8638. "const float F0 = 0.128;",
  8639. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8640. "float exponential = pow( base, 5.0 );",
  8641. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8642. */
  8643. /*
  8644. // fresnel term from fresnel shader
  8645. "const float mFresnelBias = 0.08;",
  8646. "const float mFresnelScale = 0.3;",
  8647. "const float mFresnelPower = 5.0;",
  8648. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8649. */
  8650. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8651. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8652. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8653. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8654. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8655. "#else",
  8656. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8657. "#endif",
  8658. "}",
  8659. "#endif",
  8660. "#if MAX_HEMI_LIGHTS > 0",
  8661. "vec3 hemiDiffuse = vec3( 0.0 );",
  8662. "vec3 hemiSpecular = vec3( 0.0 );" ,
  8663. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8664. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8665. "vec3 lVector = normalize( lDirection.xyz );",
  8666. // diffuse
  8667. "float dotProduct = dot( normal, lVector );",
  8668. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8669. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8670. "hemiDiffuse += diffuse * hemiColor;",
  8671. // specular (sky light)
  8672. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  8673. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  8674. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  8675. // specular (ground light)
  8676. "vec3 lVectorGround = -lVector;",
  8677. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  8678. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  8679. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  8680. "#ifdef PHYSICALLY_BASED_SHADING",
  8681. "float dotProductGround = dot( normal, lVectorGround );",
  8682. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8683. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8684. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  8685. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  8686. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  8687. "#else",
  8688. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  8689. "#endif",
  8690. "}",
  8691. "#endif",
  8692. "vec3 totalDiffuse = vec3( 0.0 );",
  8693. "vec3 totalSpecular = vec3( 0.0 );",
  8694. "#if MAX_DIR_LIGHTS > 0",
  8695. "totalDiffuse += dirDiffuse;",
  8696. "totalSpecular += dirSpecular;",
  8697. "#endif",
  8698. "#if MAX_HEMI_LIGHTS > 0",
  8699. "totalDiffuse += hemiDiffuse;",
  8700. "totalSpecular += hemiSpecular;",
  8701. "#endif",
  8702. "#if MAX_POINT_LIGHTS > 0",
  8703. "totalDiffuse += pointDiffuse;",
  8704. "totalSpecular += pointSpecular;",
  8705. "#endif",
  8706. "#if MAX_SPOT_LIGHTS > 0",
  8707. "totalDiffuse += spotDiffuse;",
  8708. "totalSpecular += spotSpecular;",
  8709. "#endif",
  8710. "#ifdef METAL",
  8711. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8712. "#else",
  8713. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8714. "#endif"
  8715. ].join("\n"),
  8716. // VERTEX COLORS
  8717. color_pars_fragment: [
  8718. "#ifdef USE_COLOR",
  8719. "varying vec3 vColor;",
  8720. "#endif"
  8721. ].join("\n"),
  8722. color_fragment: [
  8723. "#ifdef USE_COLOR",
  8724. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8725. "#endif"
  8726. ].join("\n"),
  8727. color_pars_vertex: [
  8728. "#ifdef USE_COLOR",
  8729. "varying vec3 vColor;",
  8730. "#endif"
  8731. ].join("\n"),
  8732. color_vertex: [
  8733. "#ifdef USE_COLOR",
  8734. "#ifdef GAMMA_INPUT",
  8735. "vColor = color * color;",
  8736. "#else",
  8737. "vColor = color;",
  8738. "#endif",
  8739. "#endif"
  8740. ].join("\n"),
  8741. // SKINNING
  8742. skinning_pars_vertex: [
  8743. "#ifdef USE_SKINNING",
  8744. "#ifdef BONE_TEXTURE",
  8745. "uniform sampler2D boneTexture;",
  8746. "mat4 getBoneMatrix( const in float i ) {",
  8747. "float j = i * 4.0;",
  8748. "float x = mod( j, N_BONE_PIXEL_X );",
  8749. "float y = floor( j / N_BONE_PIXEL_X );",
  8750. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8751. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8752. "y = dy * ( y + 0.5 );",
  8753. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8754. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8755. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8756. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8757. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8758. "return bone;",
  8759. "}",
  8760. "#else",
  8761. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8762. "mat4 getBoneMatrix( const in float i ) {",
  8763. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8764. "return bone;",
  8765. "}",
  8766. "#endif",
  8767. "#endif"
  8768. ].join("\n"),
  8769. skinbase_vertex: [
  8770. "#ifdef USE_SKINNING",
  8771. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8772. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8773. "#endif"
  8774. ].join("\n"),
  8775. skinning_vertex: [
  8776. "#ifdef USE_SKINNING",
  8777. "#ifdef USE_MORPHTARGETS",
  8778. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8779. "#else",
  8780. "vec4 skinVertex = vec4( position, 1.0 );",
  8781. "#endif",
  8782. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8783. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8784. "#endif"
  8785. ].join("\n"),
  8786. // MORPHING
  8787. morphtarget_pars_vertex: [
  8788. "#ifdef USE_MORPHTARGETS",
  8789. "#ifndef USE_MORPHNORMALS",
  8790. "uniform float morphTargetInfluences[ 8 ];",
  8791. "#else",
  8792. "uniform float morphTargetInfluences[ 4 ];",
  8793. "#endif",
  8794. "#endif"
  8795. ].join("\n"),
  8796. morphtarget_vertex: [
  8797. "#ifdef USE_MORPHTARGETS",
  8798. "vec3 morphed = vec3( 0.0 );",
  8799. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8800. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8801. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8802. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8803. "#ifndef USE_MORPHNORMALS",
  8804. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8805. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8806. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8807. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8808. "#endif",
  8809. "morphed += position;",
  8810. "#endif"
  8811. ].join("\n"),
  8812. default_vertex : [
  8813. "vec4 mvPosition;",
  8814. "#ifdef USE_SKINNING",
  8815. "mvPosition = modelViewMatrix * skinned;",
  8816. "#endif",
  8817. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  8818. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  8819. "#endif",
  8820. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  8821. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8822. "#endif",
  8823. "gl_Position = projectionMatrix * mvPosition;"
  8824. ].join("\n"),
  8825. morphnormal_vertex: [
  8826. "#ifdef USE_MORPHNORMALS",
  8827. "vec3 morphedNormal = vec3( 0.0 );",
  8828. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8829. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8830. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8831. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8832. "morphedNormal += normal;",
  8833. "#endif"
  8834. ].join("\n"),
  8835. skinnormal_vertex: [
  8836. "#ifdef USE_SKINNING",
  8837. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8838. "skinMatrix += skinWeight.y * boneMatY;",
  8839. "#ifdef USE_MORPHNORMALS",
  8840. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8841. "#else",
  8842. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8843. "#endif",
  8844. "#endif"
  8845. ].join("\n"),
  8846. defaultnormal_vertex: [
  8847. "vec3 objectNormal;",
  8848. "#ifdef USE_SKINNING",
  8849. "objectNormal = skinnedNormal.xyz;",
  8850. "#endif",
  8851. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  8852. "objectNormal = morphedNormal;",
  8853. "#endif",
  8854. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  8855. "objectNormal = normal;",
  8856. "#endif",
  8857. "#ifdef FLIP_SIDED",
  8858. "objectNormal = -objectNormal;",
  8859. "#endif",
  8860. "vec3 transformedNormal = normalMatrix * objectNormal;"
  8861. ].join("\n"),
  8862. // SHADOW MAP
  8863. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8864. // http://spidergl.org/example.php?id=6
  8865. // http://fabiensanglard.net/shadowmapping
  8866. shadowmap_pars_fragment: [
  8867. "#ifdef USE_SHADOWMAP",
  8868. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8869. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8870. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8871. "uniform float shadowBias[ MAX_SHADOWS ];",
  8872. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8873. "float unpackDepth( const in vec4 rgba_depth ) {",
  8874. "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 );",
  8875. "float depth = dot( rgba_depth, bit_shift );",
  8876. "return depth;",
  8877. "}",
  8878. "#endif"
  8879. ].join("\n"),
  8880. shadowmap_fragment: [
  8881. "#ifdef USE_SHADOWMAP",
  8882. "#ifdef SHADOWMAP_DEBUG",
  8883. "vec3 frustumColors[3];",
  8884. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8885. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8886. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8887. "#endif",
  8888. "#ifdef SHADOWMAP_CASCADE",
  8889. "int inFrustumCount = 0;",
  8890. "#endif",
  8891. "float fDepth;",
  8892. "vec3 shadowColor = vec3( 1.0 );",
  8893. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8894. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8895. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8896. // "if ( all( something, something ) )" using this instead
  8897. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8898. "bool inFrustum = all( inFrustumVec );",
  8899. // don't shadow pixels outside of light frustum
  8900. // use just first frustum (for cascades)
  8901. // don't shadow pixels behind far plane of light frustum
  8902. "#ifdef SHADOWMAP_CASCADE",
  8903. "inFrustumCount += int( inFrustum );",
  8904. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8905. "#else",
  8906. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8907. "#endif",
  8908. "bool frustumTest = all( frustumTestVec );",
  8909. "if ( frustumTest ) {",
  8910. "shadowCoord.z += shadowBias[ i ];",
  8911. "#ifdef SHADOWMAP_SOFT",
  8912. // Percentage-close filtering
  8913. // (9 pixel kernel)
  8914. // http://fabiensanglard.net/shadowmappingPCF/
  8915. "float shadow = 0.0;",
  8916. /*
  8917. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8918. // must enroll loop manually
  8919. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8920. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8921. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8922. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8923. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8924. "float fDepth = unpackDepth( rgbaDepth );",
  8925. "if ( fDepth < shadowCoord.z )",
  8926. "shadow += 1.0;",
  8927. "}",
  8928. "shadow /= 9.0;",
  8929. */
  8930. "const float shadowDelta = 1.0 / 9.0;",
  8931. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8932. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8933. "float dx0 = -1.25 * xPixelOffset;",
  8934. "float dy0 = -1.25 * yPixelOffset;",
  8935. "float dx1 = 1.25 * xPixelOffset;",
  8936. "float dy1 = 1.25 * yPixelOffset;",
  8937. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8938. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8939. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8940. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8941. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8942. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8943. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8944. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8945. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8946. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8947. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8948. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8949. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8950. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8951. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8952. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8953. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8954. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8955. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8956. "#else",
  8957. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8958. "float fDepth = unpackDepth( rgbaDepth );",
  8959. "if ( fDepth < shadowCoord.z )",
  8960. // spot with multiple shadows is darker
  8961. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8962. // spot with multiple shadows has the same color as single shadow spot
  8963. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8964. "#endif",
  8965. "}",
  8966. "#ifdef SHADOWMAP_DEBUG",
  8967. "#ifdef SHADOWMAP_CASCADE",
  8968. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8969. "#else",
  8970. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8971. "#endif",
  8972. "#endif",
  8973. "}",
  8974. "#ifdef GAMMA_OUTPUT",
  8975. "shadowColor *= shadowColor;",
  8976. "#endif",
  8977. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8978. "#endif"
  8979. ].join("\n"),
  8980. shadowmap_pars_vertex: [
  8981. "#ifdef USE_SHADOWMAP",
  8982. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8983. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8984. "#endif"
  8985. ].join("\n"),
  8986. shadowmap_vertex: [
  8987. "#ifdef USE_SHADOWMAP",
  8988. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8989. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  8990. "}",
  8991. "#endif"
  8992. ].join("\n"),
  8993. // ALPHATEST
  8994. alphatest_fragment: [
  8995. "#ifdef ALPHATEST",
  8996. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8997. "#endif"
  8998. ].join("\n"),
  8999. // LINEAR SPACE
  9000. linear_to_gamma_fragment: [
  9001. "#ifdef GAMMA_OUTPUT",
  9002. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9003. "#endif"
  9004. ].join("\n")
  9005. };
  9006. THREE.UniformsUtils = {
  9007. merge: function ( uniforms ) {
  9008. var u, p, tmp, merged = {};
  9009. for ( u = 0; u < uniforms.length; u ++ ) {
  9010. tmp = this.clone( uniforms[ u ] );
  9011. for ( p in tmp ) {
  9012. merged[ p ] = tmp[ p ];
  9013. }
  9014. }
  9015. return merged;
  9016. },
  9017. clone: function ( uniforms_src ) {
  9018. var u, p, parameter, parameter_src, uniforms_dst = {};
  9019. for ( u in uniforms_src ) {
  9020. uniforms_dst[ u ] = {};
  9021. for ( p in uniforms_src[ u ] ) {
  9022. parameter_src = uniforms_src[ u ][ p ];
  9023. if ( parameter_src instanceof THREE.Color ||
  9024. parameter_src instanceof THREE.Vector2 ||
  9025. parameter_src instanceof THREE.Vector3 ||
  9026. parameter_src instanceof THREE.Vector4 ||
  9027. parameter_src instanceof THREE.Matrix4 ||
  9028. parameter_src instanceof THREE.Texture ) {
  9029. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9030. } else if ( parameter_src instanceof Array ) {
  9031. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9032. } else {
  9033. uniforms_dst[ u ][ p ] = parameter_src;
  9034. }
  9035. }
  9036. }
  9037. return uniforms_dst;
  9038. }
  9039. };
  9040. THREE.UniformsLib = {
  9041. common: {
  9042. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9043. "opacity" : { type: "f", value: 1.0 },
  9044. "map" : { type: "t", value: null },
  9045. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9046. "lightMap" : { type: "t", value: null },
  9047. "specularMap" : { type: "t", value: null },
  9048. "envMap" : { type: "t", value: null },
  9049. "flipEnvMap" : { type: "f", value: -1 },
  9050. "useRefract" : { type: "i", value: 0 },
  9051. "reflectivity" : { type: "f", value: 1.0 },
  9052. "refractionRatio" : { type: "f", value: 0.98 },
  9053. "combine" : { type: "i", value: 0 },
  9054. "morphTargetInfluences" : { type: "f", value: 0 }
  9055. },
  9056. bump: {
  9057. "bumpMap" : { type: "t", value: null },
  9058. "bumpScale" : { type: "f", value: 1 }
  9059. },
  9060. normalmap: {
  9061. "normalMap" : { type: "t", value: null },
  9062. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9063. },
  9064. fog : {
  9065. "fogDensity" : { type: "f", value: 0.00025 },
  9066. "fogNear" : { type: "f", value: 1 },
  9067. "fogFar" : { type: "f", value: 2000 },
  9068. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9069. },
  9070. lights: {
  9071. "ambientLightColor" : { type: "fv", value: [] },
  9072. "directionalLightDirection" : { type: "fv", value: [] },
  9073. "directionalLightColor" : { type: "fv", value: [] },
  9074. "hemisphereLightDirection" : { type: "fv", value: [] },
  9075. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9076. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9077. "pointLightColor" : { type: "fv", value: [] },
  9078. "pointLightPosition" : { type: "fv", value: [] },
  9079. "pointLightDistance" : { type: "fv1", value: [] },
  9080. "spotLightColor" : { type: "fv", value: [] },
  9081. "spotLightPosition" : { type: "fv", value: [] },
  9082. "spotLightDirection" : { type: "fv", value: [] },
  9083. "spotLightDistance" : { type: "fv1", value: [] },
  9084. "spotLightAngleCos" : { type: "fv1", value: [] },
  9085. "spotLightExponent" : { type: "fv1", value: [] }
  9086. },
  9087. particle: {
  9088. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9089. "opacity" : { type: "f", value: 1.0 },
  9090. "size" : { type: "f", value: 1.0 },
  9091. "scale" : { type: "f", value: 1.0 },
  9092. "map" : { type: "t", value: null },
  9093. "fogDensity" : { type: "f", value: 0.00025 },
  9094. "fogNear" : { type: "f", value: 1 },
  9095. "fogFar" : { type: "f", value: 2000 },
  9096. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9097. },
  9098. shadowmap: {
  9099. "shadowMap": { type: "tv", value: [] },
  9100. "shadowMapSize": { type: "v2v", value: [] },
  9101. "shadowBias" : { type: "fv1", value: [] },
  9102. "shadowDarkness": { type: "fv1", value: [] },
  9103. "shadowMatrix" : { type: "m4v", value: [] }
  9104. }
  9105. };
  9106. THREE.ShaderLib = {
  9107. 'depth': {
  9108. uniforms: {
  9109. "mNear": { type: "f", value: 1.0 },
  9110. "mFar" : { type: "f", value: 2000.0 },
  9111. "opacity" : { type: "f", value: 1.0 }
  9112. },
  9113. vertexShader: [
  9114. "void main() {",
  9115. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9116. "}"
  9117. ].join("\n"),
  9118. fragmentShader: [
  9119. "uniform float mNear;",
  9120. "uniform float mFar;",
  9121. "uniform float opacity;",
  9122. "void main() {",
  9123. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9124. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9125. "gl_FragColor = vec4( vec3( color ), opacity );",
  9126. "}"
  9127. ].join("\n")
  9128. },
  9129. 'normal': {
  9130. uniforms: {
  9131. "opacity" : { type: "f", value: 1.0 }
  9132. },
  9133. vertexShader: [
  9134. "varying vec3 vNormal;",
  9135. "void main() {",
  9136. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9137. "vNormal = normalize( normalMatrix * normal );",
  9138. "gl_Position = projectionMatrix * mvPosition;",
  9139. "}"
  9140. ].join("\n"),
  9141. fragmentShader: [
  9142. "uniform float opacity;",
  9143. "varying vec3 vNormal;",
  9144. "void main() {",
  9145. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9146. "}"
  9147. ].join("\n")
  9148. },
  9149. 'basic': {
  9150. uniforms: THREE.UniformsUtils.merge( [
  9151. THREE.UniformsLib[ "common" ],
  9152. THREE.UniformsLib[ "fog" ],
  9153. THREE.UniformsLib[ "shadowmap" ]
  9154. ] ),
  9155. vertexShader: [
  9156. THREE.ShaderChunk[ "map_pars_vertex" ],
  9157. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9158. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9159. THREE.ShaderChunk[ "color_pars_vertex" ],
  9160. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9161. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9162. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9163. "void main() {",
  9164. THREE.ShaderChunk[ "map_vertex" ],
  9165. THREE.ShaderChunk[ "lightmap_vertex" ],
  9166. THREE.ShaderChunk[ "color_vertex" ],
  9167. "#ifdef USE_ENVMAP",
  9168. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9169. THREE.ShaderChunk[ "skinbase_vertex" ],
  9170. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9171. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9172. "#endif",
  9173. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9174. THREE.ShaderChunk[ "skinning_vertex" ],
  9175. THREE.ShaderChunk[ "default_vertex" ],
  9176. THREE.ShaderChunk[ "worldpos_vertex" ],
  9177. THREE.ShaderChunk[ "envmap_vertex" ],
  9178. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9179. "}"
  9180. ].join("\n"),
  9181. fragmentShader: [
  9182. "uniform vec3 diffuse;",
  9183. "uniform float opacity;",
  9184. THREE.ShaderChunk[ "color_pars_fragment" ],
  9185. THREE.ShaderChunk[ "map_pars_fragment" ],
  9186. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9187. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9188. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9189. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9190. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9191. "void main() {",
  9192. "gl_FragColor = vec4( diffuse, opacity );",
  9193. THREE.ShaderChunk[ "map_fragment" ],
  9194. THREE.ShaderChunk[ "alphatest_fragment" ],
  9195. THREE.ShaderChunk[ "specularmap_fragment" ],
  9196. THREE.ShaderChunk[ "lightmap_fragment" ],
  9197. THREE.ShaderChunk[ "color_fragment" ],
  9198. THREE.ShaderChunk[ "envmap_fragment" ],
  9199. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9200. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9201. THREE.ShaderChunk[ "fog_fragment" ],
  9202. "}"
  9203. ].join("\n")
  9204. },
  9205. 'lambert': {
  9206. uniforms: THREE.UniformsUtils.merge( [
  9207. THREE.UniformsLib[ "common" ],
  9208. THREE.UniformsLib[ "fog" ],
  9209. THREE.UniformsLib[ "lights" ],
  9210. THREE.UniformsLib[ "shadowmap" ],
  9211. {
  9212. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9213. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9214. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9215. }
  9216. ] ),
  9217. vertexShader: [
  9218. "#define LAMBERT",
  9219. "varying vec3 vLightFront;",
  9220. "#ifdef DOUBLE_SIDED",
  9221. "varying vec3 vLightBack;",
  9222. "#endif",
  9223. THREE.ShaderChunk[ "map_pars_vertex" ],
  9224. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9225. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9226. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9227. THREE.ShaderChunk[ "color_pars_vertex" ],
  9228. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9229. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9230. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9231. "void main() {",
  9232. THREE.ShaderChunk[ "map_vertex" ],
  9233. THREE.ShaderChunk[ "lightmap_vertex" ],
  9234. THREE.ShaderChunk[ "color_vertex" ],
  9235. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9236. THREE.ShaderChunk[ "skinbase_vertex" ],
  9237. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9238. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9239. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9240. THREE.ShaderChunk[ "skinning_vertex" ],
  9241. THREE.ShaderChunk[ "default_vertex" ],
  9242. THREE.ShaderChunk[ "worldpos_vertex" ],
  9243. THREE.ShaderChunk[ "envmap_vertex" ],
  9244. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9245. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9246. "}"
  9247. ].join("\n"),
  9248. fragmentShader: [
  9249. "uniform float opacity;",
  9250. "varying vec3 vLightFront;",
  9251. "#ifdef DOUBLE_SIDED",
  9252. "varying vec3 vLightBack;",
  9253. "#endif",
  9254. THREE.ShaderChunk[ "color_pars_fragment" ],
  9255. THREE.ShaderChunk[ "map_pars_fragment" ],
  9256. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9257. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9258. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9259. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9260. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9261. "void main() {",
  9262. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9263. THREE.ShaderChunk[ "map_fragment" ],
  9264. THREE.ShaderChunk[ "alphatest_fragment" ],
  9265. THREE.ShaderChunk[ "specularmap_fragment" ],
  9266. "#ifdef DOUBLE_SIDED",
  9267. //"float isFront = float( gl_FrontFacing );",
  9268. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9269. "if ( gl_FrontFacing )",
  9270. "gl_FragColor.xyz *= vLightFront;",
  9271. "else",
  9272. "gl_FragColor.xyz *= vLightBack;",
  9273. "#else",
  9274. "gl_FragColor.xyz *= vLightFront;",
  9275. "#endif",
  9276. THREE.ShaderChunk[ "lightmap_fragment" ],
  9277. THREE.ShaderChunk[ "color_fragment" ],
  9278. THREE.ShaderChunk[ "envmap_fragment" ],
  9279. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9280. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9281. THREE.ShaderChunk[ "fog_fragment" ],
  9282. "}"
  9283. ].join("\n")
  9284. },
  9285. 'phong': {
  9286. uniforms: THREE.UniformsUtils.merge( [
  9287. THREE.UniformsLib[ "common" ],
  9288. THREE.UniformsLib[ "bump" ],
  9289. THREE.UniformsLib[ "normalmap" ],
  9290. THREE.UniformsLib[ "fog" ],
  9291. THREE.UniformsLib[ "lights" ],
  9292. THREE.UniformsLib[ "shadowmap" ],
  9293. {
  9294. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9295. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9296. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9297. "shininess": { type: "f", value: 30 },
  9298. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9299. }
  9300. ] ),
  9301. vertexShader: [
  9302. "#define PHONG",
  9303. "varying vec3 vViewPosition;",
  9304. "varying vec3 vNormal;",
  9305. THREE.ShaderChunk[ "map_pars_vertex" ],
  9306. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9307. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9308. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9309. THREE.ShaderChunk[ "color_pars_vertex" ],
  9310. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9311. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9312. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9313. "void main() {",
  9314. THREE.ShaderChunk[ "map_vertex" ],
  9315. THREE.ShaderChunk[ "lightmap_vertex" ],
  9316. THREE.ShaderChunk[ "color_vertex" ],
  9317. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9318. THREE.ShaderChunk[ "skinbase_vertex" ],
  9319. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9320. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9321. "vNormal = normalize( transformedNormal );",
  9322. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9323. THREE.ShaderChunk[ "skinning_vertex" ],
  9324. THREE.ShaderChunk[ "default_vertex" ],
  9325. "vViewPosition = -mvPosition.xyz;",
  9326. THREE.ShaderChunk[ "worldpos_vertex" ],
  9327. THREE.ShaderChunk[ "envmap_vertex" ],
  9328. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9329. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9330. "}"
  9331. ].join("\n"),
  9332. fragmentShader: [
  9333. "uniform vec3 diffuse;",
  9334. "uniform float opacity;",
  9335. "uniform vec3 ambient;",
  9336. "uniform vec3 emissive;",
  9337. "uniform vec3 specular;",
  9338. "uniform float shininess;",
  9339. THREE.ShaderChunk[ "color_pars_fragment" ],
  9340. THREE.ShaderChunk[ "map_pars_fragment" ],
  9341. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9342. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9343. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9344. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9345. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9346. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9347. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9348. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9349. "void main() {",
  9350. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9351. THREE.ShaderChunk[ "map_fragment" ],
  9352. THREE.ShaderChunk[ "alphatest_fragment" ],
  9353. THREE.ShaderChunk[ "specularmap_fragment" ],
  9354. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9355. THREE.ShaderChunk[ "lightmap_fragment" ],
  9356. THREE.ShaderChunk[ "color_fragment" ],
  9357. THREE.ShaderChunk[ "envmap_fragment" ],
  9358. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9359. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9360. THREE.ShaderChunk[ "fog_fragment" ],
  9361. "}"
  9362. ].join("\n")
  9363. },
  9364. 'particle_basic': {
  9365. uniforms: THREE.UniformsUtils.merge( [
  9366. THREE.UniformsLib[ "particle" ],
  9367. THREE.UniformsLib[ "shadowmap" ]
  9368. ] ),
  9369. vertexShader: [
  9370. "uniform float size;",
  9371. "uniform float scale;",
  9372. THREE.ShaderChunk[ "color_pars_vertex" ],
  9373. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9374. "void main() {",
  9375. THREE.ShaderChunk[ "color_vertex" ],
  9376. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9377. "#ifdef USE_SIZEATTENUATION",
  9378. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9379. "#else",
  9380. "gl_PointSize = size;",
  9381. "#endif",
  9382. "gl_Position = projectionMatrix * mvPosition;",
  9383. THREE.ShaderChunk[ "worldpos_vertex" ],
  9384. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9385. "}"
  9386. ].join("\n"),
  9387. fragmentShader: [
  9388. "uniform vec3 psColor;",
  9389. "uniform float opacity;",
  9390. THREE.ShaderChunk[ "color_pars_fragment" ],
  9391. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9392. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9393. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9394. "void main() {",
  9395. "gl_FragColor = vec4( psColor, opacity );",
  9396. THREE.ShaderChunk[ "map_particle_fragment" ],
  9397. THREE.ShaderChunk[ "alphatest_fragment" ],
  9398. THREE.ShaderChunk[ "color_fragment" ],
  9399. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9400. THREE.ShaderChunk[ "fog_fragment" ],
  9401. "}"
  9402. ].join("\n")
  9403. },
  9404. 'dashed': {
  9405. uniforms: THREE.UniformsUtils.merge( [
  9406. THREE.UniformsLib[ "common" ],
  9407. THREE.UniformsLib[ "fog" ],
  9408. {
  9409. "scale": { type: "f", value: 1 },
  9410. "dashSize": { type: "f", value: 1 },
  9411. "totalSize": { type: "f", value: 2 }
  9412. }
  9413. ] ),
  9414. vertexShader: [
  9415. "uniform float scale;",
  9416. "attribute float lineDistance;",
  9417. "varying float vLineDistance;",
  9418. THREE.ShaderChunk[ "color_pars_vertex" ],
  9419. "void main() {",
  9420. THREE.ShaderChunk[ "color_vertex" ],
  9421. "vLineDistance = scale * lineDistance;",
  9422. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9423. "gl_Position = projectionMatrix * mvPosition;",
  9424. "}"
  9425. ].join("\n"),
  9426. fragmentShader: [
  9427. "uniform vec3 diffuse;",
  9428. "uniform float opacity;",
  9429. "uniform float dashSize;",
  9430. "uniform float totalSize;",
  9431. "varying float vLineDistance;",
  9432. THREE.ShaderChunk[ "color_pars_fragment" ],
  9433. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9434. "void main() {",
  9435. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  9436. "discard;",
  9437. "}",
  9438. "gl_FragColor = vec4( diffuse, opacity );",
  9439. THREE.ShaderChunk[ "color_fragment" ],
  9440. THREE.ShaderChunk[ "fog_fragment" ],
  9441. "}"
  9442. ].join("\n")
  9443. },
  9444. // Depth encoding into RGBA texture
  9445. // based on SpiderGL shadow map example
  9446. // http://spidergl.org/example.php?id=6
  9447. // originally from
  9448. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  9449. // see also here:
  9450. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  9451. 'depthRGBA': {
  9452. uniforms: {},
  9453. vertexShader: [
  9454. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9455. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9456. "void main() {",
  9457. THREE.ShaderChunk[ "skinbase_vertex" ],
  9458. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9459. THREE.ShaderChunk[ "skinning_vertex" ],
  9460. THREE.ShaderChunk[ "default_vertex" ],
  9461. "}"
  9462. ].join("\n"),
  9463. fragmentShader: [
  9464. "vec4 pack_depth( const in float depth ) {",
  9465. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  9466. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  9467. "vec4 res = fract( depth * bit_shift );",
  9468. "res -= res.xxyz * bit_mask;",
  9469. "return res;",
  9470. "}",
  9471. "void main() {",
  9472. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  9473. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  9474. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  9475. //"gl_FragData[ 0 ] = pack_depth( z );",
  9476. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  9477. "}"
  9478. ].join("\n")
  9479. }
  9480. };
  9481. /**
  9482. * @author supereggbert / http://www.paulbrunt.co.uk/
  9483. * @author mrdoob / http://mrdoob.com/
  9484. * @author alteredq / http://alteredqualia.com/
  9485. * @author szimek / https://github.com/szimek/
  9486. */
  9487. THREE.WebGLRenderer = function ( parameters ) {
  9488. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9489. parameters = parameters || {};
  9490. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  9491. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  9492. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  9493. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  9494. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  9495. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  9496. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  9497. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  9498. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  9499. // public properties
  9500. this.domElement = _canvas;
  9501. this.context = null;
  9502. // clearing
  9503. this.autoClear = true;
  9504. this.autoClearColor = true;
  9505. this.autoClearDepth = true;
  9506. this.autoClearStencil = true;
  9507. // scene graph
  9508. this.sortObjects = true;
  9509. this.autoUpdateObjects = true;
  9510. this.autoUpdateScene = true;
  9511. // physically based shading
  9512. this.gammaInput = false;
  9513. this.gammaOutput = false;
  9514. this.physicallyBasedShading = false;
  9515. // shadow map
  9516. this.shadowMapEnabled = false;
  9517. this.shadowMapAutoUpdate = true;
  9518. this.shadowMapSoft = true;
  9519. this.shadowMapCullFace = THREE.CullFaceFront;
  9520. this.shadowMapDebug = false;
  9521. this.shadowMapCascade = false;
  9522. // morphs
  9523. this.maxMorphTargets = 8;
  9524. this.maxMorphNormals = 4;
  9525. // flags
  9526. this.autoScaleCubemaps = true;
  9527. // custom render plugins
  9528. this.renderPluginsPre = [];
  9529. this.renderPluginsPost = [];
  9530. // info
  9531. this.info = {
  9532. memory: {
  9533. programs: 0,
  9534. geometries: 0,
  9535. textures: 0
  9536. },
  9537. render: {
  9538. calls: 0,
  9539. vertices: 0,
  9540. faces: 0,
  9541. points: 0
  9542. }
  9543. };
  9544. // internal properties
  9545. var _this = this,
  9546. _programs = [],
  9547. _programs_counter = 0,
  9548. // internal state cache
  9549. _currentProgram = null,
  9550. _currentFramebuffer = null,
  9551. _currentMaterialId = -1,
  9552. _currentGeometryGroupHash = null,
  9553. _currentCamera = null,
  9554. _geometryGroupCounter = 0,
  9555. _usedTextureUnits = 0,
  9556. // GL state cache
  9557. _oldDoubleSided = -1,
  9558. _oldFlipSided = -1,
  9559. _oldBlending = -1,
  9560. _oldBlendEquation = -1,
  9561. _oldBlendSrc = -1,
  9562. _oldBlendDst = -1,
  9563. _oldDepthTest = -1,
  9564. _oldDepthWrite = -1,
  9565. _oldPolygonOffset = null,
  9566. _oldPolygonOffsetFactor = null,
  9567. _oldPolygonOffsetUnits = null,
  9568. _oldLineWidth = null,
  9569. _viewportX = 0,
  9570. _viewportY = 0,
  9571. _viewportWidth = 0,
  9572. _viewportHeight = 0,
  9573. _currentWidth = 0,
  9574. _currentHeight = 0,
  9575. _enabledAttributes = {},
  9576. // frustum
  9577. _frustum = new THREE.Frustum(),
  9578. // camera matrices cache
  9579. _projScreenMatrix = new THREE.Matrix4(),
  9580. _projScreenMatrixPS = new THREE.Matrix4(),
  9581. _vector3 = new THREE.Vector3(),
  9582. // light arrays cache
  9583. _direction = new THREE.Vector3(),
  9584. _lightsNeedUpdate = true,
  9585. _lights = {
  9586. ambient: [ 0, 0, 0 ],
  9587. directional: { length: 0, colors: new Array(), positions: new Array() },
  9588. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9589. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  9590. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  9591. };
  9592. // initialize
  9593. var _gl;
  9594. var _glExtensionTextureFloat;
  9595. var _glExtensionStandardDerivatives;
  9596. var _glExtensionTextureFilterAnisotropic;
  9597. var _glExtensionCompressedTextureS3TC;
  9598. initGL();
  9599. setDefaultGLState();
  9600. this.context = _gl;
  9601. // GPU capabilities
  9602. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  9603. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9604. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9605. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9606. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9607. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9608. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9609. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  9610. // API
  9611. this.getContext = function () {
  9612. return _gl;
  9613. };
  9614. this.supportsVertexTextures = function () {
  9615. return _supportsVertexTextures;
  9616. };
  9617. this.getMaxAnisotropy = function () {
  9618. return _maxAnisotropy;
  9619. };
  9620. this.setSize = function ( width, height ) {
  9621. _canvas.width = width;
  9622. _canvas.height = height;
  9623. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9624. };
  9625. this.setViewport = function ( x, y, width, height ) {
  9626. _viewportX = x !== undefined ? x : 0;
  9627. _viewportY = y !== undefined ? y : 0;
  9628. _viewportWidth = width !== undefined ? width : _canvas.width;
  9629. _viewportHeight = height !== undefined ? height : _canvas.height;
  9630. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9631. };
  9632. this.setScissor = function ( x, y, width, height ) {
  9633. _gl.scissor( x, y, width, height );
  9634. };
  9635. this.enableScissorTest = function ( enable ) {
  9636. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9637. };
  9638. // Clearing
  9639. this.setClearColorHex = function ( hex, alpha ) {
  9640. _clearColor.setHex( hex );
  9641. _clearAlpha = alpha;
  9642. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9643. };
  9644. this.setClearColor = function ( color, alpha ) {
  9645. _clearColor.copy( color );
  9646. _clearAlpha = alpha;
  9647. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9648. };
  9649. this.getClearColor = function () {
  9650. return _clearColor;
  9651. };
  9652. this.getClearAlpha = function () {
  9653. return _clearAlpha;
  9654. };
  9655. this.clear = function ( color, depth, stencil ) {
  9656. var bits = 0;
  9657. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9658. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9659. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9660. _gl.clear( bits );
  9661. };
  9662. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9663. this.setRenderTarget( renderTarget );
  9664. this.clear( color, depth, stencil );
  9665. };
  9666. // Plugins
  9667. this.addPostPlugin = function ( plugin ) {
  9668. plugin.init( this );
  9669. this.renderPluginsPost.push( plugin );
  9670. };
  9671. this.addPrePlugin = function ( plugin ) {
  9672. plugin.init( this );
  9673. this.renderPluginsPre.push( plugin );
  9674. };
  9675. // Deallocation
  9676. this.deallocateObject = function ( object ) {
  9677. if ( ! object.__webglInit ) return;
  9678. object.__webglInit = false;
  9679. delete object._modelViewMatrix;
  9680. delete object._normalMatrix;
  9681. if ( object instanceof THREE.Mesh ) {
  9682. for ( var g in object.geometry.geometryGroups ) {
  9683. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9684. }
  9685. } else if ( object instanceof THREE.Ribbon ) {
  9686. deleteRibbonBuffers( object.geometry );
  9687. } else if ( object instanceof THREE.Line ) {
  9688. deleteLineBuffers( object.geometry );
  9689. } else if ( object instanceof THREE.ParticleSystem ) {
  9690. deleteParticleBuffers( object.geometry );
  9691. }
  9692. };
  9693. this.deallocateTexture = function ( texture ) {
  9694. // cube texture
  9695. if ( texture.image && texture.image.__webglTextureCube ) {
  9696. _gl.deleteTexture( texture.image.__webglTextureCube );
  9697. // 2D texture
  9698. } else {
  9699. if ( ! texture.__webglInit ) return;
  9700. texture.__webglInit = false;
  9701. _gl.deleteTexture( texture.__webglTexture );
  9702. }
  9703. _this.info.memory.textures --;
  9704. };
  9705. this.deallocateRenderTarget = function ( renderTarget ) {
  9706. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9707. _gl.deleteTexture( renderTarget.__webglTexture );
  9708. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9709. for ( var i = 0; i < 6; i ++ ) {
  9710. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9711. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9712. }
  9713. } else {
  9714. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9715. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9716. }
  9717. };
  9718. this.deallocateMaterial = function ( material ) {
  9719. var program = material.program;
  9720. if ( ! program ) return;
  9721. material.program = undefined;
  9722. // only deallocate GL program if this was the last use of shared program
  9723. // assumed there is only single copy of any program in the _programs list
  9724. // (that's how it's constructed)
  9725. var i, il, programInfo;
  9726. var deleteProgram = false;
  9727. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9728. programInfo = _programs[ i ];
  9729. if ( programInfo.program === program ) {
  9730. programInfo.usedTimes --;
  9731. if ( programInfo.usedTimes === 0 ) {
  9732. deleteProgram = true;
  9733. }
  9734. break;
  9735. }
  9736. }
  9737. if ( deleteProgram ) {
  9738. // avoid using array.splice, this is costlier than creating new array from scratch
  9739. var newPrograms = [];
  9740. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9741. programInfo = _programs[ i ];
  9742. if ( programInfo.program !== program ) {
  9743. newPrograms.push( programInfo );
  9744. }
  9745. }
  9746. _programs = newPrograms;
  9747. _gl.deleteProgram( program );
  9748. _this.info.memory.programs --;
  9749. }
  9750. };
  9751. // Rendering
  9752. this.updateShadowMap = function ( scene, camera ) {
  9753. _currentProgram = null;
  9754. _oldBlending = -1;
  9755. _oldDepthTest = -1;
  9756. _oldDepthWrite = -1;
  9757. _currentGeometryGroupHash = -1;
  9758. _currentMaterialId = -1;
  9759. _lightsNeedUpdate = true;
  9760. _oldDoubleSided = -1;
  9761. _oldFlipSided = -1;
  9762. this.shadowMapPlugin.update( scene, camera );
  9763. };
  9764. // Internal functions
  9765. // Buffer allocation
  9766. function createParticleBuffers ( geometry ) {
  9767. geometry.__webglVertexBuffer = _gl.createBuffer();
  9768. geometry.__webglColorBuffer = _gl.createBuffer();
  9769. _this.info.memory.geometries ++;
  9770. };
  9771. function createLineBuffers ( geometry ) {
  9772. geometry.__webglVertexBuffer = _gl.createBuffer();
  9773. geometry.__webglColorBuffer = _gl.createBuffer();
  9774. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  9775. _this.info.memory.geometries ++;
  9776. };
  9777. function createRibbonBuffers ( geometry ) {
  9778. geometry.__webglVertexBuffer = _gl.createBuffer();
  9779. geometry.__webglColorBuffer = _gl.createBuffer();
  9780. geometry.__webglNormalBuffer = _gl.createBuffer();
  9781. _this.info.memory.geometries ++;
  9782. };
  9783. function createMeshBuffers ( geometryGroup ) {
  9784. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9785. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9786. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9787. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9788. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9789. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9790. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9791. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9792. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9793. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9794. var m, ml;
  9795. if ( geometryGroup.numMorphTargets ) {
  9796. geometryGroup.__webglMorphTargetsBuffers = [];
  9797. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9798. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9799. }
  9800. }
  9801. if ( geometryGroup.numMorphNormals ) {
  9802. geometryGroup.__webglMorphNormalsBuffers = [];
  9803. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9804. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9805. }
  9806. }
  9807. _this.info.memory.geometries ++;
  9808. };
  9809. // Buffer deallocation
  9810. function deleteParticleBuffers ( geometry ) {
  9811. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9812. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9813. deleteCustomAttributesBuffers( geometry );
  9814. _this.info.memory.geometries --;
  9815. };
  9816. function deleteLineBuffers ( geometry ) {
  9817. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9818. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9819. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  9820. deleteCustomAttributesBuffers( geometry );
  9821. _this.info.memory.geometries --;
  9822. };
  9823. function deleteRibbonBuffers ( geometry ) {
  9824. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9825. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9826. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  9827. deleteCustomAttributesBuffers( geometry );
  9828. _this.info.memory.geometries --;
  9829. };
  9830. function deleteMeshBuffers ( geometryGroup ) {
  9831. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9832. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9833. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9834. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9835. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9836. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9837. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9838. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9839. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9840. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9841. var m, ml;
  9842. if ( geometryGroup.numMorphTargets ) {
  9843. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9844. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9845. }
  9846. }
  9847. if ( geometryGroup.numMorphNormals ) {
  9848. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9849. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9850. }
  9851. }
  9852. deleteCustomAttributesBuffers( geometryGroup );
  9853. _this.info.memory.geometries --;
  9854. };
  9855. function deleteCustomAttributesBuffers( geometry ) {
  9856. if ( geometry.__webglCustomAttributesList ) {
  9857. for ( var id in geometry.__webglCustomAttributesList ) {
  9858. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  9859. }
  9860. }
  9861. };
  9862. // Buffer initialization
  9863. function initCustomAttributes ( geometry, object ) {
  9864. var nvertices = geometry.vertices.length;
  9865. var material = object.material;
  9866. if ( material.attributes ) {
  9867. if ( geometry.__webglCustomAttributesList === undefined ) {
  9868. geometry.__webglCustomAttributesList = [];
  9869. }
  9870. for ( var a in material.attributes ) {
  9871. var attribute = material.attributes[ a ];
  9872. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9873. attribute.__webglInitialized = true;
  9874. var size = 1; // "f" and "i"
  9875. if ( attribute.type === "v2" ) size = 2;
  9876. else if ( attribute.type === "v3" ) size = 3;
  9877. else if ( attribute.type === "v4" ) size = 4;
  9878. else if ( attribute.type === "c" ) size = 3;
  9879. attribute.size = size;
  9880. attribute.array = new Float32Array( nvertices * size );
  9881. attribute.buffer = _gl.createBuffer();
  9882. attribute.buffer.belongsToAttribute = a;
  9883. attribute.needsUpdate = true;
  9884. }
  9885. geometry.__webglCustomAttributesList.push( attribute );
  9886. }
  9887. }
  9888. };
  9889. function initParticleBuffers ( geometry, object ) {
  9890. var nvertices = geometry.vertices.length;
  9891. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9892. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9893. geometry.__sortArray = [];
  9894. geometry.__webglParticleCount = nvertices;
  9895. initCustomAttributes ( geometry, object );
  9896. };
  9897. function initLineBuffers ( geometry, object ) {
  9898. var nvertices = geometry.vertices.length;
  9899. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9900. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9901. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  9902. geometry.__webglLineCount = nvertices;
  9903. initCustomAttributes ( geometry, object );
  9904. };
  9905. function initRibbonBuffers ( geometry, object ) {
  9906. var nvertices = geometry.vertices.length;
  9907. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9908. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9909. geometry.__normalArray = new Float32Array( nvertices * 3 );
  9910. geometry.__webglVertexCount = nvertices;
  9911. initCustomAttributes ( geometry, object );
  9912. };
  9913. function initMeshBuffers ( geometryGroup, object ) {
  9914. var geometry = object.geometry,
  9915. faces3 = geometryGroup.faces3,
  9916. faces4 = geometryGroup.faces4,
  9917. nvertices = faces3.length * 3 + faces4.length * 4,
  9918. ntris = faces3.length * 1 + faces4.length * 2,
  9919. nlines = faces3.length * 3 + faces4.length * 4,
  9920. material = getBufferMaterial( object, geometryGroup ),
  9921. uvType = bufferGuessUVType( material ),
  9922. normalType = bufferGuessNormalType( material ),
  9923. vertexColorType = bufferGuessVertexColorType( material );
  9924. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9925. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9926. if ( normalType ) {
  9927. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9928. }
  9929. if ( geometry.hasTangents ) {
  9930. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9931. }
  9932. if ( vertexColorType ) {
  9933. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9934. }
  9935. if ( uvType ) {
  9936. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9937. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9938. }
  9939. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9940. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9941. }
  9942. }
  9943. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9944. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9945. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9946. }
  9947. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9948. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9949. var m, ml;
  9950. if ( geometryGroup.numMorphTargets ) {
  9951. geometryGroup.__morphTargetsArrays = [];
  9952. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9953. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9954. }
  9955. }
  9956. if ( geometryGroup.numMorphNormals ) {
  9957. geometryGroup.__morphNormalsArrays = [];
  9958. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9959. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9960. }
  9961. }
  9962. geometryGroup.__webglFaceCount = ntris * 3;
  9963. geometryGroup.__webglLineCount = nlines * 2;
  9964. // custom attributes
  9965. if ( material.attributes ) {
  9966. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9967. geometryGroup.__webglCustomAttributesList = [];
  9968. }
  9969. for ( var a in material.attributes ) {
  9970. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9971. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9972. var originalAttribute = material.attributes[ a ];
  9973. var attribute = {};
  9974. for ( var property in originalAttribute ) {
  9975. attribute[ property ] = originalAttribute[ property ];
  9976. }
  9977. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9978. attribute.__webglInitialized = true;
  9979. var size = 1; // "f" and "i"
  9980. if( attribute.type === "v2" ) size = 2;
  9981. else if( attribute.type === "v3" ) size = 3;
  9982. else if( attribute.type === "v4" ) size = 4;
  9983. else if( attribute.type === "c" ) size = 3;
  9984. attribute.size = size;
  9985. attribute.array = new Float32Array( nvertices * size );
  9986. attribute.buffer = _gl.createBuffer();
  9987. attribute.buffer.belongsToAttribute = a;
  9988. originalAttribute.needsUpdate = true;
  9989. attribute.__original = originalAttribute;
  9990. }
  9991. geometryGroup.__webglCustomAttributesList.push( attribute );
  9992. }
  9993. }
  9994. geometryGroup.__inittedArrays = true;
  9995. };
  9996. function getBufferMaterial( object, geometryGroup ) {
  9997. return object.material instanceof THREE.MeshFaceMaterial
  9998. ? object.material.materials[ geometryGroup.materialIndex ]
  9999. : object.material;
  10000. };
  10001. function materialNeedsSmoothNormals ( material ) {
  10002. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  10003. };
  10004. function bufferGuessNormalType ( material ) {
  10005. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  10006. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  10007. return false;
  10008. }
  10009. if ( materialNeedsSmoothNormals( material ) ) {
  10010. return THREE.SmoothShading;
  10011. } else {
  10012. return THREE.FlatShading;
  10013. }
  10014. };
  10015. function bufferGuessVertexColorType ( material ) {
  10016. if ( material.vertexColors ) {
  10017. return material.vertexColors;
  10018. }
  10019. return false;
  10020. };
  10021. function bufferGuessUVType ( material ) {
  10022. // material must use some texture to require uvs
  10023. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  10024. return true;
  10025. }
  10026. return false;
  10027. };
  10028. //
  10029. function initDirectBuffers( geometry ) {
  10030. var a, attribute, type;
  10031. for ( a in geometry.attributes ) {
  10032. if ( a === "index" ) {
  10033. type = _gl.ELEMENT_ARRAY_BUFFER;
  10034. } else {
  10035. type = _gl.ARRAY_BUFFER;
  10036. }
  10037. attribute = geometry.attributes[ a ];
  10038. attribute.buffer = _gl.createBuffer();
  10039. _gl.bindBuffer( type, attribute.buffer );
  10040. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  10041. }
  10042. };
  10043. // Buffer setting
  10044. function setParticleBuffers ( geometry, hint, object ) {
  10045. var v, c, vertex, offset, index, color,
  10046. vertices = geometry.vertices,
  10047. vl = vertices.length,
  10048. colors = geometry.colors,
  10049. cl = colors.length,
  10050. vertexArray = geometry.__vertexArray,
  10051. colorArray = geometry.__colorArray,
  10052. sortArray = geometry.__sortArray,
  10053. dirtyVertices = geometry.verticesNeedUpdate,
  10054. dirtyElements = geometry.elementsNeedUpdate,
  10055. dirtyColors = geometry.colorsNeedUpdate,
  10056. customAttributes = geometry.__webglCustomAttributesList,
  10057. i, il,
  10058. a, ca, cal, value,
  10059. customAttribute;
  10060. if ( object.sortParticles ) {
  10061. _projScreenMatrixPS.copy( _projScreenMatrix );
  10062. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  10063. for ( v = 0; v < vl; v ++ ) {
  10064. vertex = vertices[ v ];
  10065. _vector3.copy( vertex );
  10066. _projScreenMatrixPS.multiplyVector3( _vector3 );
  10067. sortArray[ v ] = [ _vector3.z, v ];
  10068. }
  10069. sortArray.sort( numericalSort );
  10070. for ( v = 0; v < vl; v ++ ) {
  10071. vertex = vertices[ sortArray[v][1] ];
  10072. offset = v * 3;
  10073. vertexArray[ offset ] = vertex.x;
  10074. vertexArray[ offset + 1 ] = vertex.y;
  10075. vertexArray[ offset + 2 ] = vertex.z;
  10076. }
  10077. for ( c = 0; c < cl; c ++ ) {
  10078. offset = c * 3;
  10079. color = colors[ sortArray[c][1] ];
  10080. colorArray[ offset ] = color.r;
  10081. colorArray[ offset + 1 ] = color.g;
  10082. colorArray[ offset + 2 ] = color.b;
  10083. }
  10084. if ( customAttributes ) {
  10085. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10086. customAttribute = customAttributes[ i ];
  10087. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10088. offset = 0;
  10089. cal = customAttribute.value.length;
  10090. if ( customAttribute.size === 1 ) {
  10091. for ( ca = 0; ca < cal; ca ++ ) {
  10092. index = sortArray[ ca ][ 1 ];
  10093. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10094. }
  10095. } else if ( customAttribute.size === 2 ) {
  10096. for ( ca = 0; ca < cal; ca ++ ) {
  10097. index = sortArray[ ca ][ 1 ];
  10098. value = customAttribute.value[ index ];
  10099. customAttribute.array[ offset ] = value.x;
  10100. customAttribute.array[ offset + 1 ] = value.y;
  10101. offset += 2;
  10102. }
  10103. } else if ( customAttribute.size === 3 ) {
  10104. if ( customAttribute.type === "c" ) {
  10105. for ( ca = 0; ca < cal; ca ++ ) {
  10106. index = sortArray[ ca ][ 1 ];
  10107. value = customAttribute.value[ index ];
  10108. customAttribute.array[ offset ] = value.r;
  10109. customAttribute.array[ offset + 1 ] = value.g;
  10110. customAttribute.array[ offset + 2 ] = value.b;
  10111. offset += 3;
  10112. }
  10113. } else {
  10114. for ( ca = 0; ca < cal; ca ++ ) {
  10115. index = sortArray[ ca ][ 1 ];
  10116. value = customAttribute.value[ index ];
  10117. customAttribute.array[ offset ] = value.x;
  10118. customAttribute.array[ offset + 1 ] = value.y;
  10119. customAttribute.array[ offset + 2 ] = value.z;
  10120. offset += 3;
  10121. }
  10122. }
  10123. } else if ( customAttribute.size === 4 ) {
  10124. for ( ca = 0; ca < cal; ca ++ ) {
  10125. index = sortArray[ ca ][ 1 ];
  10126. value = customAttribute.value[ index ];
  10127. customAttribute.array[ offset ] = value.x;
  10128. customAttribute.array[ offset + 1 ] = value.y;
  10129. customAttribute.array[ offset + 2 ] = value.z;
  10130. customAttribute.array[ offset + 3 ] = value.w;
  10131. offset += 4;
  10132. }
  10133. }
  10134. }
  10135. }
  10136. } else {
  10137. if ( dirtyVertices ) {
  10138. for ( v = 0; v < vl; v ++ ) {
  10139. vertex = vertices[ v ];
  10140. offset = v * 3;
  10141. vertexArray[ offset ] = vertex.x;
  10142. vertexArray[ offset + 1 ] = vertex.y;
  10143. vertexArray[ offset + 2 ] = vertex.z;
  10144. }
  10145. }
  10146. if ( dirtyColors ) {
  10147. for ( c = 0; c < cl; c ++ ) {
  10148. color = colors[ c ];
  10149. offset = c * 3;
  10150. colorArray[ offset ] = color.r;
  10151. colorArray[ offset + 1 ] = color.g;
  10152. colorArray[ offset + 2 ] = color.b;
  10153. }
  10154. }
  10155. if ( customAttributes ) {
  10156. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10157. customAttribute = customAttributes[ i ];
  10158. if ( customAttribute.needsUpdate &&
  10159. ( customAttribute.boundTo === undefined ||
  10160. customAttribute.boundTo === "vertices") ) {
  10161. cal = customAttribute.value.length;
  10162. offset = 0;
  10163. if ( customAttribute.size === 1 ) {
  10164. for ( ca = 0; ca < cal; ca ++ ) {
  10165. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10166. }
  10167. } else if ( customAttribute.size === 2 ) {
  10168. for ( ca = 0; ca < cal; ca ++ ) {
  10169. value = customAttribute.value[ ca ];
  10170. customAttribute.array[ offset ] = value.x;
  10171. customAttribute.array[ offset + 1 ] = value.y;
  10172. offset += 2;
  10173. }
  10174. } else if ( customAttribute.size === 3 ) {
  10175. if ( customAttribute.type === "c" ) {
  10176. for ( ca = 0; ca < cal; ca ++ ) {
  10177. value = customAttribute.value[ ca ];
  10178. customAttribute.array[ offset ] = value.r;
  10179. customAttribute.array[ offset + 1 ] = value.g;
  10180. customAttribute.array[ offset + 2 ] = value.b;
  10181. offset += 3;
  10182. }
  10183. } else {
  10184. for ( ca = 0; ca < cal; ca ++ ) {
  10185. value = customAttribute.value[ ca ];
  10186. customAttribute.array[ offset ] = value.x;
  10187. customAttribute.array[ offset + 1 ] = value.y;
  10188. customAttribute.array[ offset + 2 ] = value.z;
  10189. offset += 3;
  10190. }
  10191. }
  10192. } else if ( customAttribute.size === 4 ) {
  10193. for ( ca = 0; ca < cal; ca ++ ) {
  10194. value = customAttribute.value[ ca ];
  10195. customAttribute.array[ offset ] = value.x;
  10196. customAttribute.array[ offset + 1 ] = value.y;
  10197. customAttribute.array[ offset + 2 ] = value.z;
  10198. customAttribute.array[ offset + 3 ] = value.w;
  10199. offset += 4;
  10200. }
  10201. }
  10202. }
  10203. }
  10204. }
  10205. }
  10206. if ( dirtyVertices || object.sortParticles ) {
  10207. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10208. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10209. }
  10210. if ( dirtyColors || object.sortParticles ) {
  10211. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10212. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10213. }
  10214. if ( customAttributes ) {
  10215. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10216. customAttribute = customAttributes[ i ];
  10217. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10218. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10219. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10220. }
  10221. }
  10222. }
  10223. };
  10224. function setLineBuffers ( geometry, hint ) {
  10225. var v, c, d, vertex, offset, color,
  10226. vertices = geometry.vertices,
  10227. colors = geometry.colors,
  10228. lineDistances = geometry.lineDistances,
  10229. vl = vertices.length,
  10230. cl = colors.length,
  10231. dl = lineDistances.length,
  10232. vertexArray = geometry.__vertexArray,
  10233. colorArray = geometry.__colorArray,
  10234. lineDistanceArray = geometry.__lineDistanceArray,
  10235. dirtyVertices = geometry.verticesNeedUpdate,
  10236. dirtyColors = geometry.colorsNeedUpdate,
  10237. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10238. customAttributes = geometry.__webglCustomAttributesList,
  10239. i, il,
  10240. a, ca, cal, value,
  10241. customAttribute;
  10242. if ( dirtyVertices ) {
  10243. for ( v = 0; v < vl; v ++ ) {
  10244. vertex = vertices[ v ];
  10245. offset = v * 3;
  10246. vertexArray[ offset ] = vertex.x;
  10247. vertexArray[ offset + 1 ] = vertex.y;
  10248. vertexArray[ offset + 2 ] = vertex.z;
  10249. }
  10250. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10251. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10252. }
  10253. if ( dirtyColors ) {
  10254. for ( c = 0; c < cl; c ++ ) {
  10255. color = colors[ c ];
  10256. offset = c * 3;
  10257. colorArray[ offset ] = color.r;
  10258. colorArray[ offset + 1 ] = color.g;
  10259. colorArray[ offset + 2 ] = color.b;
  10260. }
  10261. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10262. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10263. }
  10264. if ( dirtyLineDistances ) {
  10265. for ( d = 0; d < dl; d ++ ) {
  10266. lineDistanceArray[ d ] = lineDistances[ d ];
  10267. }
  10268. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10269. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10270. }
  10271. if ( customAttributes ) {
  10272. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10273. customAttribute = customAttributes[ i ];
  10274. if ( customAttribute.needsUpdate &&
  10275. ( customAttribute.boundTo === undefined ||
  10276. customAttribute.boundTo === "vertices" ) ) {
  10277. offset = 0;
  10278. cal = customAttribute.value.length;
  10279. if ( customAttribute.size === 1 ) {
  10280. for ( ca = 0; ca < cal; ca ++ ) {
  10281. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10282. }
  10283. } else if ( customAttribute.size === 2 ) {
  10284. for ( ca = 0; ca < cal; ca ++ ) {
  10285. value = customAttribute.value[ ca ];
  10286. customAttribute.array[ offset ] = value.x;
  10287. customAttribute.array[ offset + 1 ] = value.y;
  10288. offset += 2;
  10289. }
  10290. } else if ( customAttribute.size === 3 ) {
  10291. if ( customAttribute.type === "c" ) {
  10292. for ( ca = 0; ca < cal; ca ++ ) {
  10293. value = customAttribute.value[ ca ];
  10294. customAttribute.array[ offset ] = value.r;
  10295. customAttribute.array[ offset + 1 ] = value.g;
  10296. customAttribute.array[ offset + 2 ] = value.b;
  10297. offset += 3;
  10298. }
  10299. } else {
  10300. for ( ca = 0; ca < cal; ca ++ ) {
  10301. value = customAttribute.value[ ca ];
  10302. customAttribute.array[ offset ] = value.x;
  10303. customAttribute.array[ offset + 1 ] = value.y;
  10304. customAttribute.array[ offset + 2 ] = value.z;
  10305. offset += 3;
  10306. }
  10307. }
  10308. } else if ( customAttribute.size === 4 ) {
  10309. for ( ca = 0; ca < cal; ca ++ ) {
  10310. value = customAttribute.value[ ca ];
  10311. customAttribute.array[ offset ] = value.x;
  10312. customAttribute.array[ offset + 1 ] = value.y;
  10313. customAttribute.array[ offset + 2 ] = value.z;
  10314. customAttribute.array[ offset + 3 ] = value.w;
  10315. offset += 4;
  10316. }
  10317. }
  10318. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10319. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10320. }
  10321. }
  10322. }
  10323. };
  10324. function setRibbonBuffers ( geometry, hint ) {
  10325. var v, c, n, vertex, offset, color, normal,
  10326. i, il, ca, cal, customAttribute, value,
  10327. vertices = geometry.vertices,
  10328. colors = geometry.colors,
  10329. normals = geometry.normals,
  10330. vl = vertices.length,
  10331. cl = colors.length,
  10332. nl = normals.length,
  10333. vertexArray = geometry.__vertexArray,
  10334. colorArray = geometry.__colorArray,
  10335. normalArray = geometry.__normalArray,
  10336. dirtyVertices = geometry.verticesNeedUpdate,
  10337. dirtyColors = geometry.colorsNeedUpdate,
  10338. dirtyNormals = geometry.normalsNeedUpdate,
  10339. customAttributes = geometry.__webglCustomAttributesList;
  10340. if ( dirtyVertices ) {
  10341. for ( v = 0; v < vl; v ++ ) {
  10342. vertex = vertices[ v ];
  10343. offset = v * 3;
  10344. vertexArray[ offset ] = vertex.x;
  10345. vertexArray[ offset + 1 ] = vertex.y;
  10346. vertexArray[ offset + 2 ] = vertex.z;
  10347. }
  10348. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10349. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10350. }
  10351. if ( dirtyColors ) {
  10352. for ( c = 0; c < cl; c ++ ) {
  10353. color = colors[ c ];
  10354. offset = c * 3;
  10355. colorArray[ offset ] = color.r;
  10356. colorArray[ offset + 1 ] = color.g;
  10357. colorArray[ offset + 2 ] = color.b;
  10358. }
  10359. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10360. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10361. }
  10362. if ( dirtyNormals ) {
  10363. for ( n = 0; n < nl; n ++ ) {
  10364. normal = normals[ n ];
  10365. offset = n * 3;
  10366. normalArray[ offset ] = normal.x;
  10367. normalArray[ offset + 1 ] = normal.y;
  10368. normalArray[ offset + 2 ] = normal.z;
  10369. }
  10370. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  10371. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10372. }
  10373. if ( customAttributes ) {
  10374. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10375. customAttribute = customAttributes[ i ];
  10376. if ( customAttribute.needsUpdate &&
  10377. ( customAttribute.boundTo === undefined ||
  10378. customAttribute.boundTo === "vertices" ) ) {
  10379. offset = 0;
  10380. cal = customAttribute.value.length;
  10381. if ( customAttribute.size === 1 ) {
  10382. for ( ca = 0; ca < cal; ca ++ ) {
  10383. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10384. }
  10385. } else if ( customAttribute.size === 2 ) {
  10386. for ( ca = 0; ca < cal; ca ++ ) {
  10387. value = customAttribute.value[ ca ];
  10388. customAttribute.array[ offset ] = value.x;
  10389. customAttribute.array[ offset + 1 ] = value.y;
  10390. offset += 2;
  10391. }
  10392. } else if ( customAttribute.size === 3 ) {
  10393. if ( customAttribute.type === "c" ) {
  10394. for ( ca = 0; ca < cal; ca ++ ) {
  10395. value = customAttribute.value[ ca ];
  10396. customAttribute.array[ offset ] = value.r;
  10397. customAttribute.array[ offset + 1 ] = value.g;
  10398. customAttribute.array[ offset + 2 ] = value.b;
  10399. offset += 3;
  10400. }
  10401. } else {
  10402. for ( ca = 0; ca < cal; ca ++ ) {
  10403. value = customAttribute.value[ ca ];
  10404. customAttribute.array[ offset ] = value.x;
  10405. customAttribute.array[ offset + 1 ] = value.y;
  10406. customAttribute.array[ offset + 2 ] = value.z;
  10407. offset += 3;
  10408. }
  10409. }
  10410. } else if ( customAttribute.size === 4 ) {
  10411. for ( ca = 0; ca < cal; ca ++ ) {
  10412. value = customAttribute.value[ ca ];
  10413. customAttribute.array[ offset ] = value.x;
  10414. customAttribute.array[ offset + 1 ] = value.y;
  10415. customAttribute.array[ offset + 2 ] = value.z;
  10416. customAttribute.array[ offset + 3 ] = value.w;
  10417. offset += 4;
  10418. }
  10419. }
  10420. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10421. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10422. }
  10423. }
  10424. }
  10425. };
  10426. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  10427. if ( ! geometryGroup.__inittedArrays ) {
  10428. return;
  10429. }
  10430. var normalType = bufferGuessNormalType( material ),
  10431. vertexColorType = bufferGuessVertexColorType( material ),
  10432. uvType = bufferGuessUVType( material ),
  10433. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  10434. var f, fl, fi, face,
  10435. vertexNormals, faceNormal, normal,
  10436. vertexColors, faceColor,
  10437. vertexTangents,
  10438. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  10439. c1, c2, c3, c4,
  10440. sw1, sw2, sw3, sw4,
  10441. si1, si2, si3, si4,
  10442. sa1, sa2, sa3, sa4,
  10443. sb1, sb2, sb3, sb4,
  10444. m, ml, i, il,
  10445. vn, uvi, uv2i,
  10446. vk, vkl, vka,
  10447. nka, chf, faceVertexNormals,
  10448. a,
  10449. vertexIndex = 0,
  10450. offset = 0,
  10451. offset_uv = 0,
  10452. offset_uv2 = 0,
  10453. offset_face = 0,
  10454. offset_normal = 0,
  10455. offset_tangent = 0,
  10456. offset_line = 0,
  10457. offset_color = 0,
  10458. offset_skin = 0,
  10459. offset_morphTarget = 0,
  10460. offset_custom = 0,
  10461. offset_customSrc = 0,
  10462. value,
  10463. vertexArray = geometryGroup.__vertexArray,
  10464. uvArray = geometryGroup.__uvArray,
  10465. uv2Array = geometryGroup.__uv2Array,
  10466. normalArray = geometryGroup.__normalArray,
  10467. tangentArray = geometryGroup.__tangentArray,
  10468. colorArray = geometryGroup.__colorArray,
  10469. skinIndexArray = geometryGroup.__skinIndexArray,
  10470. skinWeightArray = geometryGroup.__skinWeightArray,
  10471. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  10472. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  10473. customAttributes = geometryGroup.__webglCustomAttributesList,
  10474. customAttribute,
  10475. faceArray = geometryGroup.__faceArray,
  10476. lineArray = geometryGroup.__lineArray,
  10477. geometry = object.geometry, // this is shared for all chunks
  10478. dirtyVertices = geometry.verticesNeedUpdate,
  10479. dirtyElements = geometry.elementsNeedUpdate,
  10480. dirtyUvs = geometry.uvsNeedUpdate,
  10481. dirtyNormals = geometry.normalsNeedUpdate,
  10482. dirtyTangents = geometry.tangentsNeedUpdate,
  10483. dirtyColors = geometry.colorsNeedUpdate,
  10484. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  10485. vertices = geometry.vertices,
  10486. chunk_faces3 = geometryGroup.faces3,
  10487. chunk_faces4 = geometryGroup.faces4,
  10488. obj_faces = geometry.faces,
  10489. obj_uvs = geometry.faceVertexUvs[ 0 ],
  10490. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  10491. obj_colors = geometry.colors,
  10492. obj_skinIndices = geometry.skinIndices,
  10493. obj_skinWeights = geometry.skinWeights,
  10494. morphTargets = geometry.morphTargets,
  10495. morphNormals = geometry.morphNormals;
  10496. if ( dirtyVertices ) {
  10497. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10498. face = obj_faces[ chunk_faces3[ f ] ];
  10499. v1 = vertices[ face.a ];
  10500. v2 = vertices[ face.b ];
  10501. v3 = vertices[ face.c ];
  10502. vertexArray[ offset ] = v1.x;
  10503. vertexArray[ offset + 1 ] = v1.y;
  10504. vertexArray[ offset + 2 ] = v1.z;
  10505. vertexArray[ offset + 3 ] = v2.x;
  10506. vertexArray[ offset + 4 ] = v2.y;
  10507. vertexArray[ offset + 5 ] = v2.z;
  10508. vertexArray[ offset + 6 ] = v3.x;
  10509. vertexArray[ offset + 7 ] = v3.y;
  10510. vertexArray[ offset + 8 ] = v3.z;
  10511. offset += 9;
  10512. }
  10513. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10514. face = obj_faces[ chunk_faces4[ f ] ];
  10515. v1 = vertices[ face.a ];
  10516. v2 = vertices[ face.b ];
  10517. v3 = vertices[ face.c ];
  10518. v4 = vertices[ face.d ];
  10519. vertexArray[ offset ] = v1.x;
  10520. vertexArray[ offset + 1 ] = v1.y;
  10521. vertexArray[ offset + 2 ] = v1.z;
  10522. vertexArray[ offset + 3 ] = v2.x;
  10523. vertexArray[ offset + 4 ] = v2.y;
  10524. vertexArray[ offset + 5 ] = v2.z;
  10525. vertexArray[ offset + 6 ] = v3.x;
  10526. vertexArray[ offset + 7 ] = v3.y;
  10527. vertexArray[ offset + 8 ] = v3.z;
  10528. vertexArray[ offset + 9 ] = v4.x;
  10529. vertexArray[ offset + 10 ] = v4.y;
  10530. vertexArray[ offset + 11 ] = v4.z;
  10531. offset += 12;
  10532. }
  10533. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10534. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10535. }
  10536. if ( dirtyMorphTargets ) {
  10537. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  10538. offset_morphTarget = 0;
  10539. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10540. chf = chunk_faces3[ f ];
  10541. face = obj_faces[ chf ];
  10542. // morph positions
  10543. v1 = morphTargets[ vk ].vertices[ face.a ];
  10544. v2 = morphTargets[ vk ].vertices[ face.b ];
  10545. v3 = morphTargets[ vk ].vertices[ face.c ];
  10546. vka = morphTargetsArrays[ vk ];
  10547. vka[ offset_morphTarget ] = v1.x;
  10548. vka[ offset_morphTarget + 1 ] = v1.y;
  10549. vka[ offset_morphTarget + 2 ] = v1.z;
  10550. vka[ offset_morphTarget + 3 ] = v2.x;
  10551. vka[ offset_morphTarget + 4 ] = v2.y;
  10552. vka[ offset_morphTarget + 5 ] = v2.z;
  10553. vka[ offset_morphTarget + 6 ] = v3.x;
  10554. vka[ offset_morphTarget + 7 ] = v3.y;
  10555. vka[ offset_morphTarget + 8 ] = v3.z;
  10556. // morph normals
  10557. if ( material.morphNormals ) {
  10558. if ( needsSmoothNormals ) {
  10559. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10560. n1 = faceVertexNormals.a;
  10561. n2 = faceVertexNormals.b;
  10562. n3 = faceVertexNormals.c;
  10563. } else {
  10564. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10565. n2 = n1;
  10566. n3 = n1;
  10567. }
  10568. nka = morphNormalsArrays[ vk ];
  10569. nka[ offset_morphTarget ] = n1.x;
  10570. nka[ offset_morphTarget + 1 ] = n1.y;
  10571. nka[ offset_morphTarget + 2 ] = n1.z;
  10572. nka[ offset_morphTarget + 3 ] = n2.x;
  10573. nka[ offset_morphTarget + 4 ] = n2.y;
  10574. nka[ offset_morphTarget + 5 ] = n2.z;
  10575. nka[ offset_morphTarget + 6 ] = n3.x;
  10576. nka[ offset_morphTarget + 7 ] = n3.y;
  10577. nka[ offset_morphTarget + 8 ] = n3.z;
  10578. }
  10579. //
  10580. offset_morphTarget += 9;
  10581. }
  10582. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10583. chf = chunk_faces4[ f ];
  10584. face = obj_faces[ chf ];
  10585. // morph positions
  10586. v1 = morphTargets[ vk ].vertices[ face.a ];
  10587. v2 = morphTargets[ vk ].vertices[ face.b ];
  10588. v3 = morphTargets[ vk ].vertices[ face.c ];
  10589. v4 = morphTargets[ vk ].vertices[ face.d ];
  10590. vka = morphTargetsArrays[ vk ];
  10591. vka[ offset_morphTarget ] = v1.x;
  10592. vka[ offset_morphTarget + 1 ] = v1.y;
  10593. vka[ offset_morphTarget + 2 ] = v1.z;
  10594. vka[ offset_morphTarget + 3 ] = v2.x;
  10595. vka[ offset_morphTarget + 4 ] = v2.y;
  10596. vka[ offset_morphTarget + 5 ] = v2.z;
  10597. vka[ offset_morphTarget + 6 ] = v3.x;
  10598. vka[ offset_morphTarget + 7 ] = v3.y;
  10599. vka[ offset_morphTarget + 8 ] = v3.z;
  10600. vka[ offset_morphTarget + 9 ] = v4.x;
  10601. vka[ offset_morphTarget + 10 ] = v4.y;
  10602. vka[ offset_morphTarget + 11 ] = v4.z;
  10603. // morph normals
  10604. if ( material.morphNormals ) {
  10605. if ( needsSmoothNormals ) {
  10606. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10607. n1 = faceVertexNormals.a;
  10608. n2 = faceVertexNormals.b;
  10609. n3 = faceVertexNormals.c;
  10610. n4 = faceVertexNormals.d;
  10611. } else {
  10612. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10613. n2 = n1;
  10614. n3 = n1;
  10615. n4 = n1;
  10616. }
  10617. nka = morphNormalsArrays[ vk ];
  10618. nka[ offset_morphTarget ] = n1.x;
  10619. nka[ offset_morphTarget + 1 ] = n1.y;
  10620. nka[ offset_morphTarget + 2 ] = n1.z;
  10621. nka[ offset_morphTarget + 3 ] = n2.x;
  10622. nka[ offset_morphTarget + 4 ] = n2.y;
  10623. nka[ offset_morphTarget + 5 ] = n2.z;
  10624. nka[ offset_morphTarget + 6 ] = n3.x;
  10625. nka[ offset_morphTarget + 7 ] = n3.y;
  10626. nka[ offset_morphTarget + 8 ] = n3.z;
  10627. nka[ offset_morphTarget + 9 ] = n4.x;
  10628. nka[ offset_morphTarget + 10 ] = n4.y;
  10629. nka[ offset_morphTarget + 11 ] = n4.z;
  10630. }
  10631. //
  10632. offset_morphTarget += 12;
  10633. }
  10634. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  10635. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  10636. if ( material.morphNormals ) {
  10637. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  10638. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  10639. }
  10640. }
  10641. }
  10642. if ( obj_skinWeights.length ) {
  10643. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10644. face = obj_faces[ chunk_faces3[ f ] ];
  10645. // weights
  10646. sw1 = obj_skinWeights[ face.a ];
  10647. sw2 = obj_skinWeights[ face.b ];
  10648. sw3 = obj_skinWeights[ face.c ];
  10649. skinWeightArray[ offset_skin ] = sw1.x;
  10650. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10651. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10652. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10653. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10654. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10655. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10656. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10657. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10658. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10659. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10660. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10661. // indices
  10662. si1 = obj_skinIndices[ face.a ];
  10663. si2 = obj_skinIndices[ face.b ];
  10664. si3 = obj_skinIndices[ face.c ];
  10665. skinIndexArray[ offset_skin ] = si1.x;
  10666. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10667. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10668. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10669. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10670. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10671. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10672. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10673. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10674. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10675. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10676. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10677. offset_skin += 12;
  10678. }
  10679. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10680. face = obj_faces[ chunk_faces4[ f ] ];
  10681. // weights
  10682. sw1 = obj_skinWeights[ face.a ];
  10683. sw2 = obj_skinWeights[ face.b ];
  10684. sw3 = obj_skinWeights[ face.c ];
  10685. sw4 = obj_skinWeights[ face.d ];
  10686. skinWeightArray[ offset_skin ] = sw1.x;
  10687. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10688. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10689. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10690. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10691. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10692. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10693. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10694. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10695. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10696. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10697. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10698. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10699. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10700. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10701. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10702. // indices
  10703. si1 = obj_skinIndices[ face.a ];
  10704. si2 = obj_skinIndices[ face.b ];
  10705. si3 = obj_skinIndices[ face.c ];
  10706. si4 = obj_skinIndices[ face.d ];
  10707. skinIndexArray[ offset_skin ] = si1.x;
  10708. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10709. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10710. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10711. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10712. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10713. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10714. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10715. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10716. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10717. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10718. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10719. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10720. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10721. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10722. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10723. offset_skin += 16;
  10724. }
  10725. if ( offset_skin > 0 ) {
  10726. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10727. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10728. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10729. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10730. }
  10731. }
  10732. if ( dirtyColors && vertexColorType ) {
  10733. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10734. face = obj_faces[ chunk_faces3[ f ] ];
  10735. vertexColors = face.vertexColors;
  10736. faceColor = face.color;
  10737. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10738. c1 = vertexColors[ 0 ];
  10739. c2 = vertexColors[ 1 ];
  10740. c3 = vertexColors[ 2 ];
  10741. } else {
  10742. c1 = faceColor;
  10743. c2 = faceColor;
  10744. c3 = faceColor;
  10745. }
  10746. colorArray[ offset_color ] = c1.r;
  10747. colorArray[ offset_color + 1 ] = c1.g;
  10748. colorArray[ offset_color + 2 ] = c1.b;
  10749. colorArray[ offset_color + 3 ] = c2.r;
  10750. colorArray[ offset_color + 4 ] = c2.g;
  10751. colorArray[ offset_color + 5 ] = c2.b;
  10752. colorArray[ offset_color + 6 ] = c3.r;
  10753. colorArray[ offset_color + 7 ] = c3.g;
  10754. colorArray[ offset_color + 8 ] = c3.b;
  10755. offset_color += 9;
  10756. }
  10757. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10758. face = obj_faces[ chunk_faces4[ f ] ];
  10759. vertexColors = face.vertexColors;
  10760. faceColor = face.color;
  10761. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10762. c1 = vertexColors[ 0 ];
  10763. c2 = vertexColors[ 1 ];
  10764. c3 = vertexColors[ 2 ];
  10765. c4 = vertexColors[ 3 ];
  10766. } else {
  10767. c1 = faceColor;
  10768. c2 = faceColor;
  10769. c3 = faceColor;
  10770. c4 = faceColor;
  10771. }
  10772. colorArray[ offset_color ] = c1.r;
  10773. colorArray[ offset_color + 1 ] = c1.g;
  10774. colorArray[ offset_color + 2 ] = c1.b;
  10775. colorArray[ offset_color + 3 ] = c2.r;
  10776. colorArray[ offset_color + 4 ] = c2.g;
  10777. colorArray[ offset_color + 5 ] = c2.b;
  10778. colorArray[ offset_color + 6 ] = c3.r;
  10779. colorArray[ offset_color + 7 ] = c3.g;
  10780. colorArray[ offset_color + 8 ] = c3.b;
  10781. colorArray[ offset_color + 9 ] = c4.r;
  10782. colorArray[ offset_color + 10 ] = c4.g;
  10783. colorArray[ offset_color + 11 ] = c4.b;
  10784. offset_color += 12;
  10785. }
  10786. if ( offset_color > 0 ) {
  10787. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10788. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10789. }
  10790. }
  10791. if ( dirtyTangents && geometry.hasTangents ) {
  10792. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10793. face = obj_faces[ chunk_faces3[ f ] ];
  10794. vertexTangents = face.vertexTangents;
  10795. t1 = vertexTangents[ 0 ];
  10796. t2 = vertexTangents[ 1 ];
  10797. t3 = vertexTangents[ 2 ];
  10798. tangentArray[ offset_tangent ] = t1.x;
  10799. tangentArray[ offset_tangent + 1 ] = t1.y;
  10800. tangentArray[ offset_tangent + 2 ] = t1.z;
  10801. tangentArray[ offset_tangent + 3 ] = t1.w;
  10802. tangentArray[ offset_tangent + 4 ] = t2.x;
  10803. tangentArray[ offset_tangent + 5 ] = t2.y;
  10804. tangentArray[ offset_tangent + 6 ] = t2.z;
  10805. tangentArray[ offset_tangent + 7 ] = t2.w;
  10806. tangentArray[ offset_tangent + 8 ] = t3.x;
  10807. tangentArray[ offset_tangent + 9 ] = t3.y;
  10808. tangentArray[ offset_tangent + 10 ] = t3.z;
  10809. tangentArray[ offset_tangent + 11 ] = t3.w;
  10810. offset_tangent += 12;
  10811. }
  10812. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10813. face = obj_faces[ chunk_faces4[ f ] ];
  10814. vertexTangents = face.vertexTangents;
  10815. t1 = vertexTangents[ 0 ];
  10816. t2 = vertexTangents[ 1 ];
  10817. t3 = vertexTangents[ 2 ];
  10818. t4 = vertexTangents[ 3 ];
  10819. tangentArray[ offset_tangent ] = t1.x;
  10820. tangentArray[ offset_tangent + 1 ] = t1.y;
  10821. tangentArray[ offset_tangent + 2 ] = t1.z;
  10822. tangentArray[ offset_tangent + 3 ] = t1.w;
  10823. tangentArray[ offset_tangent + 4 ] = t2.x;
  10824. tangentArray[ offset_tangent + 5 ] = t2.y;
  10825. tangentArray[ offset_tangent + 6 ] = t2.z;
  10826. tangentArray[ offset_tangent + 7 ] = t2.w;
  10827. tangentArray[ offset_tangent + 8 ] = t3.x;
  10828. tangentArray[ offset_tangent + 9 ] = t3.y;
  10829. tangentArray[ offset_tangent + 10 ] = t3.z;
  10830. tangentArray[ offset_tangent + 11 ] = t3.w;
  10831. tangentArray[ offset_tangent + 12 ] = t4.x;
  10832. tangentArray[ offset_tangent + 13 ] = t4.y;
  10833. tangentArray[ offset_tangent + 14 ] = t4.z;
  10834. tangentArray[ offset_tangent + 15 ] = t4.w;
  10835. offset_tangent += 16;
  10836. }
  10837. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10838. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10839. }
  10840. if ( dirtyNormals && normalType ) {
  10841. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10842. face = obj_faces[ chunk_faces3[ f ] ];
  10843. vertexNormals = face.vertexNormals;
  10844. faceNormal = face.normal;
  10845. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10846. for ( i = 0; i < 3; i ++ ) {
  10847. vn = vertexNormals[ i ];
  10848. normalArray[ offset_normal ] = vn.x;
  10849. normalArray[ offset_normal + 1 ] = vn.y;
  10850. normalArray[ offset_normal + 2 ] = vn.z;
  10851. offset_normal += 3;
  10852. }
  10853. } else {
  10854. for ( i = 0; i < 3; i ++ ) {
  10855. normalArray[ offset_normal ] = faceNormal.x;
  10856. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10857. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10858. offset_normal += 3;
  10859. }
  10860. }
  10861. }
  10862. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10863. face = obj_faces[ chunk_faces4[ f ] ];
  10864. vertexNormals = face.vertexNormals;
  10865. faceNormal = face.normal;
  10866. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10867. for ( i = 0; i < 4; i ++ ) {
  10868. vn = vertexNormals[ i ];
  10869. normalArray[ offset_normal ] = vn.x;
  10870. normalArray[ offset_normal + 1 ] = vn.y;
  10871. normalArray[ offset_normal + 2 ] = vn.z;
  10872. offset_normal += 3;
  10873. }
  10874. } else {
  10875. for ( i = 0; i < 4; i ++ ) {
  10876. normalArray[ offset_normal ] = faceNormal.x;
  10877. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10878. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10879. offset_normal += 3;
  10880. }
  10881. }
  10882. }
  10883. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10884. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10885. }
  10886. if ( dirtyUvs && obj_uvs && uvType ) {
  10887. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10888. fi = chunk_faces3[ f ];
  10889. uv = obj_uvs[ fi ];
  10890. if ( uv === undefined ) continue;
  10891. for ( i = 0; i < 3; i ++ ) {
  10892. uvi = uv[ i ];
  10893. uvArray[ offset_uv ] = uvi.u;
  10894. uvArray[ offset_uv + 1 ] = uvi.v;
  10895. offset_uv += 2;
  10896. }
  10897. }
  10898. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10899. fi = chunk_faces4[ f ];
  10900. uv = obj_uvs[ fi ];
  10901. if ( uv === undefined ) continue;
  10902. for ( i = 0; i < 4; i ++ ) {
  10903. uvi = uv[ i ];
  10904. uvArray[ offset_uv ] = uvi.u;
  10905. uvArray[ offset_uv + 1 ] = uvi.v;
  10906. offset_uv += 2;
  10907. }
  10908. }
  10909. if ( offset_uv > 0 ) {
  10910. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10911. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10912. }
  10913. }
  10914. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10915. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10916. fi = chunk_faces3[ f ];
  10917. uv2 = obj_uvs2[ fi ];
  10918. if ( uv2 === undefined ) continue;
  10919. for ( i = 0; i < 3; i ++ ) {
  10920. uv2i = uv2[ i ];
  10921. uv2Array[ offset_uv2 ] = uv2i.u;
  10922. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10923. offset_uv2 += 2;
  10924. }
  10925. }
  10926. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10927. fi = chunk_faces4[ f ];
  10928. uv2 = obj_uvs2[ fi ];
  10929. if ( uv2 === undefined ) continue;
  10930. for ( i = 0; i < 4; i ++ ) {
  10931. uv2i = uv2[ i ];
  10932. uv2Array[ offset_uv2 ] = uv2i.u;
  10933. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10934. offset_uv2 += 2;
  10935. }
  10936. }
  10937. if ( offset_uv2 > 0 ) {
  10938. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10939. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10940. }
  10941. }
  10942. if ( dirtyElements ) {
  10943. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10944. faceArray[ offset_face ] = vertexIndex;
  10945. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10946. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10947. offset_face += 3;
  10948. lineArray[ offset_line ] = vertexIndex;
  10949. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10950. lineArray[ offset_line + 2 ] = vertexIndex;
  10951. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10952. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10953. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10954. offset_line += 6;
  10955. vertexIndex += 3;
  10956. }
  10957. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10958. faceArray[ offset_face ] = vertexIndex;
  10959. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10960. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10961. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10962. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10963. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10964. offset_face += 6;
  10965. lineArray[ offset_line ] = vertexIndex;
  10966. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10967. lineArray[ offset_line + 2 ] = vertexIndex;
  10968. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10969. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10970. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10971. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10972. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10973. offset_line += 8;
  10974. vertexIndex += 4;
  10975. }
  10976. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10977. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10978. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10979. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10980. }
  10981. if ( customAttributes ) {
  10982. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10983. customAttribute = customAttributes[ i ];
  10984. if ( ! customAttribute.__original.needsUpdate ) continue;
  10985. offset_custom = 0;
  10986. offset_customSrc = 0;
  10987. if ( customAttribute.size === 1 ) {
  10988. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10989. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10990. face = obj_faces[ chunk_faces3[ f ] ];
  10991. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10992. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10993. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10994. offset_custom += 3;
  10995. }
  10996. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10997. face = obj_faces[ chunk_faces4[ f ] ];
  10998. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10999. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11000. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11001. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  11002. offset_custom += 4;
  11003. }
  11004. } else if ( customAttribute.boundTo === "faces" ) {
  11005. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11006. value = customAttribute.value[ chunk_faces3[ f ] ];
  11007. customAttribute.array[ offset_custom ] = value;
  11008. customAttribute.array[ offset_custom + 1 ] = value;
  11009. customAttribute.array[ offset_custom + 2 ] = value;
  11010. offset_custom += 3;
  11011. }
  11012. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11013. value = customAttribute.value[ chunk_faces4[ f ] ];
  11014. customAttribute.array[ offset_custom ] = value;
  11015. customAttribute.array[ offset_custom + 1 ] = value;
  11016. customAttribute.array[ offset_custom + 2 ] = value;
  11017. customAttribute.array[ offset_custom + 3 ] = value;
  11018. offset_custom += 4;
  11019. }
  11020. }
  11021. } else if ( customAttribute.size === 2 ) {
  11022. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11023. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11024. face = obj_faces[ chunk_faces3[ f ] ];
  11025. v1 = customAttribute.value[ face.a ];
  11026. v2 = customAttribute.value[ face.b ];
  11027. v3 = customAttribute.value[ face.c ];
  11028. customAttribute.array[ offset_custom ] = v1.x;
  11029. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11030. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11031. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11032. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11033. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11034. offset_custom += 6;
  11035. }
  11036. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11037. face = obj_faces[ chunk_faces4[ f ] ];
  11038. v1 = customAttribute.value[ face.a ];
  11039. v2 = customAttribute.value[ face.b ];
  11040. v3 = customAttribute.value[ face.c ];
  11041. v4 = customAttribute.value[ face.d ];
  11042. customAttribute.array[ offset_custom ] = v1.x;
  11043. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11044. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11045. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11046. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11047. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11048. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11049. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11050. offset_custom += 8;
  11051. }
  11052. } else if ( customAttribute.boundTo === "faces" ) {
  11053. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11054. value = customAttribute.value[ chunk_faces3[ f ] ];
  11055. v1 = value;
  11056. v2 = value;
  11057. v3 = value;
  11058. customAttribute.array[ offset_custom ] = v1.x;
  11059. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11060. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11061. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11062. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11063. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11064. offset_custom += 6;
  11065. }
  11066. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11067. value = customAttribute.value[ chunk_faces4[ f ] ];
  11068. v1 = value;
  11069. v2 = value;
  11070. v3 = value;
  11071. v4 = value;
  11072. customAttribute.array[ offset_custom ] = v1.x;
  11073. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11074. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11075. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11076. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11077. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11078. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11079. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11080. offset_custom += 8;
  11081. }
  11082. }
  11083. } else if ( customAttribute.size === 3 ) {
  11084. var pp;
  11085. if ( customAttribute.type === "c" ) {
  11086. pp = [ "r", "g", "b" ];
  11087. } else {
  11088. pp = [ "x", "y", "z" ];
  11089. }
  11090. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11091. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11092. face = obj_faces[ chunk_faces3[ f ] ];
  11093. v1 = customAttribute.value[ face.a ];
  11094. v2 = customAttribute.value[ face.b ];
  11095. v3 = customAttribute.value[ face.c ];
  11096. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11097. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11098. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11099. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11100. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11101. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11102. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11103. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11104. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11105. offset_custom += 9;
  11106. }
  11107. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11108. face = obj_faces[ chunk_faces4[ f ] ];
  11109. v1 = customAttribute.value[ face.a ];
  11110. v2 = customAttribute.value[ face.b ];
  11111. v3 = customAttribute.value[ face.c ];
  11112. v4 = customAttribute.value[ face.d ];
  11113. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11114. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11115. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11116. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11117. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11118. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11119. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11120. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11121. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11122. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11123. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11124. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11125. offset_custom += 12;
  11126. }
  11127. } else if ( customAttribute.boundTo === "faces" ) {
  11128. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11129. value = customAttribute.value[ chunk_faces3[ f ] ];
  11130. v1 = value;
  11131. v2 = value;
  11132. v3 = value;
  11133. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11134. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11135. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11136. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11137. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11138. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11139. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11140. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11141. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11142. offset_custom += 9;
  11143. }
  11144. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11145. value = customAttribute.value[ chunk_faces4[ f ] ];
  11146. v1 = value;
  11147. v2 = value;
  11148. v3 = value;
  11149. v4 = value;
  11150. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11151. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11152. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11153. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11154. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11155. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11156. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11157. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11158. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11159. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11160. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11161. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11162. offset_custom += 12;
  11163. }
  11164. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11165. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11166. value = customAttribute.value[ chunk_faces3[ f ] ];
  11167. v1 = value[ 0 ];
  11168. v2 = value[ 1 ];
  11169. v3 = value[ 2 ];
  11170. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11171. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11172. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11173. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11174. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11175. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11176. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11177. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11178. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11179. offset_custom += 9;
  11180. }
  11181. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11182. value = customAttribute.value[ chunk_faces4[ f ] ];
  11183. v1 = value[ 0 ];
  11184. v2 = value[ 1 ];
  11185. v3 = value[ 2 ];
  11186. v4 = value[ 3 ];
  11187. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11188. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11189. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11190. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11191. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11192. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11193. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11194. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11195. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11196. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11197. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11198. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11199. offset_custom += 12;
  11200. }
  11201. }
  11202. } else if ( customAttribute.size === 4 ) {
  11203. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11204. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11205. face = obj_faces[ chunk_faces3[ f ] ];
  11206. v1 = customAttribute.value[ face.a ];
  11207. v2 = customAttribute.value[ face.b ];
  11208. v3 = customAttribute.value[ face.c ];
  11209. customAttribute.array[ offset_custom ] = v1.x;
  11210. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11211. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11212. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11213. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11214. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11215. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11216. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11217. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11218. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11219. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11220. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11221. offset_custom += 12;
  11222. }
  11223. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11224. face = obj_faces[ chunk_faces4[ f ] ];
  11225. v1 = customAttribute.value[ face.a ];
  11226. v2 = customAttribute.value[ face.b ];
  11227. v3 = customAttribute.value[ face.c ];
  11228. v4 = customAttribute.value[ face.d ];
  11229. customAttribute.array[ offset_custom ] = v1.x;
  11230. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11231. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11232. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11233. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11234. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11235. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11236. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11237. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11238. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11239. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11240. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11241. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11242. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11243. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11244. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11245. offset_custom += 16;
  11246. }
  11247. } else if ( customAttribute.boundTo === "faces" ) {
  11248. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11249. value = customAttribute.value[ chunk_faces3[ f ] ];
  11250. v1 = value;
  11251. v2 = value;
  11252. v3 = value;
  11253. customAttribute.array[ offset_custom ] = v1.x;
  11254. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11255. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11256. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11257. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11258. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11259. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11260. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11261. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11262. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11263. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11264. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11265. offset_custom += 12;
  11266. }
  11267. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11268. value = customAttribute.value[ chunk_faces4[ f ] ];
  11269. v1 = value;
  11270. v2 = value;
  11271. v3 = value;
  11272. v4 = value;
  11273. customAttribute.array[ offset_custom ] = v1.x;
  11274. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11275. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11276. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11277. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11278. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11279. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11280. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11281. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11282. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11283. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11284. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11285. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11286. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11287. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11288. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11289. offset_custom += 16;
  11290. }
  11291. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11292. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11293. value = customAttribute.value[ chunk_faces3[ f ] ];
  11294. v1 = value[ 0 ];
  11295. v2 = value[ 1 ];
  11296. v3 = value[ 2 ];
  11297. customAttribute.array[ offset_custom ] = v1.x;
  11298. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11299. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11300. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11301. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11302. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11303. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11304. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11305. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11306. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11307. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11308. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11309. offset_custom += 12;
  11310. }
  11311. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11312. value = customAttribute.value[ chunk_faces4[ f ] ];
  11313. v1 = value[ 0 ];
  11314. v2 = value[ 1 ];
  11315. v3 = value[ 2 ];
  11316. v4 = value[ 3 ];
  11317. customAttribute.array[ offset_custom ] = v1.x;
  11318. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11319. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11320. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11321. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11322. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11323. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11324. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11325. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11326. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11327. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11328. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11329. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11330. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11331. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11332. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11333. offset_custom += 16;
  11334. }
  11335. }
  11336. }
  11337. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11338. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11339. }
  11340. }
  11341. if ( dispose ) {
  11342. delete geometryGroup.__inittedArrays;
  11343. delete geometryGroup.__colorArray;
  11344. delete geometryGroup.__normalArray;
  11345. delete geometryGroup.__tangentArray;
  11346. delete geometryGroup.__uvArray;
  11347. delete geometryGroup.__uv2Array;
  11348. delete geometryGroup.__faceArray;
  11349. delete geometryGroup.__vertexArray;
  11350. delete geometryGroup.__lineArray;
  11351. delete geometryGroup.__skinIndexArray;
  11352. delete geometryGroup.__skinWeightArray;
  11353. }
  11354. };
  11355. function setDirectBuffers ( geometry, hint, dispose ) {
  11356. var attributes = geometry.attributes;
  11357. var index = attributes[ "index" ];
  11358. var position = attributes[ "position" ];
  11359. var normal = attributes[ "normal" ];
  11360. var uv = attributes[ "uv" ];
  11361. var color = attributes[ "color" ];
  11362. var tangent = attributes[ "tangent" ];
  11363. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  11364. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11365. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  11366. }
  11367. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  11368. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11369. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  11370. }
  11371. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  11372. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11373. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  11374. }
  11375. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  11376. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11377. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  11378. }
  11379. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  11380. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11381. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  11382. }
  11383. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  11384. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11385. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  11386. }
  11387. if ( dispose ) {
  11388. for ( var i in geometry.attributes ) {
  11389. delete geometry.attributes[ i ].array;
  11390. }
  11391. }
  11392. };
  11393. // Buffer rendering
  11394. this.renderBufferImmediate = function ( object, program, material ) {
  11395. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11396. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11397. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11398. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11399. if ( object.hasPositions ) {
  11400. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11401. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11402. _gl.enableVertexAttribArray( program.attributes.position );
  11403. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11404. }
  11405. if ( object.hasNormals ) {
  11406. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11407. if ( material.shading === THREE.FlatShading ) {
  11408. var nx, ny, nz,
  11409. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11410. normalArray,
  11411. i, il = object.count * 3;
  11412. for( i = 0; i < il; i += 9 ) {
  11413. normalArray = object.normalArray;
  11414. nax = normalArray[ i ];
  11415. nay = normalArray[ i + 1 ];
  11416. naz = normalArray[ i + 2 ];
  11417. nbx = normalArray[ i + 3 ];
  11418. nby = normalArray[ i + 4 ];
  11419. nbz = normalArray[ i + 5 ];
  11420. ncx = normalArray[ i + 6 ];
  11421. ncy = normalArray[ i + 7 ];
  11422. ncz = normalArray[ i + 8 ];
  11423. nx = ( nax + nbx + ncx ) / 3;
  11424. ny = ( nay + nby + ncy ) / 3;
  11425. nz = ( naz + nbz + ncz ) / 3;
  11426. normalArray[ i ] = nx;
  11427. normalArray[ i + 1 ] = ny;
  11428. normalArray[ i + 2 ] = nz;
  11429. normalArray[ i + 3 ] = nx;
  11430. normalArray[ i + 4 ] = ny;
  11431. normalArray[ i + 5 ] = nz;
  11432. normalArray[ i + 6 ] = nx;
  11433. normalArray[ i + 7 ] = ny;
  11434. normalArray[ i + 8 ] = nz;
  11435. }
  11436. }
  11437. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11438. _gl.enableVertexAttribArray( program.attributes.normal );
  11439. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11440. }
  11441. if ( object.hasUvs && material.map ) {
  11442. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11443. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11444. _gl.enableVertexAttribArray( program.attributes.uv );
  11445. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11446. }
  11447. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11448. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11449. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11450. _gl.enableVertexAttribArray( program.attributes.color );
  11451. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11452. }
  11453. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11454. object.count = 0;
  11455. };
  11456. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  11457. if ( material.visible === false ) return;
  11458. var program, attributes, linewidth, primitives, a, attribute;
  11459. program = setProgram( camera, lights, fog, material, object );
  11460. attributes = program.attributes;
  11461. var updateBuffers = false,
  11462. wireframeBit = material.wireframe ? 1 : 0,
  11463. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11464. if ( geometryHash !== _currentGeometryGroupHash ) {
  11465. _currentGeometryGroupHash = geometryHash;
  11466. updateBuffers = true;
  11467. }
  11468. if ( updateBuffers ) {
  11469. disableAttributes();
  11470. }
  11471. // render mesh
  11472. if ( object instanceof THREE.Mesh ) {
  11473. var index = geometry.attributes[ "index" ];
  11474. // indexed triangles
  11475. if ( index ) {
  11476. var offsets = geometry.offsets;
  11477. // if there is more than 1 chunk
  11478. // must set attribute pointers to use new offsets for each chunk
  11479. // even if geometry and materials didn't change
  11480. if ( offsets.length > 1 ) updateBuffers = true;
  11481. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11482. var startIndex = offsets[ i ].index;
  11483. if ( updateBuffers ) {
  11484. // vertices
  11485. var position = geometry.attributes[ "position" ];
  11486. var positionSize = position.itemSize;
  11487. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11488. enableAttribute( attributes.position );
  11489. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  11490. // normals
  11491. var normal = geometry.attributes[ "normal" ];
  11492. if ( attributes.normal >= 0 && normal ) {
  11493. var normalSize = normal.itemSize;
  11494. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11495. enableAttribute( attributes.normal );
  11496. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  11497. }
  11498. // uvs
  11499. var uv = geometry.attributes[ "uv" ];
  11500. if ( attributes.uv >= 0 && uv ) {
  11501. var uvSize = uv.itemSize;
  11502. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11503. enableAttribute( attributes.uv );
  11504. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  11505. }
  11506. // colors
  11507. var color = geometry.attributes[ "color" ];
  11508. if ( attributes.color >= 0 && color ) {
  11509. var colorSize = color.itemSize;
  11510. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11511. enableAttribute( attributes.color );
  11512. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  11513. }
  11514. // tangents
  11515. var tangent = geometry.attributes[ "tangent" ];
  11516. if ( attributes.tangent >= 0 && tangent ) {
  11517. var tangentSize = tangent.itemSize;
  11518. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11519. enableAttribute( attributes.tangent );
  11520. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  11521. }
  11522. // indices
  11523. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11524. }
  11525. // render indexed triangles
  11526. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  11527. _this.info.render.calls ++;
  11528. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11529. _this.info.render.faces += offsets[ i ].count / 3;
  11530. }
  11531. // non-indexed triangles
  11532. } else {
  11533. if ( updateBuffers ) {
  11534. // vertices
  11535. var position = geometry.attributes[ "position" ];
  11536. var positionSize = position.itemSize;
  11537. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11538. enableAttribute( attributes.position );
  11539. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11540. // normals
  11541. var normal = geometry.attributes[ "normal" ];
  11542. if ( attributes.normal >= 0 && normal ) {
  11543. var normalSize = normal.itemSize;
  11544. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11545. enableAttribute( attributes.normal );
  11546. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  11547. }
  11548. // uvs
  11549. var uv = geometry.attributes[ "uv" ];
  11550. if ( attributes.uv >= 0 && uv ) {
  11551. var uvSize = uv.itemSize;
  11552. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11553. enableAttribute( attributes.uv );
  11554. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  11555. }
  11556. // colors
  11557. var color = geometry.attributes[ "color" ];
  11558. if ( attributes.color >= 0 && color ) {
  11559. var colorSize = color.itemSize;
  11560. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11561. enableAttribute( attributes.color );
  11562. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11563. }
  11564. // tangents
  11565. var tangent = geometry.attributes[ "tangent" ];
  11566. if ( attributes.tangent >= 0 && tangent ) {
  11567. var tangentSize = tangent.itemSize;
  11568. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11569. enableAttribute( attributes.tangent );
  11570. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  11571. }
  11572. }
  11573. // render non-indexed triangles
  11574. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  11575. _this.info.render.calls ++;
  11576. _this.info.render.vertices += position.numItems / 3;
  11577. _this.info.render.faces += position.numItems / 3 / 3;
  11578. }
  11579. // render particles
  11580. } else if ( object instanceof THREE.ParticleSystem ) {
  11581. if ( updateBuffers ) {
  11582. // vertices
  11583. var position = geometry.attributes[ "position" ];
  11584. var positionSize = position.itemSize;
  11585. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11586. enableAttribute( attributes.position );
  11587. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11588. // colors
  11589. var color = geometry.attributes[ "color" ];
  11590. if ( attributes.color >= 0 && color ) {
  11591. var colorSize = color.itemSize;
  11592. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11593. enableAttribute( attributes.color );
  11594. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11595. }
  11596. // render particles
  11597. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  11598. _this.info.render.calls ++;
  11599. _this.info.render.points += position.numItems / 3;
  11600. }
  11601. }
  11602. };
  11603. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11604. if ( material.visible === false ) return;
  11605. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11606. program = setProgram( camera, lights, fog, material, object );
  11607. attributes = program.attributes;
  11608. var updateBuffers = false,
  11609. wireframeBit = material.wireframe ? 1 : 0,
  11610. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11611. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11612. _currentGeometryGroupHash = geometryGroupHash;
  11613. updateBuffers = true;
  11614. }
  11615. if ( updateBuffers ) {
  11616. disableAttributes();
  11617. }
  11618. // vertices
  11619. if ( !material.morphTargets && attributes.position >= 0 ) {
  11620. if ( updateBuffers ) {
  11621. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11622. enableAttribute( attributes.position );
  11623. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11624. }
  11625. } else {
  11626. if ( object.morphTargetBase ) {
  11627. setupMorphTargets( material, geometryGroup, object );
  11628. }
  11629. }
  11630. if ( updateBuffers ) {
  11631. // custom attributes
  11632. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11633. if ( geometryGroup.__webglCustomAttributesList ) {
  11634. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11635. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11636. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11637. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  11638. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  11639. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  11640. }
  11641. }
  11642. }
  11643. // colors
  11644. if ( attributes.color >= 0 ) {
  11645. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11646. enableAttribute( attributes.color );
  11647. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11648. }
  11649. // normals
  11650. if ( attributes.normal >= 0 ) {
  11651. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11652. enableAttribute( attributes.normal );
  11653. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11654. }
  11655. // tangents
  11656. if ( attributes.tangent >= 0 ) {
  11657. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11658. enableAttribute( attributes.tangent );
  11659. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  11660. }
  11661. // uvs
  11662. if ( attributes.uv >= 0 ) {
  11663. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11664. enableAttribute( attributes.uv );
  11665. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11666. }
  11667. if ( attributes.uv2 >= 0 ) {
  11668. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11669. enableAttribute( attributes.uv2 );
  11670. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  11671. }
  11672. if ( material.skinning &&
  11673. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11674. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11675. enableAttribute( attributes.skinIndex );
  11676. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  11677. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11678. enableAttribute( attributes.skinWeight );
  11679. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  11680. }
  11681. // line distances
  11682. if ( attributes.lineDistance >= 0 ) {
  11683. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  11684. enableAttribute( attributes.lineDistance );
  11685. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  11686. }
  11687. }
  11688. // render mesh
  11689. if ( object instanceof THREE.Mesh ) {
  11690. // wireframe
  11691. if ( material.wireframe ) {
  11692. setLineWidth( material.wireframeLinewidth );
  11693. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11694. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  11695. // triangles
  11696. } else {
  11697. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11698. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  11699. }
  11700. _this.info.render.calls ++;
  11701. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11702. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11703. // render lines
  11704. } else if ( object instanceof THREE.Line ) {
  11705. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11706. setLineWidth( material.linewidth );
  11707. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11708. _this.info.render.calls ++;
  11709. // render particles
  11710. } else if ( object instanceof THREE.ParticleSystem ) {
  11711. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11712. _this.info.render.calls ++;
  11713. _this.info.render.points += geometryGroup.__webglParticleCount;
  11714. // render ribbon
  11715. } else if ( object instanceof THREE.Ribbon ) {
  11716. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11717. _this.info.render.calls ++;
  11718. }
  11719. };
  11720. function enableAttribute( attribute ) {
  11721. if ( ! _enabledAttributes[ attribute ] ) {
  11722. _gl.enableVertexAttribArray( attribute );
  11723. _enabledAttributes[ attribute ] = true;
  11724. }
  11725. };
  11726. function disableAttributes() {
  11727. for ( var attribute in _enabledAttributes ) {
  11728. if ( _enabledAttributes[ attribute ] ) {
  11729. _gl.disableVertexAttribArray( attribute );
  11730. _enabledAttributes[ attribute ] = false;
  11731. }
  11732. }
  11733. };
  11734. function setupMorphTargets ( material, geometryGroup, object ) {
  11735. // set base
  11736. var attributes = material.program.attributes;
  11737. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  11738. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11739. enableAttribute( attributes.position );
  11740. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11741. } else if ( attributes.position >= 0 ) {
  11742. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11743. enableAttribute( attributes.position );
  11744. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11745. }
  11746. if ( object.morphTargetForcedOrder.length ) {
  11747. // set forced order
  11748. var m = 0;
  11749. var order = object.morphTargetForcedOrder;
  11750. var influences = object.morphTargetInfluences;
  11751. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11752. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  11753. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11754. enableAttribute( attributes[ "morphTarget" + m ] );
  11755. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11756. }
  11757. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  11758. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11759. enableAttribute( attributes[ "morphNormal" + m ] );
  11760. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11761. }
  11762. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11763. m ++;
  11764. }
  11765. } else {
  11766. // find the most influencing
  11767. var influence, activeInfluenceIndices = [];
  11768. var influences = object.morphTargetInfluences;
  11769. var i, il = influences.length;
  11770. for ( i = 0; i < il; i ++ ) {
  11771. influence = influences[ i ];
  11772. if ( influence > 0 ) {
  11773. activeInfluenceIndices.push( [ influence, i ] );
  11774. }
  11775. }
  11776. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11777. activeInfluenceIndices.sort( numericalSort );
  11778. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11779. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11780. activeInfluenceIndices.sort( numericalSort );
  11781. } else if ( activeInfluenceIndices.length === 0 ) {
  11782. activeInfluenceIndices.push( [ 0, 0 ] );
  11783. };
  11784. var influenceIndex, m = 0;
  11785. while ( m < material.numSupportedMorphTargets ) {
  11786. if ( activeInfluenceIndices[ m ] ) {
  11787. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  11788. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  11789. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11790. enableAttribute( attributes[ "morphTarget" + m ] );
  11791. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11792. }
  11793. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  11794. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11795. enableAttribute( attributes[ "morphNormal" + m ] );
  11796. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11797. }
  11798. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11799. } else {
  11800. /*
  11801. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11802. if ( material.morphNormals ) {
  11803. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11804. }
  11805. */
  11806. object.__webglMorphTargetInfluences[ m ] = 0;
  11807. }
  11808. m ++;
  11809. }
  11810. }
  11811. // load updated influences uniform
  11812. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11813. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11814. }
  11815. };
  11816. // Sorting
  11817. function painterSortStable ( a, b ) {
  11818. if ( a.z !== b.z ) {
  11819. return b.z - a.z;
  11820. } else {
  11821. return b.id - a.id;
  11822. }
  11823. };
  11824. function numericalSort ( a, b ) {
  11825. return b[ 0 ] - a[ 0 ];
  11826. };
  11827. // Rendering
  11828. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11829. if ( camera instanceof THREE.Camera === false ) {
  11830. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11831. return;
  11832. }
  11833. var i, il,
  11834. webglObject, object,
  11835. renderList,
  11836. lights = scene.__lights,
  11837. fog = scene.fog;
  11838. // reset caching for this frame
  11839. _currentMaterialId = -1;
  11840. _lightsNeedUpdate = true;
  11841. // update scene graph
  11842. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11843. // update camera matrices and frustum
  11844. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11845. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11846. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11847. _frustum.setFromMatrix( _projScreenMatrix );
  11848. // update WebGL objects
  11849. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11850. // custom render plugins (pre pass)
  11851. renderPlugins( this.renderPluginsPre, scene, camera );
  11852. //
  11853. _this.info.render.calls = 0;
  11854. _this.info.render.vertices = 0;
  11855. _this.info.render.faces = 0;
  11856. _this.info.render.points = 0;
  11857. this.setRenderTarget( renderTarget );
  11858. if ( this.autoClear || forceClear ) {
  11859. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11860. }
  11861. // set matrices for regular objects (frustum culled)
  11862. renderList = scene.__webglObjects;
  11863. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11864. webglObject = renderList[ i ];
  11865. object = webglObject.object;
  11866. webglObject.render = false;
  11867. if ( object.visible ) {
  11868. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11869. setupMatrices( object, camera );
  11870. unrollBufferMaterial( webglObject );
  11871. webglObject.render = true;
  11872. if ( this.sortObjects === true ) {
  11873. if ( object.renderDepth !== null ) {
  11874. webglObject.z = object.renderDepth;
  11875. } else {
  11876. _vector3.copy( object.matrixWorld.getPosition() );
  11877. _projScreenMatrix.multiplyVector3( _vector3 );
  11878. webglObject.z = _vector3.z;
  11879. }
  11880. webglObject.id = object.id;
  11881. }
  11882. }
  11883. }
  11884. }
  11885. if ( this.sortObjects ) {
  11886. renderList.sort( painterSortStable );
  11887. }
  11888. // set matrices for immediate objects
  11889. renderList = scene.__webglObjectsImmediate;
  11890. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11891. webglObject = renderList[ i ];
  11892. object = webglObject.object;
  11893. if ( object.visible ) {
  11894. setupMatrices( object, camera );
  11895. unrollImmediateBufferMaterial( webglObject );
  11896. }
  11897. }
  11898. if ( scene.overrideMaterial ) {
  11899. var material = scene.overrideMaterial;
  11900. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11901. this.setDepthTest( material.depthTest );
  11902. this.setDepthWrite( material.depthWrite );
  11903. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11904. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11905. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11906. } else {
  11907. var material = null;
  11908. // opaque pass (front-to-back order)
  11909. this.setBlending( THREE.NoBlending );
  11910. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  11911. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  11912. // transparent pass (back-to-front order)
  11913. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  11914. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  11915. }
  11916. // custom render plugins (post pass)
  11917. renderPlugins( this.renderPluginsPost, scene, camera );
  11918. // Generate mipmap if we're using any kind of mipmap filtering
  11919. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11920. updateRenderTargetMipmap( renderTarget );
  11921. }
  11922. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11923. this.setDepthTest( true );
  11924. this.setDepthWrite( true );
  11925. // _gl.finish();
  11926. };
  11927. function renderPlugins( plugins, scene, camera ) {
  11928. if ( ! plugins.length ) return;
  11929. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11930. // reset state for plugin (to start from clean slate)
  11931. _currentProgram = null;
  11932. _currentCamera = null;
  11933. _oldBlending = -1;
  11934. _oldDepthTest = -1;
  11935. _oldDepthWrite = -1;
  11936. _oldDoubleSided = -1;
  11937. _oldFlipSided = -1;
  11938. _currentGeometryGroupHash = -1;
  11939. _currentMaterialId = -1;
  11940. _lightsNeedUpdate = true;
  11941. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11942. // reset state after plugin (anything could have changed)
  11943. _currentProgram = null;
  11944. _currentCamera = null;
  11945. _oldBlending = -1;
  11946. _oldDepthTest = -1;
  11947. _oldDepthWrite = -1;
  11948. _oldDoubleSided = -1;
  11949. _oldFlipSided = -1;
  11950. _currentGeometryGroupHash = -1;
  11951. _currentMaterialId = -1;
  11952. _lightsNeedUpdate = true;
  11953. }
  11954. };
  11955. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11956. var webglObject, object, buffer, material, start, end, delta;
  11957. if ( reverse ) {
  11958. start = renderList.length - 1;
  11959. end = -1;
  11960. delta = -1;
  11961. } else {
  11962. start = 0;
  11963. end = renderList.length;
  11964. delta = 1;
  11965. }
  11966. for ( var i = start; i !== end; i += delta ) {
  11967. webglObject = renderList[ i ];
  11968. if ( webglObject.render ) {
  11969. object = webglObject.object;
  11970. buffer = webglObject.buffer;
  11971. if ( overrideMaterial ) {
  11972. material = overrideMaterial;
  11973. } else {
  11974. material = webglObject[ materialType ];
  11975. if ( ! material ) continue;
  11976. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11977. _this.setDepthTest( material.depthTest );
  11978. _this.setDepthWrite( material.depthWrite );
  11979. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11980. }
  11981. _this.setMaterialFaces( material );
  11982. if ( buffer instanceof THREE.BufferGeometry ) {
  11983. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11984. } else {
  11985. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11986. }
  11987. }
  11988. }
  11989. };
  11990. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11991. var webglObject, object, material, program;
  11992. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11993. webglObject = renderList[ i ];
  11994. object = webglObject.object;
  11995. if ( object.visible ) {
  11996. if ( overrideMaterial ) {
  11997. material = overrideMaterial;
  11998. } else {
  11999. material = webglObject[ materialType ];
  12000. if ( ! material ) continue;
  12001. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12002. _this.setDepthTest( material.depthTest );
  12003. _this.setDepthWrite( material.depthWrite );
  12004. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12005. }
  12006. _this.renderImmediateObject( camera, lights, fog, material, object );
  12007. }
  12008. }
  12009. };
  12010. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12011. var program = setProgram( camera, lights, fog, material, object );
  12012. _currentGeometryGroupHash = -1;
  12013. _this.setMaterialFaces( material );
  12014. if ( object.immediateRenderCallback ) {
  12015. object.immediateRenderCallback( program, _gl, _frustum );
  12016. } else {
  12017. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12018. }
  12019. };
  12020. function unrollImmediateBufferMaterial ( globject ) {
  12021. var object = globject.object,
  12022. material = object.material;
  12023. if ( material.transparent ) {
  12024. globject.transparent = material;
  12025. globject.opaque = null;
  12026. } else {
  12027. globject.opaque = material;
  12028. globject.transparent = null;
  12029. }
  12030. };
  12031. function unrollBufferMaterial ( globject ) {
  12032. var object = globject.object,
  12033. buffer = globject.buffer,
  12034. material, materialIndex, meshMaterial;
  12035. meshMaterial = object.material;
  12036. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  12037. materialIndex = buffer.materialIndex;
  12038. material = meshMaterial.materials[ materialIndex ];
  12039. if ( material.transparent ) {
  12040. globject.transparent = material;
  12041. globject.opaque = null;
  12042. } else {
  12043. globject.opaque = material;
  12044. globject.transparent = null;
  12045. }
  12046. } else {
  12047. material = meshMaterial;
  12048. if ( material ) {
  12049. if ( material.transparent ) {
  12050. globject.transparent = material;
  12051. globject.opaque = null;
  12052. } else {
  12053. globject.opaque = material;
  12054. globject.transparent = null;
  12055. }
  12056. }
  12057. }
  12058. };
  12059. // Geometry splitting
  12060. function sortFacesByMaterial ( geometry, material ) {
  12061. var f, fl, face, materialIndex, vertices,
  12062. groupHash, hash_map = {};
  12063. var numMorphTargets = geometry.morphTargets.length;
  12064. var numMorphNormals = geometry.morphNormals.length;
  12065. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  12066. geometry.geometryGroups = {};
  12067. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12068. face = geometry.faces[ f ];
  12069. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12070. if ( hash_map[ materialIndex ] === undefined ) {
  12071. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  12072. }
  12073. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12074. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12075. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12076. }
  12077. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12078. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12079. hash_map[ materialIndex ].counter += 1;
  12080. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12081. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12082. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12083. }
  12084. }
  12085. if ( face instanceof THREE.Face3 ) {
  12086. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12087. } else {
  12088. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12089. }
  12090. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12091. }
  12092. geometry.geometryGroupsList = [];
  12093. for ( var g in geometry.geometryGroups ) {
  12094. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12095. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12096. }
  12097. };
  12098. // Objects refresh
  12099. this.initWebGLObjects = function ( scene ) {
  12100. if ( !scene.__webglObjects ) {
  12101. scene.__webglObjects = [];
  12102. scene.__webglObjectsImmediate = [];
  12103. scene.__webglSprites = [];
  12104. scene.__webglFlares = [];
  12105. }
  12106. while ( scene.__objectsAdded.length ) {
  12107. addObject( scene.__objectsAdded[ 0 ], scene );
  12108. scene.__objectsAdded.splice( 0, 1 );
  12109. }
  12110. while ( scene.__objectsRemoved.length ) {
  12111. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12112. scene.__objectsRemoved.splice( 0, 1 );
  12113. }
  12114. // update must be called after objects adding / removal
  12115. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12116. updateObject( scene.__webglObjects[ o ].object );
  12117. }
  12118. };
  12119. // Objects adding
  12120. function addObject ( object, scene ) {
  12121. var g, geometry, material, geometryGroup;
  12122. if ( ! object.__webglInit ) {
  12123. object.__webglInit = true;
  12124. object._modelViewMatrix = new THREE.Matrix4();
  12125. object._normalMatrix = new THREE.Matrix3();
  12126. if ( object instanceof THREE.Mesh ) {
  12127. geometry = object.geometry;
  12128. material = object.material;
  12129. if ( geometry instanceof THREE.Geometry ) {
  12130. if ( geometry.geometryGroups === undefined ) {
  12131. sortFacesByMaterial( geometry, material );
  12132. }
  12133. // create separate VBOs per geometry chunk
  12134. for ( g in geometry.geometryGroups ) {
  12135. geometryGroup = geometry.geometryGroups[ g ];
  12136. // initialise VBO on the first access
  12137. if ( ! geometryGroup.__webglVertexBuffer ) {
  12138. createMeshBuffers( geometryGroup );
  12139. initMeshBuffers( geometryGroup, object );
  12140. geometry.verticesNeedUpdate = true;
  12141. geometry.morphTargetsNeedUpdate = true;
  12142. geometry.elementsNeedUpdate = true;
  12143. geometry.uvsNeedUpdate = true;
  12144. geometry.normalsNeedUpdate = true;
  12145. geometry.tangentsNeedUpdate = true;
  12146. geometry.colorsNeedUpdate = true;
  12147. }
  12148. }
  12149. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12150. initDirectBuffers( geometry );
  12151. }
  12152. } else if ( object instanceof THREE.Ribbon ) {
  12153. geometry = object.geometry;
  12154. if ( ! geometry.__webglVertexBuffer ) {
  12155. createRibbonBuffers( geometry );
  12156. initRibbonBuffers( geometry, object );
  12157. geometry.verticesNeedUpdate = true;
  12158. geometry.colorsNeedUpdate = true;
  12159. geometry.normalsNeedUpdate = true;
  12160. }
  12161. } else if ( object instanceof THREE.Line ) {
  12162. geometry = object.geometry;
  12163. if ( ! geometry.__webglVertexBuffer ) {
  12164. createLineBuffers( geometry );
  12165. initLineBuffers( geometry, object );
  12166. geometry.verticesNeedUpdate = true;
  12167. geometry.colorsNeedUpdate = true;
  12168. geometry.lineDistancesNeedUpdate = true;
  12169. }
  12170. } else if ( object instanceof THREE.ParticleSystem ) {
  12171. geometry = object.geometry;
  12172. if ( ! geometry.__webglVertexBuffer ) {
  12173. if ( geometry instanceof THREE.Geometry ) {
  12174. createParticleBuffers( geometry );
  12175. initParticleBuffers( geometry, object );
  12176. geometry.verticesNeedUpdate = true;
  12177. geometry.colorsNeedUpdate = true;
  12178. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12179. initDirectBuffers( geometry );
  12180. }
  12181. }
  12182. }
  12183. }
  12184. if ( ! object.__webglActive ) {
  12185. if ( object instanceof THREE.Mesh ) {
  12186. geometry = object.geometry;
  12187. if ( geometry instanceof THREE.BufferGeometry ) {
  12188. addBuffer( scene.__webglObjects, geometry, object );
  12189. } else {
  12190. for ( g in geometry.geometryGroups ) {
  12191. geometryGroup = geometry.geometryGroups[ g ];
  12192. addBuffer( scene.__webglObjects, geometryGroup, object );
  12193. }
  12194. }
  12195. } else if ( object instanceof THREE.Ribbon ||
  12196. object instanceof THREE.Line ||
  12197. object instanceof THREE.ParticleSystem ) {
  12198. geometry = object.geometry;
  12199. addBuffer( scene.__webglObjects, geometry, object );
  12200. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12201. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12202. } else if ( object instanceof THREE.Sprite ) {
  12203. scene.__webglSprites.push( object );
  12204. } else if ( object instanceof THREE.LensFlare ) {
  12205. scene.__webglFlares.push( object );
  12206. }
  12207. object.__webglActive = true;
  12208. }
  12209. };
  12210. function addBuffer ( objlist, buffer, object ) {
  12211. objlist.push(
  12212. {
  12213. buffer: buffer,
  12214. object: object,
  12215. opaque: null,
  12216. transparent: null
  12217. }
  12218. );
  12219. };
  12220. function addBufferImmediate ( objlist, object ) {
  12221. objlist.push(
  12222. {
  12223. object: object,
  12224. opaque: null,
  12225. transparent: null
  12226. }
  12227. );
  12228. };
  12229. // Objects updates
  12230. function updateObject ( object ) {
  12231. var geometry = object.geometry,
  12232. geometryGroup, customAttributesDirty, material;
  12233. if ( object instanceof THREE.Mesh ) {
  12234. if ( geometry instanceof THREE.BufferGeometry ) {
  12235. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12236. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12237. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12238. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12239. }
  12240. geometry.verticesNeedUpdate = false;
  12241. geometry.elementsNeedUpdate = false;
  12242. geometry.uvsNeedUpdate = false;
  12243. geometry.normalsNeedUpdate = false;
  12244. geometry.colorsNeedUpdate = false;
  12245. geometry.tangentsNeedUpdate = false;
  12246. } else {
  12247. // check all geometry groups
  12248. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12249. geometryGroup = geometry.geometryGroupsList[ i ];
  12250. material = getBufferMaterial( object, geometryGroup );
  12251. if ( geometry.buffersNeedUpdate ) {
  12252. initMeshBuffers( geometryGroup, object );
  12253. }
  12254. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12255. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12256. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12257. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12258. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12259. }
  12260. }
  12261. geometry.verticesNeedUpdate = false;
  12262. geometry.morphTargetsNeedUpdate = false;
  12263. geometry.elementsNeedUpdate = false;
  12264. geometry.uvsNeedUpdate = false;
  12265. geometry.normalsNeedUpdate = false;
  12266. geometry.colorsNeedUpdate = false;
  12267. geometry.tangentsNeedUpdate = false;
  12268. geometry.buffersNeedUpdate = false;
  12269. material.attributes && clearCustomAttributes( material );
  12270. }
  12271. } else if ( object instanceof THREE.Ribbon ) {
  12272. material = getBufferMaterial( object, geometry );
  12273. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12274. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12275. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12276. }
  12277. geometry.verticesNeedUpdate = false;
  12278. geometry.colorsNeedUpdate = false;
  12279. geometry.normalsNeedUpdate = false;
  12280. material.attributes && clearCustomAttributes( material );
  12281. } else if ( object instanceof THREE.Line ) {
  12282. material = getBufferMaterial( object, geometry );
  12283. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12284. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12285. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12286. }
  12287. geometry.verticesNeedUpdate = false;
  12288. geometry.colorsNeedUpdate = false;
  12289. geometry.lineDistancesNeedUpdate = false;
  12290. material.attributes && clearCustomAttributes( material );
  12291. } else if ( object instanceof THREE.ParticleSystem ) {
  12292. if ( geometry instanceof THREE.BufferGeometry ) {
  12293. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12294. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12295. }
  12296. geometry.verticesNeedUpdate = false;
  12297. geometry.colorsNeedUpdate = false;
  12298. } else {
  12299. material = getBufferMaterial( object, geometry );
  12300. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12301. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12302. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12303. }
  12304. geometry.verticesNeedUpdate = false;
  12305. geometry.colorsNeedUpdate = false;
  12306. material.attributes && clearCustomAttributes( material );
  12307. }
  12308. }
  12309. };
  12310. // Objects updates - custom attributes check
  12311. function areCustomAttributesDirty ( material ) {
  12312. for ( var a in material.attributes ) {
  12313. if ( material.attributes[ a ].needsUpdate ) return true;
  12314. }
  12315. return false;
  12316. };
  12317. function clearCustomAttributes ( material ) {
  12318. for ( var a in material.attributes ) {
  12319. material.attributes[ a ].needsUpdate = false;
  12320. }
  12321. };
  12322. // Objects removal
  12323. function removeObject ( object, scene ) {
  12324. if ( object instanceof THREE.Mesh ||
  12325. object instanceof THREE.ParticleSystem ||
  12326. object instanceof THREE.Ribbon ||
  12327. object instanceof THREE.Line ) {
  12328. removeInstances( scene.__webglObjects, object );
  12329. } else if ( object instanceof THREE.Sprite ) {
  12330. removeInstancesDirect( scene.__webglSprites, object );
  12331. } else if ( object instanceof THREE.LensFlare ) {
  12332. removeInstancesDirect( scene.__webglFlares, object );
  12333. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12334. removeInstances( scene.__webglObjectsImmediate, object );
  12335. }
  12336. object.__webglActive = false;
  12337. };
  12338. function removeInstances ( objlist, object ) {
  12339. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12340. if ( objlist[ o ].object === object ) {
  12341. objlist.splice( o, 1 );
  12342. }
  12343. }
  12344. };
  12345. function removeInstancesDirect ( objlist, object ) {
  12346. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12347. if ( objlist[ o ] === object ) {
  12348. objlist.splice( o, 1 );
  12349. }
  12350. }
  12351. };
  12352. // Materials
  12353. this.initMaterial = function ( material, lights, fog, object ) {
  12354. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  12355. if ( material instanceof THREE.MeshDepthMaterial ) {
  12356. shaderID = 'depth';
  12357. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12358. shaderID = 'normal';
  12359. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12360. shaderID = 'basic';
  12361. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12362. shaderID = 'lambert';
  12363. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12364. shaderID = 'phong';
  12365. } else if ( material instanceof THREE.LineBasicMaterial ) {
  12366. shaderID = 'basic';
  12367. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12368. shaderID = 'dashed';
  12369. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12370. shaderID = 'particle_basic';
  12371. }
  12372. if ( shaderID ) {
  12373. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  12374. }
  12375. // heuristics to create shader parameters according to lights in the scene
  12376. // (not to blow over maxLights budget)
  12377. maxLightCount = allocateLights( lights );
  12378. maxShadows = allocateShadows( lights );
  12379. maxBones = allocateBones( object );
  12380. parameters = {
  12381. map: !!material.map,
  12382. envMap: !!material.envMap,
  12383. lightMap: !!material.lightMap,
  12384. bumpMap: !!material.bumpMap,
  12385. normalMap: !!material.normalMap,
  12386. specularMap: !!material.specularMap,
  12387. vertexColors: material.vertexColors,
  12388. fog: fog,
  12389. useFog: material.fog,
  12390. fogExp: fog instanceof THREE.FogExp2,
  12391. sizeAttenuation: material.sizeAttenuation,
  12392. skinning: material.skinning,
  12393. maxBones: maxBones,
  12394. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  12395. boneTextureWidth: object && object.boneTextureWidth,
  12396. boneTextureHeight: object && object.boneTextureHeight,
  12397. morphTargets: material.morphTargets,
  12398. morphNormals: material.morphNormals,
  12399. maxMorphTargets: this.maxMorphTargets,
  12400. maxMorphNormals: this.maxMorphNormals,
  12401. maxDirLights: maxLightCount.directional,
  12402. maxPointLights: maxLightCount.point,
  12403. maxSpotLights: maxLightCount.spot,
  12404. maxHemiLights: maxLightCount.hemi,
  12405. maxShadows: maxShadows,
  12406. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  12407. shadowMapSoft: this.shadowMapSoft,
  12408. shadowMapDebug: this.shadowMapDebug,
  12409. shadowMapCascade: this.shadowMapCascade,
  12410. alphaTest: material.alphaTest,
  12411. metal: material.metal,
  12412. perPixel: material.perPixel,
  12413. wrapAround: material.wrapAround,
  12414. doubleSided: material.side === THREE.DoubleSide,
  12415. flipSided: material.side === THREE.BackSide
  12416. };
  12417. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  12418. var attributes = material.program.attributes;
  12419. if ( material.morphTargets ) {
  12420. material.numSupportedMorphTargets = 0;
  12421. var id, base = "morphTarget";
  12422. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  12423. id = base + i;
  12424. if ( attributes[ id ] >= 0 ) {
  12425. material.numSupportedMorphTargets ++;
  12426. }
  12427. }
  12428. }
  12429. if ( material.morphNormals ) {
  12430. material.numSupportedMorphNormals = 0;
  12431. var id, base = "morphNormal";
  12432. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  12433. id = base + i;
  12434. if ( attributes[ id ] >= 0 ) {
  12435. material.numSupportedMorphNormals ++;
  12436. }
  12437. }
  12438. }
  12439. material.uniformsList = [];
  12440. for ( u in material.uniforms ) {
  12441. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  12442. }
  12443. };
  12444. function setMaterialShaders( material, shaders ) {
  12445. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  12446. material.vertexShader = shaders.vertexShader;
  12447. material.fragmentShader = shaders.fragmentShader;
  12448. };
  12449. function setProgram( camera, lights, fog, material, object ) {
  12450. _usedTextureUnits = 0;
  12451. if ( material.needsUpdate ) {
  12452. if ( material.program ) _this.deallocateMaterial( material );
  12453. _this.initMaterial( material, lights, fog, object );
  12454. material.needsUpdate = false;
  12455. }
  12456. if ( material.morphTargets ) {
  12457. if ( ! object.__webglMorphTargetInfluences ) {
  12458. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  12459. }
  12460. }
  12461. var refreshMaterial = false;
  12462. var program = material.program,
  12463. p_uniforms = program.uniforms,
  12464. m_uniforms = material.uniforms;
  12465. if ( program !== _currentProgram ) {
  12466. _gl.useProgram( program );
  12467. _currentProgram = program;
  12468. refreshMaterial = true;
  12469. }
  12470. if ( material.id !== _currentMaterialId ) {
  12471. _currentMaterialId = material.id;
  12472. refreshMaterial = true;
  12473. }
  12474. if ( refreshMaterial || camera !== _currentCamera ) {
  12475. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  12476. if ( camera !== _currentCamera ) _currentCamera = camera;
  12477. }
  12478. // skinning uniforms must be set even if material didn't change
  12479. // auto-setting of texture unit for bone texture must go before other textures
  12480. // not sure why, but otherwise weird things happen
  12481. if ( material.skinning ) {
  12482. if ( _supportsBoneTextures && object.useVertexTexture ) {
  12483. if ( p_uniforms.boneTexture !== null ) {
  12484. var textureUnit = getTextureUnit();
  12485. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12486. _this.setTexture( object.boneTexture, textureUnit );
  12487. }
  12488. } else {
  12489. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12490. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  12491. }
  12492. }
  12493. }
  12494. if ( refreshMaterial ) {
  12495. // refresh uniforms common to several materials
  12496. if ( fog && material.fog ) {
  12497. refreshUniformsFog( m_uniforms, fog );
  12498. }
  12499. if ( material instanceof THREE.MeshPhongMaterial ||
  12500. material instanceof THREE.MeshLambertMaterial ||
  12501. material.lights ) {
  12502. if ( _lightsNeedUpdate ) {
  12503. setupLights( program, lights );
  12504. _lightsNeedUpdate = false;
  12505. }
  12506. refreshUniformsLights( m_uniforms, _lights );
  12507. }
  12508. if ( material instanceof THREE.MeshBasicMaterial ||
  12509. material instanceof THREE.MeshLambertMaterial ||
  12510. material instanceof THREE.MeshPhongMaterial ) {
  12511. refreshUniformsCommon( m_uniforms, material );
  12512. }
  12513. // refresh single material specific uniforms
  12514. if ( material instanceof THREE.LineBasicMaterial ) {
  12515. refreshUniformsLine( m_uniforms, material );
  12516. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12517. refreshUniformsLine( m_uniforms, material );
  12518. refreshUniformsDash( m_uniforms, material );
  12519. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12520. refreshUniformsParticle( m_uniforms, material );
  12521. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12522. refreshUniformsPhong( m_uniforms, material );
  12523. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12524. refreshUniformsLambert( m_uniforms, material );
  12525. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12526. m_uniforms.mNear.value = camera.near;
  12527. m_uniforms.mFar.value = camera.far;
  12528. m_uniforms.opacity.value = material.opacity;
  12529. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12530. m_uniforms.opacity.value = material.opacity;
  12531. }
  12532. if ( object.receiveShadow && ! material._shadowPass ) {
  12533. refreshUniformsShadow( m_uniforms, lights );
  12534. }
  12535. // load common uniforms
  12536. loadUniformsGeneric( program, material.uniformsList );
  12537. // load material specific uniforms
  12538. // (shader material also gets them for the sake of genericity)
  12539. if ( material instanceof THREE.ShaderMaterial ||
  12540. material instanceof THREE.MeshPhongMaterial ||
  12541. material.envMap ) {
  12542. if ( p_uniforms.cameraPosition !== null ) {
  12543. var position = camera.matrixWorld.getPosition();
  12544. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  12545. }
  12546. }
  12547. if ( material instanceof THREE.MeshPhongMaterial ||
  12548. material instanceof THREE.MeshLambertMaterial ||
  12549. material instanceof THREE.ShaderMaterial ||
  12550. material.skinning ) {
  12551. if ( p_uniforms.viewMatrix !== null ) {
  12552. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  12553. }
  12554. }
  12555. }
  12556. loadUniformsMatrices( p_uniforms, object );
  12557. if ( p_uniforms.modelMatrix !== null ) {
  12558. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12559. }
  12560. return program;
  12561. };
  12562. // Uniforms (refresh uniforms objects)
  12563. function refreshUniformsCommon ( uniforms, material ) {
  12564. uniforms.opacity.value = material.opacity;
  12565. if ( _this.gammaInput ) {
  12566. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12567. } else {
  12568. uniforms.diffuse.value = material.color;
  12569. }
  12570. uniforms.map.value = material.map;
  12571. uniforms.lightMap.value = material.lightMap;
  12572. uniforms.specularMap.value = material.specularMap;
  12573. if ( material.bumpMap ) {
  12574. uniforms.bumpMap.value = material.bumpMap;
  12575. uniforms.bumpScale.value = material.bumpScale;
  12576. }
  12577. if ( material.normalMap ) {
  12578. uniforms.normalMap.value = material.normalMap;
  12579. uniforms.normalScale.value.copy( material.normalScale );
  12580. }
  12581. // uv repeat and offset setting priorities
  12582. // 1. color map
  12583. // 2. specular map
  12584. // 3. normal map
  12585. // 4. bump map
  12586. var uvScaleMap;
  12587. if ( material.map ) {
  12588. uvScaleMap = material.map;
  12589. } else if ( material.specularMap ) {
  12590. uvScaleMap = material.specularMap;
  12591. } else if ( material.normalMap ) {
  12592. uvScaleMap = material.normalMap;
  12593. } else if ( material.bumpMap ) {
  12594. uvScaleMap = material.bumpMap;
  12595. }
  12596. if ( uvScaleMap !== undefined ) {
  12597. var offset = uvScaleMap.offset;
  12598. var repeat = uvScaleMap.repeat;
  12599. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12600. }
  12601. uniforms.envMap.value = material.envMap;
  12602. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12603. if ( _this.gammaInput ) {
  12604. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12605. uniforms.reflectivity.value = material.reflectivity;
  12606. } else {
  12607. uniforms.reflectivity.value = material.reflectivity;
  12608. }
  12609. uniforms.refractionRatio.value = material.refractionRatio;
  12610. uniforms.combine.value = material.combine;
  12611. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12612. };
  12613. function refreshUniformsLine ( uniforms, material ) {
  12614. uniforms.diffuse.value = material.color;
  12615. uniforms.opacity.value = material.opacity;
  12616. };
  12617. function refreshUniformsDash ( uniforms, material ) {
  12618. uniforms.dashSize.value = material.dashSize;
  12619. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12620. uniforms.scale.value = material.scale;
  12621. };
  12622. function refreshUniformsParticle ( uniforms, material ) {
  12623. uniforms.psColor.value = material.color;
  12624. uniforms.opacity.value = material.opacity;
  12625. uniforms.size.value = material.size;
  12626. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12627. uniforms.map.value = material.map;
  12628. };
  12629. function refreshUniformsFog ( uniforms, fog ) {
  12630. uniforms.fogColor.value = fog.color;
  12631. if ( fog instanceof THREE.Fog ) {
  12632. uniforms.fogNear.value = fog.near;
  12633. uniforms.fogFar.value = fog.far;
  12634. } else if ( fog instanceof THREE.FogExp2 ) {
  12635. uniforms.fogDensity.value = fog.density;
  12636. }
  12637. };
  12638. function refreshUniformsPhong ( uniforms, material ) {
  12639. uniforms.shininess.value = material.shininess;
  12640. if ( _this.gammaInput ) {
  12641. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12642. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12643. uniforms.specular.value.copyGammaToLinear( material.specular );
  12644. } else {
  12645. uniforms.ambient.value = material.ambient;
  12646. uniforms.emissive.value = material.emissive;
  12647. uniforms.specular.value = material.specular;
  12648. }
  12649. if ( material.wrapAround ) {
  12650. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12651. }
  12652. };
  12653. function refreshUniformsLambert ( uniforms, material ) {
  12654. if ( _this.gammaInput ) {
  12655. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12656. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12657. } else {
  12658. uniforms.ambient.value = material.ambient;
  12659. uniforms.emissive.value = material.emissive;
  12660. }
  12661. if ( material.wrapAround ) {
  12662. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12663. }
  12664. };
  12665. function refreshUniformsLights ( uniforms, lights ) {
  12666. uniforms.ambientLightColor.value = lights.ambient;
  12667. uniforms.directionalLightColor.value = lights.directional.colors;
  12668. uniforms.directionalLightDirection.value = lights.directional.positions;
  12669. uniforms.pointLightColor.value = lights.point.colors;
  12670. uniforms.pointLightPosition.value = lights.point.positions;
  12671. uniforms.pointLightDistance.value = lights.point.distances;
  12672. uniforms.spotLightColor.value = lights.spot.colors;
  12673. uniforms.spotLightPosition.value = lights.spot.positions;
  12674. uniforms.spotLightDistance.value = lights.spot.distances;
  12675. uniforms.spotLightDirection.value = lights.spot.directions;
  12676. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12677. uniforms.spotLightExponent.value = lights.spot.exponents;
  12678. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12679. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12680. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12681. };
  12682. function refreshUniformsShadow ( uniforms, lights ) {
  12683. if ( uniforms.shadowMatrix ) {
  12684. var j = 0;
  12685. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12686. var light = lights[ i ];
  12687. if ( ! light.castShadow ) continue;
  12688. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12689. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12690. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12691. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12692. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12693. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12694. j ++;
  12695. }
  12696. }
  12697. }
  12698. };
  12699. // Uniforms (load to GPU)
  12700. function loadUniformsMatrices ( uniforms, object ) {
  12701. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12702. if ( uniforms.normalMatrix ) {
  12703. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12704. }
  12705. };
  12706. function getTextureUnit() {
  12707. var textureUnit = _usedTextureUnits;
  12708. if ( textureUnit >= _maxTextures ) {
  12709. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  12710. }
  12711. _usedTextureUnits += 1;
  12712. return textureUnit;
  12713. };
  12714. function loadUniformsGeneric ( program, uniforms ) {
  12715. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12716. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12717. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12718. if ( !location ) continue;
  12719. uniform = uniforms[ j ][ 0 ];
  12720. type = uniform.type;
  12721. value = uniform.value;
  12722. if ( type === "i" ) { // single integer
  12723. _gl.uniform1i( location, value );
  12724. } else if ( type === "f" ) { // single float
  12725. _gl.uniform1f( location, value );
  12726. } else if ( type === "v2" ) { // single THREE.Vector2
  12727. _gl.uniform2f( location, value.x, value.y );
  12728. } else if ( type === "v3" ) { // single THREE.Vector3
  12729. _gl.uniform3f( location, value.x, value.y, value.z );
  12730. } else if ( type === "v4" ) { // single THREE.Vector4
  12731. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12732. } else if ( type === "c" ) { // single THREE.Color
  12733. _gl.uniform3f( location, value.r, value.g, value.b );
  12734. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12735. _gl.uniform1iv( location, value );
  12736. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12737. _gl.uniform3iv( location, value );
  12738. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12739. _gl.uniform1fv( location, value );
  12740. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12741. _gl.uniform3fv( location, value );
  12742. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12743. if ( uniform._array === undefined ) {
  12744. uniform._array = new Float32Array( 2 * value.length );
  12745. }
  12746. for ( i = 0, il = value.length; i < il; i ++ ) {
  12747. offset = i * 2;
  12748. uniform._array[ offset ] = value[ i ].x;
  12749. uniform._array[ offset + 1 ] = value[ i ].y;
  12750. }
  12751. _gl.uniform2fv( location, uniform._array );
  12752. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12753. if ( uniform._array === undefined ) {
  12754. uniform._array = new Float32Array( 3 * value.length );
  12755. }
  12756. for ( i = 0, il = value.length; i < il; i ++ ) {
  12757. offset = i * 3;
  12758. uniform._array[ offset ] = value[ i ].x;
  12759. uniform._array[ offset + 1 ] = value[ i ].y;
  12760. uniform._array[ offset + 2 ] = value[ i ].z;
  12761. }
  12762. _gl.uniform3fv( location, uniform._array );
  12763. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12764. if ( uniform._array === undefined ) {
  12765. uniform._array = new Float32Array( 4 * value.length );
  12766. }
  12767. for ( i = 0, il = value.length; i < il; i ++ ) {
  12768. offset = i * 4;
  12769. uniform._array[ offset ] = value[ i ].x;
  12770. uniform._array[ offset + 1 ] = value[ i ].y;
  12771. uniform._array[ offset + 2 ] = value[ i ].z;
  12772. uniform._array[ offset + 3 ] = value[ i ].w;
  12773. }
  12774. _gl.uniform4fv( location, uniform._array );
  12775. } else if ( type === "m4") { // single THREE.Matrix4
  12776. if ( uniform._array === undefined ) {
  12777. uniform._array = new Float32Array( 16 );
  12778. }
  12779. value.flattenToArray( uniform._array );
  12780. _gl.uniformMatrix4fv( location, false, uniform._array );
  12781. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12782. if ( uniform._array === undefined ) {
  12783. uniform._array = new Float32Array( 16 * value.length );
  12784. }
  12785. for ( i = 0, il = value.length; i < il; i ++ ) {
  12786. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12787. }
  12788. _gl.uniformMatrix4fv( location, false, uniform._array );
  12789. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12790. texture = value;
  12791. textureUnit = getTextureUnit();
  12792. _gl.uniform1i( location, textureUnit );
  12793. if ( !texture ) continue;
  12794. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12795. setCubeTexture( texture, textureUnit );
  12796. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12797. setCubeTextureDynamic( texture, textureUnit );
  12798. } else {
  12799. _this.setTexture( texture, textureUnit );
  12800. }
  12801. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12802. if ( uniform._array === undefined ) {
  12803. uniform._array = [];
  12804. }
  12805. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12806. uniform._array[ i ] = getTextureUnit();
  12807. }
  12808. _gl.uniform1iv( location, uniform._array );
  12809. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12810. texture = uniform.value[ i ];
  12811. textureUnit = uniform._array[ i ];
  12812. if ( !texture ) continue;
  12813. _this.setTexture( texture, textureUnit );
  12814. }
  12815. }
  12816. }
  12817. };
  12818. function setupMatrices ( object, camera ) {
  12819. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12820. object._normalMatrix.getInverse( object._modelViewMatrix );
  12821. object._normalMatrix.transpose();
  12822. };
  12823. //
  12824. function setColorGamma( array, offset, color, intensitySq ) {
  12825. array[ offset ] = color.r * color.r * intensitySq;
  12826. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12827. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12828. };
  12829. function setColorLinear( array, offset, color, intensity ) {
  12830. array[ offset ] = color.r * intensity;
  12831. array[ offset + 1 ] = color.g * intensity;
  12832. array[ offset + 2 ] = color.b * intensity;
  12833. };
  12834. function setupLights ( program, lights ) {
  12835. var l, ll, light, n,
  12836. r = 0, g = 0, b = 0,
  12837. color, skyColor, groundColor,
  12838. intensity, intensitySq,
  12839. position,
  12840. distance,
  12841. zlights = _lights,
  12842. dirColors = zlights.directional.colors,
  12843. dirPositions = zlights.directional.positions,
  12844. pointColors = zlights.point.colors,
  12845. pointPositions = zlights.point.positions,
  12846. pointDistances = zlights.point.distances,
  12847. spotColors = zlights.spot.colors,
  12848. spotPositions = zlights.spot.positions,
  12849. spotDistances = zlights.spot.distances,
  12850. spotDirections = zlights.spot.directions,
  12851. spotAnglesCos = zlights.spot.anglesCos,
  12852. spotExponents = zlights.spot.exponents,
  12853. hemiSkyColors = zlights.hemi.skyColors,
  12854. hemiGroundColors = zlights.hemi.groundColors,
  12855. hemiPositions = zlights.hemi.positions,
  12856. dirLength = 0,
  12857. pointLength = 0,
  12858. spotLength = 0,
  12859. hemiLength = 0,
  12860. dirCount = 0,
  12861. pointCount = 0,
  12862. spotCount = 0,
  12863. hemiCount = 0,
  12864. dirOffset = 0,
  12865. pointOffset = 0,
  12866. spotOffset = 0,
  12867. hemiOffset = 0;
  12868. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12869. light = lights[ l ];
  12870. if ( light.onlyShadow ) continue;
  12871. color = light.color;
  12872. intensity = light.intensity;
  12873. distance = light.distance;
  12874. if ( light instanceof THREE.AmbientLight ) {
  12875. if ( ! light.visible ) continue;
  12876. if ( _this.gammaInput ) {
  12877. r += color.r * color.r;
  12878. g += color.g * color.g;
  12879. b += color.b * color.b;
  12880. } else {
  12881. r += color.r;
  12882. g += color.g;
  12883. b += color.b;
  12884. }
  12885. } else if ( light instanceof THREE.DirectionalLight ) {
  12886. dirCount += 1;
  12887. if ( ! light.visible ) continue;
  12888. dirOffset = dirLength * 3;
  12889. if ( _this.gammaInput ) {
  12890. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12891. } else {
  12892. setColorLinear( dirColors, dirOffset, color, intensity );
  12893. }
  12894. _direction.copy( light.matrixWorld.getPosition() );
  12895. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12896. _direction.normalize();
  12897. dirPositions[ dirOffset ] = _direction.x;
  12898. dirPositions[ dirOffset + 1 ] = _direction.y;
  12899. dirPositions[ dirOffset + 2 ] = _direction.z;
  12900. dirLength += 1;
  12901. } else if ( light instanceof THREE.PointLight ) {
  12902. pointCount += 1;
  12903. if ( ! light.visible ) continue;
  12904. pointOffset = pointLength * 3;
  12905. if ( _this.gammaInput ) {
  12906. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12907. } else {
  12908. setColorLinear( pointColors, pointOffset, color, intensity );
  12909. }
  12910. position = light.matrixWorld.getPosition();
  12911. pointPositions[ pointOffset ] = position.x;
  12912. pointPositions[ pointOffset + 1 ] = position.y;
  12913. pointPositions[ pointOffset + 2 ] = position.z;
  12914. pointDistances[ pointLength ] = distance;
  12915. pointLength += 1;
  12916. } else if ( light instanceof THREE.SpotLight ) {
  12917. spotCount += 1;
  12918. if ( ! light.visible ) continue;
  12919. spotOffset = spotLength * 3;
  12920. if ( _this.gammaInput ) {
  12921. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12922. } else {
  12923. setColorLinear( spotColors, spotOffset, color, intensity );
  12924. }
  12925. position = light.matrixWorld.getPosition();
  12926. spotPositions[ spotOffset ] = position.x;
  12927. spotPositions[ spotOffset + 1 ] = position.y;
  12928. spotPositions[ spotOffset + 2 ] = position.z;
  12929. spotDistances[ spotLength ] = distance;
  12930. _direction.copy( position );
  12931. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12932. _direction.normalize();
  12933. spotDirections[ spotOffset ] = _direction.x;
  12934. spotDirections[ spotOffset + 1 ] = _direction.y;
  12935. spotDirections[ spotOffset + 2 ] = _direction.z;
  12936. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  12937. spotExponents[ spotLength ] = light.exponent;
  12938. spotLength += 1;
  12939. } else if ( light instanceof THREE.HemisphereLight ) {
  12940. hemiCount += 1;
  12941. if ( ! light.visible ) continue;
  12942. skyColor = light.color;
  12943. groundColor = light.groundColor;
  12944. hemiOffset = hemiLength * 3;
  12945. if ( _this.gammaInput ) {
  12946. intensitySq = intensity * intensity;
  12947. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12948. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12949. } else {
  12950. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12951. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12952. }
  12953. _direction.copy( light.matrixWorld.getPosition() );
  12954. _direction.normalize();
  12955. hemiPositions[ hemiOffset ] = _direction.x;
  12956. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  12957. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  12958. hemiLength += 1;
  12959. }
  12960. }
  12961. // null eventual remains from removed lights
  12962. // (this is to avoid if in shader)
  12963. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  12964. for ( l = dirLength * 3, ll = Math.max( dirPositions.length, dirCount * 3 ); l < ll; l ++ ) dirPositions[ l ] = 0.0;
  12965. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  12966. for ( l = pointLength * 3, ll = Math.max( pointPositions.length, pointCount * 3 ); l < ll; l ++ ) pointPositions[ l ] = 0.0;
  12967. for ( l = pointLength, ll = Math.max( pointDistances.length, pointCount ); l < ll; l ++ ) pointDistances[ l ] = 0.0;
  12968. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  12969. for ( l = spotLength * 3, ll = Math.max( spotPositions.length, spotCount * 3 ); l < ll; l ++ ) spotPositions[ l ] = 0.0;
  12970. for ( l = spotLength * 3, ll = Math.max( spotDirections.length, spotCount * 3 ); l < ll; l ++ ) spotDirections[ l ] = 0.0;
  12971. for ( l = spotLength, ll = Math.max( spotAnglesCos.length, spotCount ); l < ll; l ++ ) spotAnglesCos[ l ] = 0.0;
  12972. for ( l = spotLength, ll = Math.max( spotExponents.length, spotCount ); l < ll; l ++ ) spotExponents[ l ] = 0.0;
  12973. for ( l = spotLength, ll = Math.max( spotDistances.length, spotCount ); l < ll; l ++ ) spotDistances[ l ] = 0.0;
  12974. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12975. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12976. for ( l = hemiLength * 3, ll = Math.max( hemiPositions.length, hemiCount * 3 ); l < ll; l ++ ) hemiPositions[ l ] = 0.0;
  12977. zlights.directional.length = dirLength;
  12978. zlights.point.length = pointLength;
  12979. zlights.spot.length = spotLength;
  12980. zlights.hemi.length = hemiLength;
  12981. zlights.ambient[ 0 ] = r;
  12982. zlights.ambient[ 1 ] = g;
  12983. zlights.ambient[ 2 ] = b;
  12984. };
  12985. // GL state setting
  12986. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  12987. if ( cullFace === THREE.CullFaceNone ) {
  12988. _gl.disable( _gl.CULL_FACE );
  12989. } else {
  12990. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  12991. _gl.frontFace( _gl.CW );
  12992. } else {
  12993. _gl.frontFace( _gl.CCW );
  12994. }
  12995. if ( cullFace === THREE.CullFaceBack ) {
  12996. _gl.cullFace( _gl.BACK );
  12997. } else if ( cullFace === THREE.CullFaceFront ) {
  12998. _gl.cullFace( _gl.FRONT );
  12999. } else {
  13000. _gl.cullFace( _gl.FRONT_AND_BACK );
  13001. }
  13002. _gl.enable( _gl.CULL_FACE );
  13003. }
  13004. };
  13005. this.setMaterialFaces = function ( material ) {
  13006. var doubleSided = material.side === THREE.DoubleSide;
  13007. var flipSided = material.side === THREE.BackSide;
  13008. if ( _oldDoubleSided !== doubleSided ) {
  13009. if ( doubleSided ) {
  13010. _gl.disable( _gl.CULL_FACE );
  13011. } else {
  13012. _gl.enable( _gl.CULL_FACE );
  13013. }
  13014. _oldDoubleSided = doubleSided;
  13015. }
  13016. if ( _oldFlipSided !== flipSided ) {
  13017. if ( flipSided ) {
  13018. _gl.frontFace( _gl.CW );
  13019. } else {
  13020. _gl.frontFace( _gl.CCW );
  13021. }
  13022. _oldFlipSided = flipSided;
  13023. }
  13024. };
  13025. this.setDepthTest = function ( depthTest ) {
  13026. if ( _oldDepthTest !== depthTest ) {
  13027. if ( depthTest ) {
  13028. _gl.enable( _gl.DEPTH_TEST );
  13029. } else {
  13030. _gl.disable( _gl.DEPTH_TEST );
  13031. }
  13032. _oldDepthTest = depthTest;
  13033. }
  13034. };
  13035. this.setDepthWrite = function ( depthWrite ) {
  13036. if ( _oldDepthWrite !== depthWrite ) {
  13037. _gl.depthMask( depthWrite );
  13038. _oldDepthWrite = depthWrite;
  13039. }
  13040. };
  13041. function setLineWidth ( width ) {
  13042. if ( width !== _oldLineWidth ) {
  13043. _gl.lineWidth( width );
  13044. _oldLineWidth = width;
  13045. }
  13046. };
  13047. function setPolygonOffset ( polygonoffset, factor, units ) {
  13048. if ( _oldPolygonOffset !== polygonoffset ) {
  13049. if ( polygonoffset ) {
  13050. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13051. } else {
  13052. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13053. }
  13054. _oldPolygonOffset = polygonoffset;
  13055. }
  13056. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13057. _gl.polygonOffset( factor, units );
  13058. _oldPolygonOffsetFactor = factor;
  13059. _oldPolygonOffsetUnits = units;
  13060. }
  13061. };
  13062. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13063. if ( blending !== _oldBlending ) {
  13064. if ( blending === THREE.NoBlending ) {
  13065. _gl.disable( _gl.BLEND );
  13066. } else if ( blending === THREE.AdditiveBlending ) {
  13067. _gl.enable( _gl.BLEND );
  13068. _gl.blendEquation( _gl.FUNC_ADD );
  13069. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13070. } else if ( blending === THREE.SubtractiveBlending ) {
  13071. // TODO: Find blendFuncSeparate() combination
  13072. _gl.enable( _gl.BLEND );
  13073. _gl.blendEquation( _gl.FUNC_ADD );
  13074. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13075. } else if ( blending === THREE.MultiplyBlending ) {
  13076. // TODO: Find blendFuncSeparate() combination
  13077. _gl.enable( _gl.BLEND );
  13078. _gl.blendEquation( _gl.FUNC_ADD );
  13079. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13080. } else if ( blending === THREE.CustomBlending ) {
  13081. _gl.enable( _gl.BLEND );
  13082. } else {
  13083. _gl.enable( _gl.BLEND );
  13084. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13085. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13086. }
  13087. _oldBlending = blending;
  13088. }
  13089. if ( blending === THREE.CustomBlending ) {
  13090. if ( blendEquation !== _oldBlendEquation ) {
  13091. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13092. _oldBlendEquation = blendEquation;
  13093. }
  13094. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13095. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13096. _oldBlendSrc = blendSrc;
  13097. _oldBlendDst = blendDst;
  13098. }
  13099. } else {
  13100. _oldBlendEquation = null;
  13101. _oldBlendSrc = null;
  13102. _oldBlendDst = null;
  13103. }
  13104. };
  13105. // Defines
  13106. function generateDefines ( defines ) {
  13107. var value, chunk, chunks = [];
  13108. for ( var d in defines ) {
  13109. value = defines[ d ];
  13110. if ( value === false ) continue;
  13111. chunk = "#define " + d + " " + value;
  13112. chunks.push( chunk );
  13113. }
  13114. return chunks.join( "\n" );
  13115. };
  13116. // Shaders
  13117. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13118. var p, pl, d, program, code;
  13119. var chunks = [];
  13120. // Generate code
  13121. if ( shaderID ) {
  13122. chunks.push( shaderID );
  13123. } else {
  13124. chunks.push( fragmentShader );
  13125. chunks.push( vertexShader );
  13126. }
  13127. for ( d in defines ) {
  13128. chunks.push( d );
  13129. chunks.push( defines[ d ] );
  13130. }
  13131. for ( p in parameters ) {
  13132. chunks.push( p );
  13133. chunks.push( parameters[ p ] );
  13134. }
  13135. code = chunks.join();
  13136. // Check if code has been already compiled
  13137. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13138. var programInfo = _programs[ p ];
  13139. if ( programInfo.code === code ) {
  13140. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13141. programInfo.usedTimes ++;
  13142. return programInfo.program;
  13143. }
  13144. }
  13145. //console.log( "building new program " );
  13146. //
  13147. var customDefines = generateDefines( defines );
  13148. //
  13149. program = _gl.createProgram();
  13150. var prefix_vertex = [
  13151. "precision " + _precision + " float;",
  13152. customDefines,
  13153. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13154. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13155. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13156. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13157. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13158. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13159. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13160. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13161. "#define MAX_SHADOWS " + parameters.maxShadows,
  13162. "#define MAX_BONES " + parameters.maxBones,
  13163. parameters.map ? "#define USE_MAP" : "",
  13164. parameters.envMap ? "#define USE_ENVMAP" : "",
  13165. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13166. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13167. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13168. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13169. parameters.vertexColors ? "#define USE_COLOR" : "",
  13170. parameters.skinning ? "#define USE_SKINNING" : "",
  13171. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13172. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13173. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13174. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13175. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13176. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13177. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13178. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13179. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13180. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13181. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13182. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13183. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13184. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13185. "uniform mat4 modelMatrix;",
  13186. "uniform mat4 modelViewMatrix;",
  13187. "uniform mat4 projectionMatrix;",
  13188. "uniform mat4 viewMatrix;",
  13189. "uniform mat3 normalMatrix;",
  13190. "uniform vec3 cameraPosition;",
  13191. "attribute vec3 position;",
  13192. "attribute vec3 normal;",
  13193. "attribute vec2 uv;",
  13194. "attribute vec2 uv2;",
  13195. "#ifdef USE_COLOR",
  13196. "attribute vec3 color;",
  13197. "#endif",
  13198. "#ifdef USE_MORPHTARGETS",
  13199. "attribute vec3 morphTarget0;",
  13200. "attribute vec3 morphTarget1;",
  13201. "attribute vec3 morphTarget2;",
  13202. "attribute vec3 morphTarget3;",
  13203. "#ifdef USE_MORPHNORMALS",
  13204. "attribute vec3 morphNormal0;",
  13205. "attribute vec3 morphNormal1;",
  13206. "attribute vec3 morphNormal2;",
  13207. "attribute vec3 morphNormal3;",
  13208. "#else",
  13209. "attribute vec3 morphTarget4;",
  13210. "attribute vec3 morphTarget5;",
  13211. "attribute vec3 morphTarget6;",
  13212. "attribute vec3 morphTarget7;",
  13213. "#endif",
  13214. "#endif",
  13215. "#ifdef USE_SKINNING",
  13216. "attribute vec4 skinIndex;",
  13217. "attribute vec4 skinWeight;",
  13218. "#endif",
  13219. ""
  13220. ].join("\n");
  13221. var prefix_fragment = [
  13222. "precision " + _precision + " float;",
  13223. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13224. customDefines,
  13225. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13226. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13227. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13228. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13229. "#define MAX_SHADOWS " + parameters.maxShadows,
  13230. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13231. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13232. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13233. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13234. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13235. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13236. parameters.map ? "#define USE_MAP" : "",
  13237. parameters.envMap ? "#define USE_ENVMAP" : "",
  13238. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13239. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13240. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13241. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13242. parameters.vertexColors ? "#define USE_COLOR" : "",
  13243. parameters.metal ? "#define METAL" : "",
  13244. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13245. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13246. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13247. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13248. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13249. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13250. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13251. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13252. "uniform mat4 viewMatrix;",
  13253. "uniform vec3 cameraPosition;",
  13254. ""
  13255. ].join("\n");
  13256. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13257. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13258. _gl.attachShader( program, glVertexShader );
  13259. _gl.attachShader( program, glFragmentShader );
  13260. _gl.linkProgram( program );
  13261. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13262. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13263. }
  13264. // clean up
  13265. _gl.deleteShader( glFragmentShader );
  13266. _gl.deleteShader( glVertexShader );
  13267. //console.log( prefix_fragment + fragmentShader );
  13268. //console.log( prefix_vertex + vertexShader );
  13269. program.uniforms = {};
  13270. program.attributes = {};
  13271. var identifiers, u, a, i;
  13272. // cache uniform locations
  13273. identifiers = [
  13274. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13275. 'morphTargetInfluences'
  13276. ];
  13277. if ( parameters.useVertexTexture ) {
  13278. identifiers.push( 'boneTexture' );
  13279. } else {
  13280. identifiers.push( 'boneGlobalMatrices' );
  13281. }
  13282. for ( u in uniforms ) {
  13283. identifiers.push( u );
  13284. }
  13285. cacheUniformLocations( program, identifiers );
  13286. // cache attributes locations
  13287. identifiers = [
  13288. "position", "normal", "uv", "uv2", "tangent", "color",
  13289. "skinIndex", "skinWeight", "lineDistance"
  13290. ];
  13291. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13292. identifiers.push( "morphTarget" + i );
  13293. }
  13294. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13295. identifiers.push( "morphNormal" + i );
  13296. }
  13297. for ( a in attributes ) {
  13298. identifiers.push( a );
  13299. }
  13300. cacheAttributeLocations( program, identifiers );
  13301. program.id = _programs_counter ++;
  13302. _programs.push( { program: program, code: code, usedTimes: 1 } );
  13303. _this.info.memory.programs = _programs.length;
  13304. return program;
  13305. };
  13306. // Shader parameters cache
  13307. function cacheUniformLocations ( program, identifiers ) {
  13308. var i, l, id;
  13309. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13310. id = identifiers[ i ];
  13311. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  13312. }
  13313. };
  13314. function cacheAttributeLocations ( program, identifiers ) {
  13315. var i, l, id;
  13316. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13317. id = identifiers[ i ];
  13318. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  13319. }
  13320. };
  13321. function addLineNumbers ( string ) {
  13322. var chunks = string.split( "\n" );
  13323. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  13324. // Chrome reports shader errors on lines
  13325. // starting counting from 1
  13326. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  13327. }
  13328. return chunks.join( "\n" );
  13329. };
  13330. function getShader ( type, string ) {
  13331. var shader;
  13332. if ( type === "fragment" ) {
  13333. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13334. } else if ( type === "vertex" ) {
  13335. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13336. }
  13337. _gl.shaderSource( shader, string );
  13338. _gl.compileShader( shader );
  13339. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13340. console.error( _gl.getShaderInfoLog( shader ) );
  13341. console.error( addLineNumbers( string ) );
  13342. return null;
  13343. }
  13344. return shader;
  13345. };
  13346. // Textures
  13347. function isPowerOfTwo ( value ) {
  13348. return ( value & ( value - 1 ) ) === 0;
  13349. };
  13350. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13351. if ( isImagePowerOfTwo ) {
  13352. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13353. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13354. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13355. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13356. } else {
  13357. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13358. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13359. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13360. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13361. }
  13362. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13363. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13364. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13365. texture.__oldAnisotropy = texture.anisotropy;
  13366. }
  13367. }
  13368. };
  13369. this.setTexture = function ( texture, slot ) {
  13370. if ( texture.needsUpdate ) {
  13371. if ( ! texture.__webglInit ) {
  13372. texture.__webglInit = true;
  13373. texture.__webglTexture = _gl.createTexture();
  13374. _this.info.memory.textures ++;
  13375. }
  13376. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13377. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13378. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13379. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13380. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13381. var image = texture.image,
  13382. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13383. glFormat = paramThreeToGL( texture.format ),
  13384. glType = paramThreeToGL( texture.type );
  13385. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13386. var mipmap, mipmaps = texture.mipmaps;
  13387. if ( texture instanceof THREE.DataTexture ) {
  13388. // use manually created mipmaps if available
  13389. // if there are no manual mipmaps
  13390. // set 0 level mipmap and then use GL to generate other mipmap levels
  13391. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13392. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13393. mipmap = mipmaps[ i ];
  13394. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13395. }
  13396. texture.generateMipmaps = false;
  13397. } else {
  13398. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13399. }
  13400. } else if ( texture instanceof THREE.CompressedTexture ) {
  13401. // compressed textures can only use manually created mipmaps
  13402. // WebGL can't generate mipmaps for DDS textures
  13403. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13404. mipmap = mipmaps[ i ];
  13405. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13406. }
  13407. } else { // regular Texture (image, video, canvas)
  13408. // use manually created mipmaps if available
  13409. // if there are no manual mipmaps
  13410. // set 0 level mipmap and then use GL to generate other mipmap levels
  13411. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13412. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13413. mipmap = mipmaps[ i ];
  13414. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13415. }
  13416. texture.generateMipmaps = false;
  13417. } else {
  13418. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13419. }
  13420. }
  13421. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13422. texture.needsUpdate = false;
  13423. if ( texture.onUpdate ) texture.onUpdate();
  13424. } else {
  13425. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13426. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13427. }
  13428. };
  13429. function clampToMaxSize ( image, maxSize ) {
  13430. if ( image.width <= maxSize && image.height <= maxSize ) {
  13431. return image;
  13432. }
  13433. // Warning: Scaling through the canvas will only work with images that use
  13434. // premultiplied alpha.
  13435. var maxDimension = Math.max( image.width, image.height );
  13436. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13437. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13438. var canvas = document.createElement( 'canvas' );
  13439. canvas.width = newWidth;
  13440. canvas.height = newHeight;
  13441. var ctx = canvas.getContext( "2d" );
  13442. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13443. return canvas;
  13444. }
  13445. function setCubeTexture ( texture, slot ) {
  13446. if ( texture.image.length === 6 ) {
  13447. if ( texture.needsUpdate ) {
  13448. if ( ! texture.image.__webglTextureCube ) {
  13449. texture.image.__webglTextureCube = _gl.createTexture();
  13450. _this.info.memory.textures ++;
  13451. }
  13452. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13453. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13454. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13455. var isCompressed = texture instanceof THREE.CompressedTexture;
  13456. var cubeImage = [];
  13457. for ( var i = 0; i < 6; i ++ ) {
  13458. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  13459. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13460. } else {
  13461. cubeImage[ i ] = texture.image[ i ];
  13462. }
  13463. }
  13464. var image = cubeImage[ 0 ],
  13465. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13466. glFormat = paramThreeToGL( texture.format ),
  13467. glType = paramThreeToGL( texture.type );
  13468. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13469. for ( var i = 0; i < 6; i ++ ) {
  13470. if ( isCompressed ) {
  13471. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13472. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13473. mipmap = mipmaps[ j ];
  13474. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13475. }
  13476. } else {
  13477. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13478. }
  13479. }
  13480. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13481. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13482. }
  13483. texture.needsUpdate = false;
  13484. if ( texture.onUpdate ) texture.onUpdate();
  13485. } else {
  13486. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13487. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13488. }
  13489. }
  13490. };
  13491. function setCubeTextureDynamic ( texture, slot ) {
  13492. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13493. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13494. };
  13495. // Render targets
  13496. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13497. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13498. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13499. };
  13500. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13501. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13502. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13503. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13504. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13505. /* For some reason this is not working. Defaulting to RGBA4.
  13506. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13507. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13508. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13509. */
  13510. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13511. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13512. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13513. } else {
  13514. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13515. }
  13516. };
  13517. this.setRenderTarget = function ( renderTarget ) {
  13518. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13519. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13520. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13521. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13522. renderTarget.__webglTexture = _gl.createTexture();
  13523. _this.info.memory.textures ++;
  13524. // Setup texture, create render and frame buffers
  13525. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13526. glFormat = paramThreeToGL( renderTarget.format ),
  13527. glType = paramThreeToGL( renderTarget.type );
  13528. if ( isCube ) {
  13529. renderTarget.__webglFramebuffer = [];
  13530. renderTarget.__webglRenderbuffer = [];
  13531. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13532. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13533. for ( var i = 0; i < 6; i ++ ) {
  13534. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13535. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13536. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13537. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13538. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13539. }
  13540. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13541. } else {
  13542. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13543. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13544. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13545. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13546. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13547. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13548. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13549. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13550. }
  13551. // Release everything
  13552. if ( isCube ) {
  13553. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13554. } else {
  13555. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13556. }
  13557. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13558. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  13559. }
  13560. var framebuffer, width, height, vx, vy;
  13561. if ( renderTarget ) {
  13562. if ( isCube ) {
  13563. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13564. } else {
  13565. framebuffer = renderTarget.__webglFramebuffer;
  13566. }
  13567. width = renderTarget.width;
  13568. height = renderTarget.height;
  13569. vx = 0;
  13570. vy = 0;
  13571. } else {
  13572. framebuffer = null;
  13573. width = _viewportWidth;
  13574. height = _viewportHeight;
  13575. vx = _viewportX;
  13576. vy = _viewportY;
  13577. }
  13578. if ( framebuffer !== _currentFramebuffer ) {
  13579. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13580. _gl.viewport( vx, vy, width, height );
  13581. _currentFramebuffer = framebuffer;
  13582. }
  13583. _currentWidth = width;
  13584. _currentHeight = height;
  13585. };
  13586. function updateRenderTargetMipmap ( renderTarget ) {
  13587. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13588. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13589. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13590. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13591. } else {
  13592. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13593. _gl.generateMipmap( _gl.TEXTURE_2D );
  13594. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13595. }
  13596. };
  13597. // Fallback filters for non-power-of-2 textures
  13598. function filterFallback ( f ) {
  13599. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13600. return _gl.NEAREST;
  13601. }
  13602. return _gl.LINEAR;
  13603. };
  13604. // Map three.js constants to WebGL constants
  13605. function paramThreeToGL ( p ) {
  13606. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13607. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13608. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13609. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13610. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13611. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13612. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13613. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13614. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13615. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13616. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13617. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13618. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13619. if ( p === THREE.ByteType ) return _gl.BYTE;
  13620. if ( p === THREE.ShortType ) return _gl.SHORT;
  13621. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13622. if ( p === THREE.IntType ) return _gl.INT;
  13623. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13624. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13625. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13626. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13627. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13628. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13629. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13630. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13631. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13632. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13633. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13634. if ( p === THREE.OneFactor ) return _gl.ONE;
  13635. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13636. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13637. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13638. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13639. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13640. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13641. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13642. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13643. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13644. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13645. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13646. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13647. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13648. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13649. }
  13650. return 0;
  13651. };
  13652. // Allocations
  13653. function allocateBones ( object ) {
  13654. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  13655. return 1024;
  13656. } else {
  13657. // default for when object is not specified
  13658. // ( for example when prebuilding shader
  13659. // to be used with multiple objects )
  13660. //
  13661. // - leave some extra space for other uniforms
  13662. // - limit here is ANGLE's 254 max uniform vectors
  13663. // (up to 54 should be safe)
  13664. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13665. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13666. var maxBones = nVertexMatrices;
  13667. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13668. maxBones = Math.min( object.bones.length, maxBones );
  13669. if ( maxBones < object.bones.length ) {
  13670. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  13671. }
  13672. }
  13673. return maxBones;
  13674. }
  13675. };
  13676. function allocateLights ( lights ) {
  13677. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  13678. dirLights = pointLights = spotLights = hemiLights = 0;
  13679. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13680. light = lights[ l ];
  13681. if ( light.onlyShadow ) continue;
  13682. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13683. if ( light instanceof THREE.PointLight ) pointLights ++;
  13684. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13685. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13686. }
  13687. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  13688. };
  13689. function allocateShadows ( lights ) {
  13690. var l, ll, light, maxShadows = 0;
  13691. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  13692. light = lights[ l ];
  13693. if ( ! light.castShadow ) continue;
  13694. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13695. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13696. }
  13697. return maxShadows;
  13698. };
  13699. // Initialization
  13700. function initGL () {
  13701. try {
  13702. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  13703. throw 'Error creating WebGL context.';
  13704. }
  13705. } catch ( error ) {
  13706. console.error( error );
  13707. }
  13708. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  13709. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  13710. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  13711. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  13712. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13713. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  13714. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  13715. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13716. if ( ! _glExtensionTextureFloat ) {
  13717. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  13718. }
  13719. if ( ! _glExtensionStandardDerivatives ) {
  13720. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  13721. }
  13722. if ( ! _glExtensionTextureFilterAnisotropic ) {
  13723. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  13724. }
  13725. if ( ! _glExtensionCompressedTextureS3TC ) {
  13726. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  13727. }
  13728. };
  13729. function setDefaultGLState () {
  13730. _gl.clearColor( 0, 0, 0, 1 );
  13731. _gl.clearDepth( 1 );
  13732. _gl.clearStencil( 0 );
  13733. _gl.enable( _gl.DEPTH_TEST );
  13734. _gl.depthFunc( _gl.LEQUAL );
  13735. _gl.frontFace( _gl.CCW );
  13736. _gl.cullFace( _gl.BACK );
  13737. _gl.enable( _gl.CULL_FACE );
  13738. _gl.enable( _gl.BLEND );
  13739. _gl.blendEquation( _gl.FUNC_ADD );
  13740. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  13741. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  13742. };
  13743. // default plugins (order is important)
  13744. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  13745. this.addPrePlugin( this.shadowMapPlugin );
  13746. this.addPostPlugin( new THREE.SpritePlugin() );
  13747. this.addPostPlugin( new THREE.LensFlarePlugin() );
  13748. };
  13749. /**
  13750. * @author szimek / https://github.com/szimek/
  13751. * @author alteredq / http://alteredqualia.com/
  13752. */
  13753. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13754. this.width = width;
  13755. this.height = height;
  13756. options = options || {};
  13757. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13758. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13759. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13760. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13761. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13762. this.offset = new THREE.Vector2( 0, 0 );
  13763. this.repeat = new THREE.Vector2( 1, 1 );
  13764. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13765. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13766. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13767. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13768. this.generateMipmaps = true;
  13769. };
  13770. THREE.WebGLRenderTarget.prototype.clone = function() {
  13771. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13772. tmp.wrapS = this.wrapS;
  13773. tmp.wrapT = this.wrapT;
  13774. tmp.magFilter = this.magFilter;
  13775. tmp.minFilter = this.minFilter;
  13776. tmp.anisotropy = this.anisotropy;
  13777. tmp.offset.copy( this.offset );
  13778. tmp.repeat.copy( this.repeat );
  13779. tmp.format = this.format;
  13780. tmp.type = this.type;
  13781. tmp.depthBuffer = this.depthBuffer;
  13782. tmp.stencilBuffer = this.stencilBuffer;
  13783. tmp.generateMipmaps = this.generateMipmaps;
  13784. return tmp;
  13785. };
  13786. /**
  13787. * @author alteredq / http://alteredqualia.com
  13788. */
  13789. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13790. THREE.WebGLRenderTarget.call( this, width, height, options );
  13791. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13792. };
  13793. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13794. /**
  13795. * @author mrdoob / http://mrdoob.com/
  13796. */
  13797. THREE.RenderableVertex = function () {
  13798. this.positionWorld = new THREE.Vector3();
  13799. this.positionScreen = new THREE.Vector4();
  13800. this.visible = true;
  13801. };
  13802. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  13803. this.positionWorld.copy( vertex.positionWorld );
  13804. this.positionScreen.copy( vertex.positionScreen );
  13805. }
  13806. /**
  13807. * @author mrdoob / http://mrdoob.com/
  13808. */
  13809. THREE.RenderableFace3 = function () {
  13810. this.v1 = new THREE.RenderableVertex();
  13811. this.v2 = new THREE.RenderableVertex();
  13812. this.v3 = new THREE.RenderableVertex();
  13813. this.centroidWorld = new THREE.Vector3();
  13814. this.centroidScreen = new THREE.Vector3();
  13815. this.normalWorld = new THREE.Vector3();
  13816. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13817. this.vertexNormalsLength = 0;
  13818. this.color = null;
  13819. this.material = null;
  13820. this.uvs = [[]];
  13821. this.z = null;
  13822. };
  13823. /**
  13824. * @author mrdoob / http://mrdoob.com/
  13825. */
  13826. THREE.RenderableFace4 = function () {
  13827. this.v1 = new THREE.RenderableVertex();
  13828. this.v2 = new THREE.RenderableVertex();
  13829. this.v3 = new THREE.RenderableVertex();
  13830. this.v4 = new THREE.RenderableVertex();
  13831. this.centroidWorld = new THREE.Vector3();
  13832. this.centroidScreen = new THREE.Vector3();
  13833. this.normalWorld = new THREE.Vector3();
  13834. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13835. this.vertexNormalsLength = 0;
  13836. this.color = null;
  13837. this.material = null;
  13838. this.uvs = [[]];
  13839. this.z = null;
  13840. };
  13841. /**
  13842. * @author mrdoob / http://mrdoob.com/
  13843. */
  13844. THREE.RenderableObject = function () {
  13845. this.object = null;
  13846. this.z = null;
  13847. };
  13848. /**
  13849. * @author mrdoob / http://mrdoob.com/
  13850. */
  13851. THREE.RenderableParticle = function () {
  13852. this.object = null;
  13853. this.x = null;
  13854. this.y = null;
  13855. this.z = null;
  13856. this.rotation = null;
  13857. this.scale = new THREE.Vector2();
  13858. this.material = null;
  13859. };
  13860. /**
  13861. * @author mrdoob / http://mrdoob.com/
  13862. */
  13863. THREE.RenderableLine = function () {
  13864. this.z = null;
  13865. this.v1 = new THREE.RenderableVertex();
  13866. this.v2 = new THREE.RenderableVertex();
  13867. this.material = null;
  13868. };
  13869. /**
  13870. * @author alteredq / http://alteredqualia.com/
  13871. */
  13872. THREE.ColorUtils = {
  13873. adjustHSV : function ( color, h, s, v ) {
  13874. var hsv = THREE.ColorUtils.__hsv;
  13875. color.getHSV( hsv );
  13876. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  13877. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  13878. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  13879. color.setHSV( hsv.h, hsv.s, hsv.v );
  13880. }
  13881. };
  13882. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  13883. * @author mrdoob / http://mrdoob.com/
  13884. * @author alteredq / http://alteredqualia.com/
  13885. */
  13886. THREE.GeometryUtils = {
  13887. // Merge two geometries or geometry and geometry from object (using object's transform)
  13888. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  13889. var matrix, matrixRotation,
  13890. vertexOffset = geometry1.vertices.length,
  13891. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  13892. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  13893. vertices1 = geometry1.vertices,
  13894. vertices2 = geometry2.vertices,
  13895. faces1 = geometry1.faces,
  13896. faces2 = geometry2.faces,
  13897. uvs1 = geometry1.faceVertexUvs[ 0 ],
  13898. uvs2 = geometry2.faceVertexUvs[ 0 ];
  13899. if ( object2 instanceof THREE.Mesh ) {
  13900. object2.matrixAutoUpdate && object2.updateMatrix();
  13901. matrix = object2.matrix;
  13902. matrixRotation = new THREE.Matrix4();
  13903. matrixRotation.extractRotation( matrix, object2.scale );
  13904. }
  13905. // vertices
  13906. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13907. var vertex = vertices2[ i ];
  13908. var vertexCopy = vertex.clone();
  13909. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13910. vertices1.push( vertexCopy );
  13911. }
  13912. // faces
  13913. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13914. var face = faces2[ i ], faceCopy, normal, color,
  13915. faceVertexNormals = face.vertexNormals,
  13916. faceVertexColors = face.vertexColors;
  13917. if ( face instanceof THREE.Face3 ) {
  13918. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13919. } else if ( face instanceof THREE.Face4 ) {
  13920. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13921. }
  13922. faceCopy.normal.copy( face.normal );
  13923. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13924. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13925. normal = faceVertexNormals[ j ].clone();
  13926. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13927. faceCopy.vertexNormals.push( normal );
  13928. }
  13929. faceCopy.color.copy( face.color );
  13930. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13931. color = faceVertexColors[ j ];
  13932. faceCopy.vertexColors.push( color.clone() );
  13933. }
  13934. faceCopy.materialIndex = face.materialIndex;
  13935. faceCopy.centroid.copy( face.centroid );
  13936. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13937. faces1.push( faceCopy );
  13938. }
  13939. // uvs
  13940. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13941. var uv = uvs2[ i ], uvCopy = [];
  13942. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13943. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13944. }
  13945. uvs1.push( uvCopy );
  13946. }
  13947. },
  13948. removeMaterials: function ( geometry, materialIndexArray ) {
  13949. var materialIndexMap = {};
  13950. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  13951. materialIndexMap[ materialIndexArray[i] ] = true;
  13952. }
  13953. var face, newFaces = [];
  13954. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13955. face = geometry.faces[ i ];
  13956. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  13957. }
  13958. geometry.faces = newFaces;
  13959. },
  13960. // Get random point in triangle (via barycentric coordinates)
  13961. // (uniform distribution)
  13962. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13963. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13964. var a, b, c,
  13965. point = new THREE.Vector3(),
  13966. tmp = THREE.GeometryUtils.__v1;
  13967. a = THREE.GeometryUtils.random();
  13968. b = THREE.GeometryUtils.random();
  13969. if ( ( a + b ) > 1 ) {
  13970. a = 1 - a;
  13971. b = 1 - b;
  13972. }
  13973. c = 1 - a - b;
  13974. point.copy( vectorA );
  13975. point.multiplyScalar( a );
  13976. tmp.copy( vectorB );
  13977. tmp.multiplyScalar( b );
  13978. point.addSelf( tmp );
  13979. tmp.copy( vectorC );
  13980. tmp.multiplyScalar( c );
  13981. point.addSelf( tmp );
  13982. return point;
  13983. },
  13984. // Get random point in face (triangle / quad)
  13985. // (uniform distribution)
  13986. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13987. var vA, vB, vC, vD;
  13988. if ( face instanceof THREE.Face3 ) {
  13989. vA = geometry.vertices[ face.a ];
  13990. vB = geometry.vertices[ face.b ];
  13991. vC = geometry.vertices[ face.c ];
  13992. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13993. } else if ( face instanceof THREE.Face4 ) {
  13994. vA = geometry.vertices[ face.a ];
  13995. vB = geometry.vertices[ face.b ];
  13996. vC = geometry.vertices[ face.c ];
  13997. vD = geometry.vertices[ face.d ];
  13998. var area1, area2;
  13999. if ( useCachedAreas ) {
  14000. if ( face._area1 && face._area2 ) {
  14001. area1 = face._area1;
  14002. area2 = face._area2;
  14003. } else {
  14004. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14005. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14006. face._area1 = area1;
  14007. face._area2 = area2;
  14008. }
  14009. } else {
  14010. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  14011. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14012. }
  14013. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  14014. if ( r < area1 ) {
  14015. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  14016. } else {
  14017. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  14018. }
  14019. }
  14020. },
  14021. // Get uniformly distributed random points in mesh
  14022. // - create array with cumulative sums of face areas
  14023. // - pick random number from 0 to total area
  14024. // - find corresponding place in area array by binary search
  14025. // - get random point in face
  14026. randomPointsInGeometry: function ( geometry, n ) {
  14027. var face, i,
  14028. faces = geometry.faces,
  14029. vertices = geometry.vertices,
  14030. il = faces.length,
  14031. totalArea = 0,
  14032. cumulativeAreas = [],
  14033. vA, vB, vC, vD;
  14034. // precompute face areas
  14035. for ( i = 0; i < il; i ++ ) {
  14036. face = faces[ i ];
  14037. if ( face instanceof THREE.Face3 ) {
  14038. vA = vertices[ face.a ];
  14039. vB = vertices[ face.b ];
  14040. vC = vertices[ face.c ];
  14041. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  14042. } else if ( face instanceof THREE.Face4 ) {
  14043. vA = vertices[ face.a ];
  14044. vB = vertices[ face.b ];
  14045. vC = vertices[ face.c ];
  14046. vD = vertices[ face.d ];
  14047. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14048. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14049. face._area = face._area1 + face._area2;
  14050. }
  14051. totalArea += face._area;
  14052. cumulativeAreas[ i ] = totalArea;
  14053. }
  14054. // binary search cumulative areas array
  14055. function binarySearchIndices( value ) {
  14056. function binarySearch( start, end ) {
  14057. // return closest larger index
  14058. // if exact number is not found
  14059. if ( end < start )
  14060. return start;
  14061. var mid = start + Math.floor( ( end - start ) / 2 );
  14062. if ( cumulativeAreas[ mid ] > value ) {
  14063. return binarySearch( start, mid - 1 );
  14064. } else if ( cumulativeAreas[ mid ] < value ) {
  14065. return binarySearch( mid + 1, end );
  14066. } else {
  14067. return mid;
  14068. }
  14069. }
  14070. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  14071. return result;
  14072. }
  14073. // pick random face weighted by face area
  14074. var r, index,
  14075. result = [];
  14076. var stats = {};
  14077. for ( i = 0; i < n; i ++ ) {
  14078. r = THREE.GeometryUtils.random() * totalArea;
  14079. index = binarySearchIndices( r );
  14080. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  14081. if ( ! stats[ index ] ) {
  14082. stats[ index ] = 1;
  14083. } else {
  14084. stats[ index ] += 1;
  14085. }
  14086. }
  14087. return result;
  14088. },
  14089. // Get triangle area (half of parallelogram)
  14090. // http://mathworld.wolfram.com/TriangleArea.html
  14091. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14092. var tmp1 = THREE.GeometryUtils.__v1,
  14093. tmp2 = THREE.GeometryUtils.__v2;
  14094. tmp1.sub( vectorB, vectorA );
  14095. tmp2.sub( vectorC, vectorA );
  14096. tmp1.crossSelf( tmp2 );
  14097. return 0.5 * tmp1.length();
  14098. },
  14099. // Center geometry so that 0,0,0 is in center of bounding box
  14100. center: function ( geometry ) {
  14101. geometry.computeBoundingBox();
  14102. var bb = geometry.boundingBox;
  14103. var offset = new THREE.Vector3();
  14104. offset.add( bb.min, bb.max );
  14105. offset.multiplyScalar( -0.5 );
  14106. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  14107. geometry.computeBoundingBox();
  14108. return offset;
  14109. },
  14110. // Normalize UVs to be from <0,1>
  14111. // (for now just the first set of UVs)
  14112. normalizeUVs: function ( geometry ) {
  14113. var uvSet = geometry.faceVertexUvs[ 0 ];
  14114. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14115. var uvs = uvSet[ i ];
  14116. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14117. // texture repeat
  14118. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  14119. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  14120. }
  14121. }
  14122. },
  14123. triangulateQuads: function ( geometry ) {
  14124. var i, il, j, jl;
  14125. var faces = [];
  14126. var faceUvs = [];
  14127. var faceVertexUvs = [];
  14128. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14129. faceUvs[ i ] = [];
  14130. }
  14131. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14132. faceVertexUvs[ i ] = [];
  14133. }
  14134. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14135. var face = geometry.faces[ i ];
  14136. if ( face instanceof THREE.Face4 ) {
  14137. var a = face.a;
  14138. var b = face.b;
  14139. var c = face.c;
  14140. var d = face.d;
  14141. var triA = new THREE.Face3();
  14142. var triB = new THREE.Face3();
  14143. triA.color.copy( face.color );
  14144. triB.color.copy( face.color );
  14145. triA.materialIndex = face.materialIndex;
  14146. triB.materialIndex = face.materialIndex;
  14147. triA.a = a;
  14148. triA.b = b;
  14149. triA.c = d;
  14150. triB.a = b;
  14151. triB.b = c;
  14152. triB.c = d;
  14153. if ( face.vertexColors.length === 4 ) {
  14154. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14155. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14156. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14157. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14158. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14159. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14160. }
  14161. faces.push( triA, triB );
  14162. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14163. if ( geometry.faceVertexUvs[ j ].length ) {
  14164. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14165. var uvA = uvs[ 0 ];
  14166. var uvB = uvs[ 1 ];
  14167. var uvC = uvs[ 2 ];
  14168. var uvD = uvs[ 3 ];
  14169. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14170. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14171. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14172. }
  14173. }
  14174. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14175. if ( geometry.faceUvs[ j ].length ) {
  14176. var faceUv = geometry.faceUvs[ j ][ i ];
  14177. faceUvs[ j ].push( faceUv, faceUv );
  14178. }
  14179. }
  14180. } else {
  14181. faces.push( face );
  14182. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14183. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14184. }
  14185. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14186. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14187. }
  14188. }
  14189. }
  14190. geometry.faces = faces;
  14191. geometry.faceUvs = faceUvs;
  14192. geometry.faceVertexUvs = faceVertexUvs;
  14193. geometry.computeCentroids();
  14194. geometry.computeFaceNormals();
  14195. geometry.computeVertexNormals();
  14196. if ( geometry.hasTangents ) geometry.computeTangents();
  14197. },
  14198. // Make all faces use unique vertices
  14199. // so that each face can be separated from others
  14200. explode: function( geometry ) {
  14201. var vertices = [];
  14202. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14203. var n = vertices.length;
  14204. var face = geometry.faces[ i ];
  14205. if ( face instanceof THREE.Face4 ) {
  14206. var a = face.a;
  14207. var b = face.b;
  14208. var c = face.c;
  14209. var d = face.d;
  14210. var va = geometry.vertices[ a ];
  14211. var vb = geometry.vertices[ b ];
  14212. var vc = geometry.vertices[ c ];
  14213. var vd = geometry.vertices[ d ];
  14214. vertices.push( va.clone() );
  14215. vertices.push( vb.clone() );
  14216. vertices.push( vc.clone() );
  14217. vertices.push( vd.clone() );
  14218. face.a = n;
  14219. face.b = n + 1;
  14220. face.c = n + 2;
  14221. face.d = n + 3;
  14222. } else {
  14223. var a = face.a;
  14224. var b = face.b;
  14225. var c = face.c;
  14226. var va = geometry.vertices[ a ];
  14227. var vb = geometry.vertices[ b ];
  14228. var vc = geometry.vertices[ c ];
  14229. vertices.push( va.clone() );
  14230. vertices.push( vb.clone() );
  14231. vertices.push( vc.clone() );
  14232. face.a = n;
  14233. face.b = n + 1;
  14234. face.c = n + 2;
  14235. }
  14236. }
  14237. geometry.vertices = vertices;
  14238. delete geometry.__tmpVertices;
  14239. },
  14240. // Break faces with edges longer than maxEdgeLength
  14241. // - not recursive
  14242. tessellate: function ( geometry, maxEdgeLength ) {
  14243. var i, il, face,
  14244. a, b, c, d,
  14245. va, vb, vc, vd,
  14246. dab, dbc, dac, dcd, dad,
  14247. m, m1, m2,
  14248. vm, vm1, vm2,
  14249. vnm, vnm1, vnm2,
  14250. vcm, vcm1, vcm2,
  14251. triA, triB,
  14252. quadA, quadB,
  14253. edge;
  14254. var faces = [];
  14255. var faceVertexUvs = [];
  14256. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14257. faceVertexUvs[ i ] = [];
  14258. }
  14259. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14260. face = geometry.faces[ i ];
  14261. if ( face instanceof THREE.Face3 ) {
  14262. a = face.a;
  14263. b = face.b;
  14264. c = face.c;
  14265. va = geometry.vertices[ a ];
  14266. vb = geometry.vertices[ b ];
  14267. vc = geometry.vertices[ c ];
  14268. dab = va.distanceTo( vb );
  14269. dbc = vb.distanceTo( vc );
  14270. dac = va.distanceTo( vc );
  14271. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  14272. m = geometry.vertices.length;
  14273. triA = face.clone();
  14274. triB = face.clone();
  14275. if ( dab >= dbc && dab >= dac ) {
  14276. vm = va.clone();
  14277. vm.lerpSelf( vb, 0.5 );
  14278. triA.a = a;
  14279. triA.b = m;
  14280. triA.c = c;
  14281. triB.a = m;
  14282. triB.b = b;
  14283. triB.c = c;
  14284. if ( face.vertexNormals.length === 3 ) {
  14285. vnm = face.vertexNormals[ 0 ].clone();
  14286. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14287. triA.vertexNormals[ 1 ].copy( vnm );
  14288. triB.vertexNormals[ 0 ].copy( vnm );
  14289. }
  14290. if ( face.vertexColors.length === 3 ) {
  14291. vcm = face.vertexColors[ 0 ].clone();
  14292. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14293. triA.vertexColors[ 1 ].copy( vcm );
  14294. triB.vertexColors[ 0 ].copy( vcm );
  14295. }
  14296. edge = 0;
  14297. } else if ( dbc >= dab && dbc >= dac ) {
  14298. vm = vb.clone();
  14299. vm.lerpSelf( vc, 0.5 );
  14300. triA.a = a;
  14301. triA.b = b;
  14302. triA.c = m;
  14303. triB.a = m;
  14304. triB.b = c;
  14305. triB.c = a;
  14306. if ( face.vertexNormals.length === 3 ) {
  14307. vnm = face.vertexNormals[ 1 ].clone();
  14308. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14309. triA.vertexNormals[ 2 ].copy( vnm );
  14310. triB.vertexNormals[ 0 ].copy( vnm );
  14311. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  14312. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  14313. }
  14314. if ( face.vertexColors.length === 3 ) {
  14315. vcm = face.vertexColors[ 1 ].clone();
  14316. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14317. triA.vertexColors[ 2 ].copy( vcm );
  14318. triB.vertexColors[ 0 ].copy( vcm );
  14319. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  14320. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  14321. }
  14322. edge = 1;
  14323. } else {
  14324. vm = va.clone();
  14325. vm.lerpSelf( vc, 0.5 );
  14326. triA.a = a;
  14327. triA.b = b;
  14328. triA.c = m;
  14329. triB.a = m;
  14330. triB.b = b;
  14331. triB.c = c;
  14332. if ( face.vertexNormals.length === 3 ) {
  14333. vnm = face.vertexNormals[ 0 ].clone();
  14334. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14335. triA.vertexNormals[ 2 ].copy( vnm );
  14336. triB.vertexNormals[ 0 ].copy( vnm );
  14337. }
  14338. if ( face.vertexColors.length === 3 ) {
  14339. vcm = face.vertexColors[ 0 ].clone();
  14340. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14341. triA.vertexColors[ 2 ].copy( vcm );
  14342. triB.vertexColors[ 0 ].copy( vcm );
  14343. }
  14344. edge = 2;
  14345. }
  14346. faces.push( triA, triB );
  14347. geometry.vertices.push( vm );
  14348. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  14349. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14350. if ( geometry.faceVertexUvs[ j ].length ) {
  14351. uvs = geometry.faceVertexUvs[ j ][ i ];
  14352. uvA = uvs[ 0 ];
  14353. uvB = uvs[ 1 ];
  14354. uvC = uvs[ 2 ];
  14355. // AB
  14356. if ( edge === 0 ) {
  14357. uvM = uvA.clone();
  14358. uvM.lerpSelf( uvB, 0.5 );
  14359. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  14360. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14361. // BC
  14362. } else if ( edge === 1 ) {
  14363. uvM = uvB.clone();
  14364. uvM.lerpSelf( uvC, 0.5 );
  14365. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14366. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  14367. // AC
  14368. } else {
  14369. uvM = uvA.clone();
  14370. uvM.lerpSelf( uvC, 0.5 );
  14371. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14372. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14373. }
  14374. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14375. }
  14376. }
  14377. } else {
  14378. faces.push( face );
  14379. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14380. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14381. }
  14382. }
  14383. } else {
  14384. a = face.a;
  14385. b = face.b;
  14386. c = face.c;
  14387. d = face.d;
  14388. va = geometry.vertices[ a ];
  14389. vb = geometry.vertices[ b ];
  14390. vc = geometry.vertices[ c ];
  14391. vd = geometry.vertices[ d ];
  14392. dab = va.distanceTo( vb );
  14393. dbc = vb.distanceTo( vc );
  14394. dcd = vc.distanceTo( vd );
  14395. dad = va.distanceTo( vd );
  14396. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  14397. m1 = geometry.vertices.length;
  14398. m2 = geometry.vertices.length + 1;
  14399. quadA = face.clone();
  14400. quadB = face.clone();
  14401. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  14402. vm1 = va.clone();
  14403. vm1.lerpSelf( vb, 0.5 );
  14404. vm2 = vc.clone();
  14405. vm2.lerpSelf( vd, 0.5 );
  14406. quadA.a = a;
  14407. quadA.b = m1;
  14408. quadA.c = m2;
  14409. quadA.d = d;
  14410. quadB.a = m1;
  14411. quadB.b = b;
  14412. quadB.c = c;
  14413. quadB.d = m2;
  14414. if ( face.vertexNormals.length === 4 ) {
  14415. vnm1 = face.vertexNormals[ 0 ].clone();
  14416. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14417. vnm2 = face.vertexNormals[ 2 ].clone();
  14418. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  14419. quadA.vertexNormals[ 1 ].copy( vnm1 );
  14420. quadA.vertexNormals[ 2 ].copy( vnm2 );
  14421. quadB.vertexNormals[ 0 ].copy( vnm1 );
  14422. quadB.vertexNormals[ 3 ].copy( vnm2 );
  14423. }
  14424. if ( face.vertexColors.length === 4 ) {
  14425. vcm1 = face.vertexColors[ 0 ].clone();
  14426. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14427. vcm2 = face.vertexColors[ 2 ].clone();
  14428. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  14429. quadA.vertexColors[ 1 ].copy( vcm1 );
  14430. quadA.vertexColors[ 2 ].copy( vcm2 );
  14431. quadB.vertexColors[ 0 ].copy( vcm1 );
  14432. quadB.vertexColors[ 3 ].copy( vcm2 );
  14433. }
  14434. edge = 0;
  14435. } else {
  14436. vm1 = vb.clone();
  14437. vm1.lerpSelf( vc, 0.5 );
  14438. vm2 = vd.clone();
  14439. vm2.lerpSelf( va, 0.5 );
  14440. quadA.a = a;
  14441. quadA.b = b;
  14442. quadA.c = m1;
  14443. quadA.d = m2;
  14444. quadB.a = m2;
  14445. quadB.b = m1;
  14446. quadB.c = c;
  14447. quadB.d = d;
  14448. if ( face.vertexNormals.length === 4 ) {
  14449. vnm1 = face.vertexNormals[ 1 ].clone();
  14450. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14451. vnm2 = face.vertexNormals[ 3 ].clone();
  14452. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  14453. quadA.vertexNormals[ 2 ].copy( vnm1 );
  14454. quadA.vertexNormals[ 3 ].copy( vnm2 );
  14455. quadB.vertexNormals[ 0 ].copy( vnm2 );
  14456. quadB.vertexNormals[ 1 ].copy( vnm1 );
  14457. }
  14458. if ( face.vertexColors.length === 4 ) {
  14459. vcm1 = face.vertexColors[ 1 ].clone();
  14460. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14461. vcm2 = face.vertexColors[ 3 ].clone();
  14462. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  14463. quadA.vertexColors[ 2 ].copy( vcm1 );
  14464. quadA.vertexColors[ 3 ].copy( vcm2 );
  14465. quadB.vertexColors[ 0 ].copy( vcm2 );
  14466. quadB.vertexColors[ 1 ].copy( vcm1 );
  14467. }
  14468. edge = 1;
  14469. }
  14470. faces.push( quadA, quadB );
  14471. geometry.vertices.push( vm1, vm2 );
  14472. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  14473. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14474. if ( geometry.faceVertexUvs[ j ].length ) {
  14475. uvs = geometry.faceVertexUvs[ j ][ i ];
  14476. uvA = uvs[ 0 ];
  14477. uvB = uvs[ 1 ];
  14478. uvC = uvs[ 2 ];
  14479. uvD = uvs[ 3 ];
  14480. // AB + CD
  14481. if ( edge === 0 ) {
  14482. uvM1 = uvA.clone();
  14483. uvM1.lerpSelf( uvB, 0.5 );
  14484. uvM2 = uvC.clone();
  14485. uvM2.lerpSelf( uvD, 0.5 );
  14486. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  14487. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  14488. // BC + AD
  14489. } else {
  14490. uvM1 = uvB.clone();
  14491. uvM1.lerpSelf( uvC, 0.5 );
  14492. uvM2 = uvD.clone();
  14493. uvM2.lerpSelf( uvA, 0.5 );
  14494. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  14495. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  14496. }
  14497. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  14498. }
  14499. }
  14500. } else {
  14501. faces.push( face );
  14502. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14503. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14504. }
  14505. }
  14506. }
  14507. }
  14508. geometry.faces = faces;
  14509. geometry.faceVertexUvs = faceVertexUvs;
  14510. }
  14511. };
  14512. THREE.GeometryUtils.random = THREE.Math.random16;
  14513. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14514. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  14515. /**
  14516. * @author alteredq / http://alteredqualia.com/
  14517. * @author mrdoob / http://mrdoob.com/
  14518. */
  14519. THREE.ImageUtils = {
  14520. crossOrigin: 'anonymous',
  14521. loadTexture: function ( url, mapping, onLoad, onError ) {
  14522. var image = new Image();
  14523. var texture = new THREE.Texture( image, mapping );
  14524. var loader = new THREE.ImageLoader();
  14525. loader.addEventListener( 'load', function ( event ) {
  14526. texture.image = event.content;
  14527. texture.needsUpdate = true;
  14528. if ( onLoad ) onLoad( texture );
  14529. } );
  14530. loader.addEventListener( 'error', function ( event ) {
  14531. if ( onError ) onError( event.message );
  14532. } );
  14533. loader.crossOrigin = this.crossOrigin;
  14534. loader.load( url, image );
  14535. texture.sourceFile = url;
  14536. return texture;
  14537. },
  14538. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14539. var texture = new THREE.CompressedTexture();
  14540. texture.mapping = mapping;
  14541. var request = new XMLHttpRequest();
  14542. request.onload = function () {
  14543. var buffer = request.response;
  14544. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14545. texture.format = dds.format;
  14546. texture.mipmaps = dds.mipmaps;
  14547. texture.image.width = dds.width;
  14548. texture.image.height = dds.height;
  14549. // gl.generateMipmap fails for compressed textures
  14550. // mipmaps must be embedded in the DDS file
  14551. // or texture filters must not use mipmapping
  14552. texture.generateMipmaps = false;
  14553. texture.needsUpdate = true;
  14554. if ( onLoad ) onLoad( texture );
  14555. }
  14556. request.onerror = onError;
  14557. request.open( 'GET', url, true );
  14558. request.responseType = "arraybuffer";
  14559. request.send( null );
  14560. return texture;
  14561. },
  14562. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14563. var images = [];
  14564. images.loadCount = 0;
  14565. var texture = new THREE.Texture();
  14566. texture.image = images;
  14567. if ( mapping !== undefined ) texture.mapping = mapping;
  14568. // no flipping needed for cube textures
  14569. texture.flipY = false;
  14570. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14571. var cubeImage = new Image();
  14572. images[ i ] = cubeImage;
  14573. cubeImage.onload = function () {
  14574. images.loadCount += 1;
  14575. if ( images.loadCount === 6 ) {
  14576. texture.needsUpdate = true;
  14577. if ( onLoad ) onLoad( texture );
  14578. }
  14579. };
  14580. cubeImage.onerror = onError;
  14581. cubeImage.crossOrigin = this.crossOrigin;
  14582. cubeImage.src = array[ i ];
  14583. }
  14584. return texture;
  14585. },
  14586. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14587. var images = [];
  14588. images.loadCount = 0;
  14589. var texture = new THREE.CompressedTexture();
  14590. texture.image = images;
  14591. if ( mapping !== undefined ) texture.mapping = mapping;
  14592. // no flipping for cube textures
  14593. // (also flipping doesn't work for compressed textures )
  14594. texture.flipY = false;
  14595. // can't generate mipmaps for compressed textures
  14596. // mips must be embedded in DDS files
  14597. texture.generateMipmaps = false;
  14598. var generateCubeFaceCallback = function ( rq, img ) {
  14599. return function () {
  14600. var buffer = rq.response;
  14601. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14602. img.format = dds.format;
  14603. img.mipmaps = dds.mipmaps;
  14604. img.width = dds.width;
  14605. img.height = dds.height;
  14606. images.loadCount += 1;
  14607. if ( images.loadCount === 6 ) {
  14608. texture.format = dds.format;
  14609. texture.needsUpdate = true;
  14610. if ( onLoad ) onLoad( texture );
  14611. }
  14612. }
  14613. }
  14614. // compressed cubemap textures as 6 separate DDS files
  14615. if ( array instanceof Array ) {
  14616. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14617. var cubeImage = {};
  14618. images[ i ] = cubeImage;
  14619. var request = new XMLHttpRequest();
  14620. request.onload = generateCubeFaceCallback( request, cubeImage );
  14621. request.onerror = onError;
  14622. var url = array[ i ];
  14623. request.open( 'GET', url, true );
  14624. request.responseType = "arraybuffer";
  14625. request.send( null );
  14626. }
  14627. // compressed cubemap texture stored in a single DDS file
  14628. } else {
  14629. var url = array;
  14630. var request = new XMLHttpRequest();
  14631. request.onload = function( ) {
  14632. var buffer = request.response;
  14633. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14634. if ( dds.isCubemap ) {
  14635. var faces = dds.mipmaps.length / dds.mipmapCount;
  14636. for ( var f = 0; f < faces; f ++ ) {
  14637. images[ f ] = { mipmaps : [] };
  14638. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14639. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  14640. images[ f ].format = dds.format;
  14641. images[ f ].width = dds.width;
  14642. images[ f ].height = dds.height;
  14643. }
  14644. }
  14645. texture.format = dds.format;
  14646. texture.needsUpdate = true;
  14647. if ( onLoad ) onLoad( texture );
  14648. }
  14649. }
  14650. request.onerror = onError;
  14651. request.open( 'GET', url, true );
  14652. request.responseType = "arraybuffer";
  14653. request.send( null );
  14654. }
  14655. return texture;
  14656. },
  14657. parseDDS: function ( buffer, loadMipmaps ) {
  14658. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  14659. // Adapted from @toji's DDS utils
  14660. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  14661. // All values and structures referenced from:
  14662. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  14663. var DDS_MAGIC = 0x20534444;
  14664. var DDSD_CAPS = 0x1,
  14665. DDSD_HEIGHT = 0x2,
  14666. DDSD_WIDTH = 0x4,
  14667. DDSD_PITCH = 0x8,
  14668. DDSD_PIXELFORMAT = 0x1000,
  14669. DDSD_MIPMAPCOUNT = 0x20000,
  14670. DDSD_LINEARSIZE = 0x80000,
  14671. DDSD_DEPTH = 0x800000;
  14672. var DDSCAPS_COMPLEX = 0x8,
  14673. DDSCAPS_MIPMAP = 0x400000,
  14674. DDSCAPS_TEXTURE = 0x1000;
  14675. var DDSCAPS2_CUBEMAP = 0x200,
  14676. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  14677. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  14678. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  14679. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  14680. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  14681. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  14682. DDSCAPS2_VOLUME = 0x200000;
  14683. var DDPF_ALPHAPIXELS = 0x1,
  14684. DDPF_ALPHA = 0x2,
  14685. DDPF_FOURCC = 0x4,
  14686. DDPF_RGB = 0x40,
  14687. DDPF_YUV = 0x200,
  14688. DDPF_LUMINANCE = 0x20000;
  14689. function fourCCToInt32( value ) {
  14690. return value.charCodeAt(0) +
  14691. (value.charCodeAt(1) << 8) +
  14692. (value.charCodeAt(2) << 16) +
  14693. (value.charCodeAt(3) << 24);
  14694. }
  14695. function int32ToFourCC( value ) {
  14696. return String.fromCharCode(
  14697. value & 0xff,
  14698. (value >> 8) & 0xff,
  14699. (value >> 16) & 0xff,
  14700. (value >> 24) & 0xff
  14701. );
  14702. }
  14703. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  14704. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  14705. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  14706. var headerLengthInt = 31; // The header length in 32 bit ints
  14707. // Offsets into the header array
  14708. var off_magic = 0;
  14709. var off_size = 1;
  14710. var off_flags = 2;
  14711. var off_height = 3;
  14712. var off_width = 4;
  14713. var off_mipmapCount = 7;
  14714. var off_pfFlags = 20;
  14715. var off_pfFourCC = 21;
  14716. var off_caps = 27;
  14717. var off_caps2 = 28;
  14718. var off_caps3 = 29;
  14719. var off_caps4 = 30;
  14720. // Parse header
  14721. var header = new Int32Array( buffer, 0, headerLengthInt );
  14722. if ( header[ off_magic ] !== DDS_MAGIC ) {
  14723. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  14724. return dds;
  14725. }
  14726. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  14727. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  14728. return dds;
  14729. }
  14730. var blockBytes;
  14731. var fourCC = header[ off_pfFourCC ];
  14732. switch ( fourCC ) {
  14733. case FOURCC_DXT1:
  14734. blockBytes = 8;
  14735. dds.format = THREE.RGB_S3TC_DXT1_Format;
  14736. break;
  14737. case FOURCC_DXT3:
  14738. blockBytes = 16;
  14739. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  14740. break;
  14741. case FOURCC_DXT5:
  14742. blockBytes = 16;
  14743. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  14744. break;
  14745. default:
  14746. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  14747. return dds;
  14748. }
  14749. dds.mipmapCount = 1;
  14750. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  14751. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  14752. }
  14753. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  14754. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  14755. dds.width = header[ off_width ];
  14756. dds.height = header[ off_height ];
  14757. var dataOffset = header[ off_size ] + 4;
  14758. // Extract mipmaps buffers
  14759. var width = dds.width;
  14760. var height = dds.height;
  14761. var faces = dds.isCubemap ? 6 : 1;
  14762. for ( var face = 0; face < faces; face ++ ) {
  14763. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14764. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  14765. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  14766. var mipmap = { "data": byteArray, "width": width, "height": height };
  14767. dds.mipmaps.push( mipmap );
  14768. dataOffset += dataLength;
  14769. width = Math.max( width * 0.5, 1 );
  14770. height = Math.max( height * 0.5, 1 );
  14771. }
  14772. width = dds.width;
  14773. height = dds.height;
  14774. }
  14775. return dds;
  14776. },
  14777. getNormalMap: function ( image, depth ) {
  14778. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  14779. var cross = function ( a, b ) {
  14780. 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 ] ];
  14781. }
  14782. var subtract = function ( a, b ) {
  14783. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  14784. }
  14785. var normalize = function ( a ) {
  14786. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  14787. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  14788. }
  14789. depth = depth | 1;
  14790. var width = image.width;
  14791. var height = image.height;
  14792. var canvas = document.createElement( 'canvas' );
  14793. canvas.width = width;
  14794. canvas.height = height;
  14795. var context = canvas.getContext( '2d' );
  14796. context.drawImage( image, 0, 0 );
  14797. var data = context.getImageData( 0, 0, width, height ).data;
  14798. var imageData = context.createImageData( width, height );
  14799. var output = imageData.data;
  14800. for ( var x = 0; x < width; x ++ ) {
  14801. for ( var y = 0; y < height; y ++ ) {
  14802. var ly = y - 1 < 0 ? 0 : y - 1;
  14803. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  14804. var lx = x - 1 < 0 ? 0 : x - 1;
  14805. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  14806. var points = [];
  14807. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  14808. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  14809. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  14810. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  14811. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  14812. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  14813. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  14814. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  14815. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  14816. var normals = [];
  14817. var num_points = points.length;
  14818. for ( var i = 0; i < num_points; i ++ ) {
  14819. var v1 = points[ i ];
  14820. var v2 = points[ ( i + 1 ) % num_points ];
  14821. v1 = subtract( v1, origin );
  14822. v2 = subtract( v2, origin );
  14823. normals.push( normalize( cross( v1, v2 ) ) );
  14824. }
  14825. var normal = [ 0, 0, 0 ];
  14826. for ( var i = 0; i < normals.length; i ++ ) {
  14827. normal[ 0 ] += normals[ i ][ 0 ];
  14828. normal[ 1 ] += normals[ i ][ 1 ];
  14829. normal[ 2 ] += normals[ i ][ 2 ];
  14830. }
  14831. normal[ 0 ] /= normals.length;
  14832. normal[ 1 ] /= normals.length;
  14833. normal[ 2 ] /= normals.length;
  14834. var idx = ( y * width + x ) * 4;
  14835. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14836. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14837. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  14838. output[ idx + 3 ] = 255;
  14839. }
  14840. }
  14841. context.putImageData( imageData, 0, 0 );
  14842. return canvas;
  14843. },
  14844. generateDataTexture: function ( width, height, color ) {
  14845. var size = width * height;
  14846. var data = new Uint8Array( 3 * size );
  14847. var r = Math.floor( color.r * 255 );
  14848. var g = Math.floor( color.g * 255 );
  14849. var b = Math.floor( color.b * 255 );
  14850. for ( var i = 0; i < size; i ++ ) {
  14851. data[ i * 3 ] = r;
  14852. data[ i * 3 + 1 ] = g;
  14853. data[ i * 3 + 2 ] = b;
  14854. }
  14855. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  14856. texture.needsUpdate = true;
  14857. return texture;
  14858. }
  14859. };
  14860. /**
  14861. * @author alteredq / http://alteredqualia.com/
  14862. */
  14863. THREE.SceneUtils = {
  14864. createMultiMaterialObject: function ( geometry, materials ) {
  14865. var group = new THREE.Object3D();
  14866. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14867. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  14868. }
  14869. return group;
  14870. },
  14871. detach : function ( child, parent, scene ) {
  14872. child.applyMatrix( parent.matrixWorld );
  14873. parent.remove( child );
  14874. scene.add( child );
  14875. },
  14876. attach: function ( child, scene, parent ) {
  14877. var matrixWorldInverse = new THREE.Matrix4();
  14878. matrixWorldInverse.getInverse( parent.matrixWorld );
  14879. child.applyMatrix( matrixWorldInverse );
  14880. scene.remove( child );
  14881. parent.add( child );
  14882. }
  14883. };
  14884. /**
  14885. * @author alteredq / http://alteredqualia.com/
  14886. * @author mrdoob / http://mrdoob.com/
  14887. *
  14888. * ShaderUtils currently contains:
  14889. *
  14890. * fresnel
  14891. * normal
  14892. * cube
  14893. *
  14894. */
  14895. THREE.ShaderUtils = {
  14896. lib: {
  14897. /* -------------------------------------------------------------------------
  14898. // Fresnel shader
  14899. // - based on Nvidia Cg tutorial
  14900. ------------------------------------------------------------------------- */
  14901. 'fresnel': {
  14902. uniforms: {
  14903. "mRefractionRatio": { type: "f", value: 1.02 },
  14904. "mFresnelBias": { type: "f", value: 0.1 },
  14905. "mFresnelPower": { type: "f", value: 2.0 },
  14906. "mFresnelScale": { type: "f", value: 1.0 },
  14907. "tCube": { type: "t", value: null }
  14908. },
  14909. fragmentShader: [
  14910. "uniform samplerCube tCube;",
  14911. "varying vec3 vReflect;",
  14912. "varying vec3 vRefract[3];",
  14913. "varying float vReflectionFactor;",
  14914. "void main() {",
  14915. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14916. "vec4 refractedColor = vec4( 1.0 );",
  14917. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  14918. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  14919. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  14920. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  14921. "}"
  14922. ].join("\n"),
  14923. vertexShader: [
  14924. "uniform float mRefractionRatio;",
  14925. "uniform float mFresnelBias;",
  14926. "uniform float mFresnelScale;",
  14927. "uniform float mFresnelPower;",
  14928. "varying vec3 vReflect;",
  14929. "varying vec3 vRefract[3];",
  14930. "varying float vReflectionFactor;",
  14931. "void main() {",
  14932. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14933. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  14934. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  14935. "vec3 I = worldPosition.xyz - cameraPosition;",
  14936. "vReflect = reflect( I, worldNormal );",
  14937. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  14938. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  14939. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  14940. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  14941. "gl_Position = projectionMatrix * mvPosition;",
  14942. "}"
  14943. ].join("\n")
  14944. },
  14945. /* -------------------------------------------------------------------------
  14946. // Normal map shader
  14947. // - Blinn-Phong
  14948. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  14949. // - point and directional lights (use with "lights: true" material option)
  14950. ------------------------------------------------------------------------- */
  14951. 'normal' : {
  14952. uniforms: THREE.UniformsUtils.merge( [
  14953. THREE.UniformsLib[ "fog" ],
  14954. THREE.UniformsLib[ "lights" ],
  14955. THREE.UniformsLib[ "shadowmap" ],
  14956. {
  14957. "enableAO" : { type: "i", value: 0 },
  14958. "enableDiffuse" : { type: "i", value: 0 },
  14959. "enableSpecular" : { type: "i", value: 0 },
  14960. "enableReflection": { type: "i", value: 0 },
  14961. "enableDisplacement": { type: "i", value: 0 },
  14962. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  14963. "tDiffuse" : { type: "t", value: null },
  14964. "tCube" : { type: "t", value: null },
  14965. "tNormal" : { type: "t", value: null },
  14966. "tSpecular" : { type: "t", value: null },
  14967. "tAO" : { type: "t", value: null },
  14968. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14969. "uDisplacementBias": { type: "f", value: 0.0 },
  14970. "uDisplacementScale": { type: "f", value: 1.0 },
  14971. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14972. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  14973. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14974. "uShininess": { type: "f", value: 30 },
  14975. "uOpacity": { type: "f", value: 1 },
  14976. "useRefract": { type: "i", value: 0 },
  14977. "uRefractionRatio": { type: "f", value: 0.98 },
  14978. "uReflectivity": { type: "f", value: 0.5 },
  14979. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  14980. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14981. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  14982. }
  14983. ] ),
  14984. fragmentShader: [
  14985. "uniform vec3 uAmbientColor;",
  14986. "uniform vec3 uDiffuseColor;",
  14987. "uniform vec3 uSpecularColor;",
  14988. "uniform float uShininess;",
  14989. "uniform float uOpacity;",
  14990. "uniform bool enableDiffuse;",
  14991. "uniform bool enableSpecular;",
  14992. "uniform bool enableAO;",
  14993. "uniform bool enableReflection;",
  14994. "uniform sampler2D tDiffuse;",
  14995. "uniform sampler2D tNormal;",
  14996. "uniform sampler2D tSpecular;",
  14997. "uniform sampler2D tAO;",
  14998. "uniform samplerCube tCube;",
  14999. "uniform vec2 uNormalScale;",
  15000. "uniform bool useRefract;",
  15001. "uniform float uRefractionRatio;",
  15002. "uniform float uReflectivity;",
  15003. "varying vec3 vTangent;",
  15004. "varying vec3 vBinormal;",
  15005. "varying vec3 vNormal;",
  15006. "varying vec2 vUv;",
  15007. "uniform vec3 ambientLightColor;",
  15008. "#if MAX_DIR_LIGHTS > 0",
  15009. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  15010. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  15011. "#endif",
  15012. "#if MAX_HEMI_LIGHTS > 0",
  15013. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  15014. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  15015. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  15016. "#endif",
  15017. "#if MAX_POINT_LIGHTS > 0",
  15018. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  15019. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  15020. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  15021. "#endif",
  15022. "#if MAX_SPOT_LIGHTS > 0",
  15023. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  15024. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  15025. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  15026. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  15027. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  15028. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  15029. "#endif",
  15030. "#ifdef WRAP_AROUND",
  15031. "uniform vec3 wrapRGB;",
  15032. "#endif",
  15033. "varying vec3 vWorldPosition;",
  15034. "varying vec3 vViewPosition;",
  15035. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  15036. THREE.ShaderChunk[ "fog_pars_fragment" ],
  15037. "void main() {",
  15038. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  15039. "vec3 specularTex = vec3( 1.0 );",
  15040. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  15041. "normalTex.xy *= uNormalScale;",
  15042. "normalTex = normalize( normalTex );",
  15043. "if( enableDiffuse ) {",
  15044. "#ifdef GAMMA_INPUT",
  15045. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  15046. "texelColor.xyz *= texelColor.xyz;",
  15047. "gl_FragColor = gl_FragColor * texelColor;",
  15048. "#else",
  15049. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  15050. "#endif",
  15051. "}",
  15052. "if( enableAO ) {",
  15053. "#ifdef GAMMA_INPUT",
  15054. "vec4 aoColor = texture2D( tAO, vUv );",
  15055. "aoColor.xyz *= aoColor.xyz;",
  15056. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  15057. "#else",
  15058. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  15059. "#endif",
  15060. "}",
  15061. "if( enableSpecular )",
  15062. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  15063. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  15064. "vec3 finalNormal = tsb * normalTex;",
  15065. "#ifdef FLIP_SIDED",
  15066. "finalNormal = -finalNormal;",
  15067. "#endif",
  15068. "vec3 normal = normalize( finalNormal );",
  15069. "vec3 viewPosition = normalize( vViewPosition );",
  15070. // point lights
  15071. "#if MAX_POINT_LIGHTS > 0",
  15072. "vec3 pointDiffuse = vec3( 0.0 );",
  15073. "vec3 pointSpecular = vec3( 0.0 );",
  15074. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  15075. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  15076. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  15077. "float pointDistance = 1.0;",
  15078. "if ( pointLightDistance[ i ] > 0.0 )",
  15079. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  15080. "pointVector = normalize( pointVector );",
  15081. // diffuse
  15082. "#ifdef WRAP_AROUND",
  15083. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  15084. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  15085. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  15086. "#else",
  15087. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  15088. "#endif",
  15089. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  15090. // specular
  15091. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  15092. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  15093. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  15094. "#ifdef PHYSICALLY_BASED_SHADING",
  15095. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15096. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15097. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  15098. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  15099. "#else",
  15100. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  15101. "#endif",
  15102. "}",
  15103. "#endif",
  15104. // spot lights
  15105. "#if MAX_SPOT_LIGHTS > 0",
  15106. "vec3 spotDiffuse = vec3( 0.0 );",
  15107. "vec3 spotSpecular = vec3( 0.0 );",
  15108. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  15109. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  15110. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  15111. "float spotDistance = 1.0;",
  15112. "if ( spotLightDistance[ i ] > 0.0 )",
  15113. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  15114. "spotVector = normalize( spotVector );",
  15115. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  15116. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  15117. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  15118. // diffuse
  15119. "#ifdef WRAP_AROUND",
  15120. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15121. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15122. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15123. "#else",
  15124. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15125. "#endif",
  15126. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15127. // specular
  15128. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15129. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15130. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15131. "#ifdef PHYSICALLY_BASED_SHADING",
  15132. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15133. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15134. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15135. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15136. "#else",
  15137. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15138. "#endif",
  15139. "}",
  15140. "}",
  15141. "#endif",
  15142. // directional lights
  15143. "#if MAX_DIR_LIGHTS > 0",
  15144. "vec3 dirDiffuse = vec3( 0.0 );",
  15145. "vec3 dirSpecular = vec3( 0.0 );",
  15146. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15147. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15148. "vec3 dirVector = normalize( lDirection.xyz );",
  15149. // diffuse
  15150. "#ifdef WRAP_AROUND",
  15151. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15152. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15153. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15154. "#else",
  15155. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15156. "#endif",
  15157. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15158. // specular
  15159. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15160. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15161. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15162. "#ifdef PHYSICALLY_BASED_SHADING",
  15163. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15164. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15165. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15166. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15167. "#else",
  15168. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15169. "#endif",
  15170. "}",
  15171. "#endif",
  15172. // hemisphere lights
  15173. "#if MAX_HEMI_LIGHTS > 0",
  15174. "vec3 hemiDiffuse = vec3( 0.0 );",
  15175. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15176. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15177. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15178. "vec3 lVector = normalize( lDirection.xyz );",
  15179. // diffuse
  15180. "float dotProduct = dot( normal, lVector );",
  15181. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  15182. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  15183. "hemiDiffuse += uDiffuseColor * hemiColor;",
  15184. // specular (sky light)
  15185. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  15186. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  15187. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  15188. // specular (ground light)
  15189. "vec3 lVectorGround = -lVector;",
  15190. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  15191. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15192. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15193. "#ifdef PHYSICALLY_BASED_SHADING",
  15194. "float dotProductGround = dot( normal, lVectorGround );",
  15195. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15196. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15197. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15198. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15199. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15200. "#else",
  15201. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15202. "#endif",
  15203. "}",
  15204. "#endif",
  15205. // all lights contribution summation
  15206. "vec3 totalDiffuse = vec3( 0.0 );",
  15207. "vec3 totalSpecular = vec3( 0.0 );",
  15208. "#if MAX_DIR_LIGHTS > 0",
  15209. "totalDiffuse += dirDiffuse;",
  15210. "totalSpecular += dirSpecular;",
  15211. "#endif",
  15212. "#if MAX_HEMI_LIGHTS > 0",
  15213. "totalDiffuse += hemiDiffuse;",
  15214. "totalSpecular += hemiSpecular;",
  15215. "#endif",
  15216. "#if MAX_POINT_LIGHTS > 0",
  15217. "totalDiffuse += pointDiffuse;",
  15218. "totalSpecular += pointSpecular;",
  15219. "#endif",
  15220. "#if MAX_SPOT_LIGHTS > 0",
  15221. "totalDiffuse += spotDiffuse;",
  15222. "totalSpecular += spotSpecular;",
  15223. "#endif",
  15224. "#ifdef METAL",
  15225. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15226. "#else",
  15227. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15228. "#endif",
  15229. "if ( enableReflection ) {",
  15230. "vec3 vReflect;",
  15231. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15232. "if ( useRefract ) {",
  15233. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15234. "} else {",
  15235. "vReflect = reflect( cameraToVertex, normal );",
  15236. "}",
  15237. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15238. "#ifdef GAMMA_INPUT",
  15239. "cubeColor.xyz *= cubeColor.xyz;",
  15240. "#endif",
  15241. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15242. "}",
  15243. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15244. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15245. THREE.ShaderChunk[ "fog_fragment" ],
  15246. "}"
  15247. ].join("\n"),
  15248. vertexShader: [
  15249. "attribute vec4 tangent;",
  15250. "uniform vec2 uOffset;",
  15251. "uniform vec2 uRepeat;",
  15252. "uniform bool enableDisplacement;",
  15253. "#ifdef VERTEX_TEXTURES",
  15254. "uniform sampler2D tDisplacement;",
  15255. "uniform float uDisplacementScale;",
  15256. "uniform float uDisplacementBias;",
  15257. "#endif",
  15258. "varying vec3 vTangent;",
  15259. "varying vec3 vBinormal;",
  15260. "varying vec3 vNormal;",
  15261. "varying vec2 vUv;",
  15262. "varying vec3 vWorldPosition;",
  15263. "varying vec3 vViewPosition;",
  15264. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15265. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15266. "void main() {",
  15267. THREE.ShaderChunk[ "skinbase_vertex" ],
  15268. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15269. // normal, tangent and binormal vectors
  15270. "#ifdef USE_SKINNING",
  15271. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15272. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15273. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15274. "#else",
  15275. "vNormal = normalize( normalMatrix * normal );",
  15276. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15277. "#endif",
  15278. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15279. "vUv = uv * uRepeat + uOffset;",
  15280. // displacement mapping
  15281. "vec3 displacedPosition;",
  15282. "#ifdef VERTEX_TEXTURES",
  15283. "if ( enableDisplacement ) {",
  15284. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15285. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15286. "displacedPosition = position + normalize( normal ) * df;",
  15287. "} else {",
  15288. "#ifdef USE_SKINNING",
  15289. "vec4 skinVertex = vec4( position, 1.0 );",
  15290. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15291. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15292. "displacedPosition = skinned.xyz;",
  15293. "#else",
  15294. "displacedPosition = position;",
  15295. "#endif",
  15296. "}",
  15297. "#else",
  15298. "#ifdef USE_SKINNING",
  15299. "vec4 skinVertex = vec4( position, 1.0 );",
  15300. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15301. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15302. "displacedPosition = skinned.xyz;",
  15303. "#else",
  15304. "displacedPosition = position;",
  15305. "#endif",
  15306. "#endif",
  15307. //
  15308. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15309. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15310. "gl_Position = projectionMatrix * mvPosition;",
  15311. //
  15312. "vWorldPosition = worldPosition.xyz;",
  15313. "vViewPosition = -mvPosition.xyz;",
  15314. // shadows
  15315. "#ifdef USE_SHADOWMAP",
  15316. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15317. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15318. "}",
  15319. "#endif",
  15320. "}"
  15321. ].join("\n")
  15322. },
  15323. /* -------------------------------------------------------------------------
  15324. // Cube map shader
  15325. ------------------------------------------------------------------------- */
  15326. 'cube': {
  15327. uniforms: { "tCube": { type: "t", value: null },
  15328. "tFlip": { type: "f", value: -1 } },
  15329. vertexShader: [
  15330. "varying vec3 vWorldPosition;",
  15331. "void main() {",
  15332. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15333. "vWorldPosition = worldPosition.xyz;",
  15334. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15335. "}"
  15336. ].join("\n"),
  15337. fragmentShader: [
  15338. "uniform samplerCube tCube;",
  15339. "uniform float tFlip;",
  15340. "varying vec3 vWorldPosition;",
  15341. "void main() {",
  15342. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15343. "}"
  15344. ].join("\n")
  15345. }
  15346. }
  15347. };
  15348. /**
  15349. * @author zz85 / http://www.lab4games.net/zz85/blog
  15350. * @author alteredq / http://alteredqualia.com/
  15351. *
  15352. * For Text operations in three.js (See TextGeometry)
  15353. *
  15354. * It uses techniques used in:
  15355. *
  15356. * typeface.js and canvastext
  15357. * For converting fonts and rendering with javascript
  15358. * http://typeface.neocracy.org
  15359. *
  15360. * Triangulation ported from AS3
  15361. * Simple Polygon Triangulation
  15362. * http://actionsnippet.com/?p=1462
  15363. *
  15364. * A Method to triangulate shapes with holes
  15365. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15366. *
  15367. */
  15368. THREE.FontUtils = {
  15369. faces : {},
  15370. // Just for now. face[weight][style]
  15371. face : "helvetiker",
  15372. weight: "normal",
  15373. style : "normal",
  15374. size : 150,
  15375. divisions : 10,
  15376. getFace : function() {
  15377. return this.faces[ this.face ][ this.weight ][ this.style ];
  15378. },
  15379. loadFace : function( data ) {
  15380. var family = data.familyName.toLowerCase();
  15381. var ThreeFont = this;
  15382. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15383. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15384. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15385. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15386. return data;
  15387. },
  15388. drawText : function( text ) {
  15389. var characterPts = [], allPts = [];
  15390. // RenderText
  15391. var i, p,
  15392. face = this.getFace(),
  15393. scale = this.size / face.resolution,
  15394. offset = 0,
  15395. chars = String( text ).split( '' ),
  15396. length = chars.length;
  15397. var fontPaths = [];
  15398. for ( i = 0; i < length; i ++ ) {
  15399. var path = new THREE.Path();
  15400. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15401. offset += ret.offset;
  15402. fontPaths.push( ret.path );
  15403. }
  15404. // get the width
  15405. var width = offset / 2;
  15406. //
  15407. // for ( p = 0; p < allPts.length; p++ ) {
  15408. //
  15409. // allPts[ p ].x -= width;
  15410. //
  15411. // }
  15412. //var extract = this.extractPoints( allPts, characterPts );
  15413. //extract.contour = allPts;
  15414. //extract.paths = fontPaths;
  15415. //extract.offset = width;
  15416. return { paths : fontPaths, offset : width };
  15417. },
  15418. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15419. var pts = [];
  15420. var i, i2, divisions,
  15421. outline, action, length,
  15422. scaleX, scaleY,
  15423. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15424. laste,
  15425. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15426. if ( !glyph ) return;
  15427. if ( glyph.o ) {
  15428. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15429. length = outline.length;
  15430. scaleX = scale;
  15431. scaleY = scale;
  15432. for ( i = 0; i < length; ) {
  15433. action = outline[ i ++ ];
  15434. //console.log( action );
  15435. switch( action ) {
  15436. case 'm':
  15437. // Move To
  15438. x = outline[ i++ ] * scaleX + offset;
  15439. y = outline[ i++ ] * scaleY;
  15440. path.moveTo( x, y );
  15441. break;
  15442. case 'l':
  15443. // Line To
  15444. x = outline[ i++ ] * scaleX + offset;
  15445. y = outline[ i++ ] * scaleY;
  15446. path.lineTo(x,y);
  15447. break;
  15448. case 'q':
  15449. // QuadraticCurveTo
  15450. cpx = outline[ i++ ] * scaleX + offset;
  15451. cpy = outline[ i++ ] * scaleY;
  15452. cpx1 = outline[ i++ ] * scaleX + offset;
  15453. cpy1 = outline[ i++ ] * scaleY;
  15454. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15455. laste = pts[ pts.length - 1 ];
  15456. if ( laste ) {
  15457. cpx0 = laste.x;
  15458. cpy0 = laste.y;
  15459. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15460. var t = i2 / divisions;
  15461. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15462. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15463. }
  15464. }
  15465. break;
  15466. case 'b':
  15467. // Cubic Bezier Curve
  15468. cpx = outline[ i++ ] * scaleX + offset;
  15469. cpy = outline[ i++ ] * scaleY;
  15470. cpx1 = outline[ i++ ] * scaleX + offset;
  15471. cpy1 = outline[ i++ ] * -scaleY;
  15472. cpx2 = outline[ i++ ] * scaleX + offset;
  15473. cpy2 = outline[ i++ ] * -scaleY;
  15474. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15475. laste = pts[ pts.length - 1 ];
  15476. if ( laste ) {
  15477. cpx0 = laste.x;
  15478. cpy0 = laste.y;
  15479. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15480. var t = i2 / divisions;
  15481. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15482. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15483. }
  15484. }
  15485. break;
  15486. }
  15487. }
  15488. }
  15489. return { offset: glyph.ha*scale, path:path};
  15490. }
  15491. };
  15492. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15493. // Parameters
  15494. parameters = parameters || {};
  15495. var size = parameters.size !== undefined ? parameters.size : 100;
  15496. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15497. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15498. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15499. var style = parameters.style !== undefined ? parameters.style : "normal";
  15500. THREE.FontUtils.size = size;
  15501. THREE.FontUtils.divisions = curveSegments;
  15502. THREE.FontUtils.face = font;
  15503. THREE.FontUtils.weight = weight;
  15504. THREE.FontUtils.style = style;
  15505. // Get a Font data json object
  15506. var data = THREE.FontUtils.drawText( text );
  15507. var paths = data.paths;
  15508. var shapes = [];
  15509. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15510. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15511. }
  15512. return shapes;
  15513. };
  15514. /**
  15515. * This code is a quick port of code written in C++ which was submitted to
  15516. * flipcode.com by John W. Ratcliff // July 22, 2000
  15517. * See original code and more information here:
  15518. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15519. *
  15520. * ported to actionscript by Zevan Rosser
  15521. * www.actionsnippet.com
  15522. *
  15523. * ported to javascript by Joshua Koo
  15524. * http://www.lab4games.net/zz85/blog
  15525. *
  15526. */
  15527. ( function( namespace ) {
  15528. var EPSILON = 0.0000000001;
  15529. // takes in an contour array and returns
  15530. var process = function( contour, indices ) {
  15531. var n = contour.length;
  15532. if ( n < 3 ) return null;
  15533. var result = [],
  15534. verts = [],
  15535. vertIndices = [];
  15536. /* we want a counter-clockwise polygon in verts */
  15537. var u, v, w;
  15538. if ( area( contour ) > 0.0 ) {
  15539. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15540. } else {
  15541. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15542. }
  15543. var nv = n;
  15544. /* remove nv - 2 vertices, creating 1 triangle every time */
  15545. var count = 2 * nv; /* error detection */
  15546. for( v = nv - 1; nv > 2; ) {
  15547. /* if we loop, it is probably a non-simple polygon */
  15548. if ( ( count-- ) <= 0 ) {
  15549. //** Triangulate: ERROR - probable bad polygon!
  15550. //throw ( "Warning, unable to triangulate polygon!" );
  15551. //return null;
  15552. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15553. console.log( "Warning, unable to triangulate polygon!" );
  15554. if ( indices ) return vertIndices;
  15555. return result;
  15556. }
  15557. /* three consecutive vertices in current polygon, <u,v,w> */
  15558. u = v; if ( nv <= u ) u = 0; /* previous */
  15559. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15560. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15561. if ( snip( contour, u, v, w, nv, verts ) ) {
  15562. var a, b, c, s, t;
  15563. /* true names of the vertices */
  15564. a = verts[ u ];
  15565. b = verts[ v ];
  15566. c = verts[ w ];
  15567. /* output Triangle */
  15568. /*
  15569. result.push( contour[ a ] );
  15570. result.push( contour[ b ] );
  15571. result.push( contour[ c ] );
  15572. */
  15573. result.push( [ contour[ a ],
  15574. contour[ b ],
  15575. contour[ c ] ] );
  15576. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15577. /* remove v from the remaining polygon */
  15578. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15579. verts[ s ] = verts[ t ];
  15580. }
  15581. nv--;
  15582. /* reset error detection counter */
  15583. count = 2 * nv;
  15584. }
  15585. }
  15586. if ( indices ) return vertIndices;
  15587. return result;
  15588. };
  15589. // calculate area of the contour polygon
  15590. var area = function ( contour ) {
  15591. var n = contour.length;
  15592. var a = 0.0;
  15593. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15594. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15595. }
  15596. return a * 0.5;
  15597. };
  15598. // see if p is inside triangle abc
  15599. var insideTriangle = function( ax, ay,
  15600. bx, by,
  15601. cx, cy,
  15602. px, py ) {
  15603. var aX, aY, bX, bY;
  15604. var cX, cY, apx, apy;
  15605. var bpx, bpy, cpx, cpy;
  15606. var cCROSSap, bCROSScp, aCROSSbp;
  15607. aX = cx - bx; aY = cy - by;
  15608. bX = ax - cx; bY = ay - cy;
  15609. cX = bx - ax; cY = by - ay;
  15610. apx= px -ax; apy= py - ay;
  15611. bpx= px - bx; bpy= py - by;
  15612. cpx= px - cx; cpy= py - cy;
  15613. aCROSSbp = aX*bpy - aY*bpx;
  15614. cCROSSap = cX*apy - cY*apx;
  15615. bCROSScp = bX*cpy - bY*cpx;
  15616. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15617. };
  15618. var snip = function ( contour, u, v, w, n, verts ) {
  15619. var p;
  15620. var ax, ay, bx, by;
  15621. var cx, cy, px, py;
  15622. ax = contour[ verts[ u ] ].x;
  15623. ay = contour[ verts[ u ] ].y;
  15624. bx = contour[ verts[ v ] ].x;
  15625. by = contour[ verts[ v ] ].y;
  15626. cx = contour[ verts[ w ] ].x;
  15627. cy = contour[ verts[ w ] ].y;
  15628. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15629. for ( p = 0; p < n; p++ ) {
  15630. if( (p == u) || (p == v) || (p == w) ) continue;
  15631. px = contour[ verts[ p ] ].x
  15632. py = contour[ verts[ p ] ].y
  15633. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15634. }
  15635. return true;
  15636. };
  15637. namespace.Triangulate = process;
  15638. namespace.Triangulate.area = area;
  15639. return namespace;
  15640. })(THREE.FontUtils);
  15641. // To use the typeface.js face files, hook up the API
  15642. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  15643. * @author zz85 / http://www.lab4games.net/zz85/blog
  15644. * Extensible curve object
  15645. *
  15646. * Some common of Curve methods
  15647. * .getPoint(t), getTangent(t)
  15648. * .getPointAt(u), getTagentAt(u)
  15649. * .getPoints(), .getSpacedPoints()
  15650. * .getLength()
  15651. * .updateArcLengths()
  15652. *
  15653. * This file contains following classes:
  15654. *
  15655. * -- 2d classes --
  15656. * THREE.Curve
  15657. * THREE.LineCurve
  15658. * THREE.QuadraticBezierCurve
  15659. * THREE.CubicBezierCurve
  15660. * THREE.SplineCurve
  15661. * THREE.ArcCurve
  15662. * THREE.EllipseCurve
  15663. *
  15664. * -- 3d classes --
  15665. * THREE.LineCurve3
  15666. * THREE.QuadraticBezierCurve3
  15667. * THREE.CubicBezierCurve3
  15668. * THREE.SplineCurve3
  15669. * THREE.ClosedSplineCurve3
  15670. *
  15671. * A series of curves can be represented as a THREE.CurvePath
  15672. *
  15673. **/
  15674. /**************************************************************
  15675. * Abstract Curve base class
  15676. **************************************************************/
  15677. THREE.Curve = function () {
  15678. };
  15679. // Virtual base class method to overwrite and implement in subclasses
  15680. // - t [0 .. 1]
  15681. THREE.Curve.prototype.getPoint = function ( t ) {
  15682. console.log( "Warning, getPoint() not implemented!" );
  15683. return null;
  15684. };
  15685. // Get point at relative position in curve according to arc length
  15686. // - u [0 .. 1]
  15687. THREE.Curve.prototype.getPointAt = function ( u ) {
  15688. var t = this.getUtoTmapping( u );
  15689. return this.getPoint( t );
  15690. };
  15691. // Get sequence of points using getPoint( t )
  15692. THREE.Curve.prototype.getPoints = function ( divisions ) {
  15693. if ( !divisions ) divisions = 5;
  15694. var d, pts = [];
  15695. for ( d = 0; d <= divisions; d ++ ) {
  15696. pts.push( this.getPoint( d / divisions ) );
  15697. }
  15698. return pts;
  15699. };
  15700. // Get sequence of points using getPointAt( u )
  15701. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  15702. if ( !divisions ) divisions = 5;
  15703. var d, pts = [];
  15704. for ( d = 0; d <= divisions; d ++ ) {
  15705. pts.push( this.getPointAt( d / divisions ) );
  15706. }
  15707. return pts;
  15708. };
  15709. // Get total curve arc length
  15710. THREE.Curve.prototype.getLength = function () {
  15711. var lengths = this.getLengths();
  15712. return lengths[ lengths.length - 1 ];
  15713. };
  15714. // Get list of cumulative segment lengths
  15715. THREE.Curve.prototype.getLengths = function ( divisions ) {
  15716. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  15717. if ( this.cacheArcLengths
  15718. && ( this.cacheArcLengths.length == divisions + 1 )
  15719. && !this.needsUpdate) {
  15720. //console.log( "cached", this.cacheArcLengths );
  15721. return this.cacheArcLengths;
  15722. }
  15723. this.needsUpdate = false;
  15724. var cache = [];
  15725. var current, last = this.getPoint( 0 );
  15726. var p, sum = 0;
  15727. cache.push( 0 );
  15728. for ( p = 1; p <= divisions; p ++ ) {
  15729. current = this.getPoint ( p / divisions );
  15730. sum += current.distanceTo( last );
  15731. cache.push( sum );
  15732. last = current;
  15733. }
  15734. this.cacheArcLengths = cache;
  15735. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  15736. };
  15737. THREE.Curve.prototype.updateArcLengths = function() {
  15738. this.needsUpdate = true;
  15739. this.getLengths();
  15740. };
  15741. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  15742. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  15743. var arcLengths = this.getLengths();
  15744. var i = 0, il = arcLengths.length;
  15745. var targetArcLength; // The targeted u distance value to get
  15746. if ( distance ) {
  15747. targetArcLength = distance;
  15748. } else {
  15749. targetArcLength = u * arcLengths[ il - 1 ];
  15750. }
  15751. //var time = Date.now();
  15752. // binary search for the index with largest value smaller than target u distance
  15753. var low = 0, high = il - 1, comparison;
  15754. while ( low <= high ) {
  15755. 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
  15756. comparison = arcLengths[ i ] - targetArcLength;
  15757. if ( comparison < 0 ) {
  15758. low = i + 1;
  15759. continue;
  15760. } else if ( comparison > 0 ) {
  15761. high = i - 1;
  15762. continue;
  15763. } else {
  15764. high = i;
  15765. break;
  15766. // DONE
  15767. }
  15768. }
  15769. i = high;
  15770. //console.log('b' , i, low, high, Date.now()- time);
  15771. if ( arcLengths[ i ] == targetArcLength ) {
  15772. var t = i / ( il - 1 );
  15773. return t;
  15774. }
  15775. // we could get finer grain at lengths, or use simple interpolatation between two points
  15776. var lengthBefore = arcLengths[ i ];
  15777. var lengthAfter = arcLengths[ i + 1 ];
  15778. var segmentLength = lengthAfter - lengthBefore;
  15779. // determine where we are between the 'before' and 'after' points
  15780. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  15781. // add that fractional amount to t
  15782. var t = ( i + segmentFraction ) / ( il -1 );
  15783. return t;
  15784. };
  15785. // In 2D space, there are actually 2 normal vectors,
  15786. // and in 3D space, infinte
  15787. // TODO this should be depreciated.
  15788. THREE.Curve.prototype.getNormalVector = function( t ) {
  15789. var vec = this.getTangent( t );
  15790. return new THREE.Vector2( -vec.y , vec.x );
  15791. };
  15792. // Returns a unit vector tangent at t
  15793. // In case any sub curve does not implement its tangent / normal finding,
  15794. // we get 2 points with a small delta and find a gradient of the 2 points
  15795. // which seems to make a reasonable approximation
  15796. THREE.Curve.prototype.getTangent = function( t ) {
  15797. var delta = 0.0001;
  15798. var t1 = t - delta;
  15799. var t2 = t + delta;
  15800. // Capping in case of danger
  15801. if ( t1 < 0 ) t1 = 0;
  15802. if ( t2 > 1 ) t2 = 1;
  15803. var pt1 = this.getPoint( t1 );
  15804. var pt2 = this.getPoint( t2 );
  15805. var vec = pt2.clone().subSelf(pt1);
  15806. return vec.normalize();
  15807. };
  15808. THREE.Curve.prototype.getTangentAt = function ( u ) {
  15809. var t = this.getUtoTmapping( u );
  15810. return this.getTangent( t );
  15811. };
  15812. /**************************************************************
  15813. * Line
  15814. **************************************************************/
  15815. THREE.LineCurve = function ( v1, v2 ) {
  15816. this.v1 = v1;
  15817. this.v2 = v2;
  15818. };
  15819. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  15820. THREE.LineCurve.prototype.getPoint = function ( t ) {
  15821. var point = this.v2.clone().subSelf(this.v1);
  15822. point.multiplyScalar( t ).addSelf( this.v1 );
  15823. return point;
  15824. };
  15825. // Line curve is linear, so we can overwrite default getPointAt
  15826. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  15827. return this.getPoint( u );
  15828. };
  15829. THREE.LineCurve.prototype.getTangent = function( t ) {
  15830. var tangent = this.v2.clone().subSelf(this.v1);
  15831. return tangent.normalize();
  15832. };
  15833. /**************************************************************
  15834. * Quadratic Bezier curve
  15835. **************************************************************/
  15836. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  15837. this.v0 = v0;
  15838. this.v1 = v1;
  15839. this.v2 = v2;
  15840. };
  15841. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15842. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  15843. var tx, ty;
  15844. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15845. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15846. return new THREE.Vector2( tx, ty );
  15847. };
  15848. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  15849. var tx, ty;
  15850. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  15851. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  15852. // returns unit vector
  15853. var tangent = new THREE.Vector2( tx, ty );
  15854. tangent.normalize();
  15855. return tangent;
  15856. };
  15857. /**************************************************************
  15858. * Cubic Bezier curve
  15859. **************************************************************/
  15860. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  15861. this.v0 = v0;
  15862. this.v1 = v1;
  15863. this.v2 = v2;
  15864. this.v3 = v3;
  15865. };
  15866. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15867. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  15868. var tx, ty;
  15869. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15870. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15871. return new THREE.Vector2( tx, ty );
  15872. };
  15873. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  15874. var tx, ty;
  15875. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15876. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15877. var tangent = new THREE.Vector2( tx, ty );
  15878. tangent.normalize();
  15879. return tangent;
  15880. };
  15881. /**************************************************************
  15882. * Spline curve
  15883. **************************************************************/
  15884. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  15885. this.points = (points == undefined) ? [] : points;
  15886. };
  15887. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  15888. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  15889. var v = new THREE.Vector2();
  15890. var c = [];
  15891. var points = this.points, point, intPoint, weight;
  15892. point = ( points.length - 1 ) * t;
  15893. intPoint = Math.floor( point );
  15894. weight = point - intPoint;
  15895. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15896. c[ 1 ] = intPoint;
  15897. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  15898. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  15899. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15900. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15901. return v;
  15902. };
  15903. /**************************************************************
  15904. * Ellipse curve
  15905. **************************************************************/
  15906. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  15907. aStartAngle, aEndAngle,
  15908. aClockwise ) {
  15909. this.aX = aX;
  15910. this.aY = aY;
  15911. this.xRadius = xRadius;
  15912. this.yRadius = yRadius;
  15913. this.aStartAngle = aStartAngle;
  15914. this.aEndAngle = aEndAngle;
  15915. this.aClockwise = aClockwise;
  15916. };
  15917. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  15918. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  15919. var deltaAngle = this.aEndAngle - this.aStartAngle;
  15920. if ( !this.aClockwise ) {
  15921. t = 1 - t;
  15922. }
  15923. var angle = this.aStartAngle + t * deltaAngle;
  15924. var tx = this.aX + this.xRadius * Math.cos( angle );
  15925. var ty = this.aY + this.yRadius * Math.sin( angle );
  15926. return new THREE.Vector2( tx, ty );
  15927. };
  15928. /**************************************************************
  15929. * Arc curve
  15930. **************************************************************/
  15931. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  15932. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  15933. };
  15934. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  15935. /**************************************************************
  15936. * Utils
  15937. **************************************************************/
  15938. THREE.Curve.Utils = {
  15939. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  15940. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  15941. },
  15942. // Puay Bing, thanks for helping with this derivative!
  15943. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  15944. return -3 * p0 * (1 - t) * (1 - t) +
  15945. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  15946. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  15947. 3 * t * t * p3;
  15948. },
  15949. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  15950. // To check if my formulas are correct
  15951. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  15952. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  15953. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  15954. var h11 = 3 * t * t - 2 * t; // t3 − t2
  15955. return h00 + h10 + h01 + h11;
  15956. },
  15957. // Catmull-Rom
  15958. interpolate: function( p0, p1, p2, p3, t ) {
  15959. var v0 = ( p2 - p0 ) * 0.5;
  15960. var v1 = ( p3 - p1 ) * 0.5;
  15961. var t2 = t * t;
  15962. var t3 = t * t2;
  15963. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  15964. }
  15965. };
  15966. // TODO: Transformation for Curves?
  15967. /**************************************************************
  15968. * 3D Curves
  15969. **************************************************************/
  15970. // A Factory method for creating new curve subclasses
  15971. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15972. constructor.prototype = Object.create( THREE.Curve.prototype );
  15973. constructor.prototype.getPoint = getPointFunc;
  15974. return constructor;
  15975. };
  15976. /**************************************************************
  15977. * Line3D
  15978. **************************************************************/
  15979. THREE.LineCurve3 = THREE.Curve.create(
  15980. function ( v1, v2 ) {
  15981. this.v1 = v1;
  15982. this.v2 = v2;
  15983. },
  15984. function ( t ) {
  15985. var r = new THREE.Vector3();
  15986. r.sub( this.v2, this.v1 ); // diff
  15987. r.multiplyScalar( t );
  15988. r.addSelf( this.v1 );
  15989. return r;
  15990. }
  15991. );
  15992. /**************************************************************
  15993. * Quadratic Bezier 3D curve
  15994. **************************************************************/
  15995. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  15996. function ( v0, v1, v2 ) {
  15997. this.v0 = v0;
  15998. this.v1 = v1;
  15999. this.v2 = v2;
  16000. },
  16001. function ( t ) {
  16002. var tx, ty, tz;
  16003. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16004. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16005. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16006. return new THREE.Vector3( tx, ty, tz );
  16007. }
  16008. );
  16009. /**************************************************************
  16010. * Cubic Bezier 3D curve
  16011. **************************************************************/
  16012. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16013. function ( v0, v1, v2, v3 ) {
  16014. this.v0 = v0;
  16015. this.v1 = v1;
  16016. this.v2 = v2;
  16017. this.v3 = v3;
  16018. },
  16019. function ( t ) {
  16020. var tx, ty, tz;
  16021. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16022. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16023. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16024. return new THREE.Vector3( tx, ty, tz );
  16025. }
  16026. );
  16027. /**************************************************************
  16028. * Spline 3D curve
  16029. **************************************************************/
  16030. THREE.SplineCurve3 = THREE.Curve.create(
  16031. function ( points /* array of Vector3 */) {
  16032. this.points = (points == undefined) ? [] : points;
  16033. },
  16034. function ( t ) {
  16035. var v = new THREE.Vector3();
  16036. var c = [];
  16037. var points = this.points, point, intPoint, weight;
  16038. point = ( points.length - 1 ) * t;
  16039. intPoint = Math.floor( point );
  16040. weight = point - intPoint;
  16041. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16042. c[ 1 ] = intPoint;
  16043. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16044. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16045. var pt0 = points[ c[0] ],
  16046. pt1 = points[ c[1] ],
  16047. pt2 = points[ c[2] ],
  16048. pt3 = points[ c[3] ];
  16049. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16050. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16051. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16052. return v;
  16053. }
  16054. );
  16055. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16056. // var v = new THREE.Vector3();
  16057. // var c = [];
  16058. // var points = this.points, point, intPoint, weight;
  16059. // point = ( points.length - 1 ) * t;
  16060. // intPoint = Math.floor( point );
  16061. // weight = point - intPoint;
  16062. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16063. // c[ 1 ] = intPoint;
  16064. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16065. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16066. // var pt0 = points[ c[0] ],
  16067. // pt1 = points[ c[1] ],
  16068. // pt2 = points[ c[2] ],
  16069. // pt3 = points[ c[3] ];
  16070. // // t = weight;
  16071. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16072. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16073. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16074. // return v;
  16075. // }
  16076. /**************************************************************
  16077. * Closed Spline 3D curve
  16078. **************************************************************/
  16079. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16080. function ( points /* array of Vector3 */) {
  16081. this.points = (points == undefined) ? [] : points;
  16082. },
  16083. function ( t ) {
  16084. var v = new THREE.Vector3();
  16085. var c = [];
  16086. var points = this.points, point, intPoint, weight;
  16087. point = ( points.length - 0 ) * t;
  16088. // This needs to be from 0-length +1
  16089. intPoint = Math.floor( point );
  16090. weight = point - intPoint;
  16091. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16092. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16093. c[ 1 ] = ( intPoint ) % points.length;
  16094. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16095. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16096. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16097. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16098. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16099. return v;
  16100. }
  16101. );
  16102. /**
  16103. * @author zz85 / http://www.lab4games.net/zz85/blog
  16104. *
  16105. **/
  16106. /**************************************************************
  16107. * Curved Path - a curve path is simply a array of connected
  16108. * curves, but retains the api of a curve
  16109. **************************************************************/
  16110. THREE.CurvePath = function () {
  16111. this.curves = [];
  16112. this.bends = [];
  16113. this.autoClose = false; // Automatically closes the path
  16114. };
  16115. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16116. THREE.CurvePath.prototype.add = function ( curve ) {
  16117. this.curves.push( curve );
  16118. };
  16119. THREE.CurvePath.prototype.checkConnection = function() {
  16120. // TODO
  16121. // If the ending of curve is not connected to the starting
  16122. // or the next curve, then, this is not a real path
  16123. };
  16124. THREE.CurvePath.prototype.closePath = function() {
  16125. // TODO Test
  16126. // and verify for vector3 (needs to implement equals)
  16127. // Add a line curve if start and end of lines are not connected
  16128. var startPoint = this.curves[0].getPoint(0);
  16129. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16130. if (!startPoint.equals(endPoint)) {
  16131. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16132. }
  16133. };
  16134. // To get accurate point with reference to
  16135. // entire path distance at time t,
  16136. // following has to be done:
  16137. // 1. Length of each sub path have to be known
  16138. // 2. Locate and identify type of curve
  16139. // 3. Get t for the curve
  16140. // 4. Return curve.getPointAt(t')
  16141. THREE.CurvePath.prototype.getPoint = function( t ) {
  16142. var d = t * this.getLength();
  16143. var curveLengths = this.getCurveLengths();
  16144. var i = 0, diff, curve;
  16145. // To think about boundaries points.
  16146. while ( i < curveLengths.length ) {
  16147. if ( curveLengths[ i ] >= d ) {
  16148. diff = curveLengths[ i ] - d;
  16149. curve = this.curves[ i ];
  16150. var u = 1 - diff / curve.getLength();
  16151. return curve.getPointAt( u );
  16152. break;
  16153. }
  16154. i ++;
  16155. }
  16156. return null;
  16157. // loop where sum != 0, sum > d , sum+1 <d
  16158. };
  16159. /*
  16160. THREE.CurvePath.prototype.getTangent = function( t ) {
  16161. };*/
  16162. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16163. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16164. // getPoint() depends on getLength
  16165. THREE.CurvePath.prototype.getLength = function() {
  16166. var lens = this.getCurveLengths();
  16167. return lens[ lens.length - 1 ];
  16168. };
  16169. // Compute lengths and cache them
  16170. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16171. THREE.CurvePath.prototype.getCurveLengths = function() {
  16172. // We use cache values if curves and cache array are same length
  16173. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16174. return this.cacheLengths;
  16175. };
  16176. // Get length of subsurve
  16177. // Push sums into cached array
  16178. var lengths = [], sums = 0;
  16179. var i, il = this.curves.length;
  16180. for ( i = 0; i < il; i ++ ) {
  16181. sums += this.curves[ i ].getLength();
  16182. lengths.push( sums );
  16183. }
  16184. this.cacheLengths = lengths;
  16185. return lengths;
  16186. };
  16187. // Returns min and max coordinates, as well as centroid
  16188. THREE.CurvePath.prototype.getBoundingBox = function () {
  16189. var points = this.getPoints();
  16190. var maxX, maxY, maxZ;
  16191. var minX, minY, minZ;
  16192. maxX = maxY = Number.NEGATIVE_INFINITY;
  16193. minX = minY = Number.POSITIVE_INFINITY;
  16194. var p, i, il, sum;
  16195. var v3 = points[0] instanceof THREE.Vector3;
  16196. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16197. for ( i = 0, il = points.length; i < il; i ++ ) {
  16198. p = points[ i ];
  16199. if ( p.x > maxX ) maxX = p.x;
  16200. else if ( p.x < minX ) minX = p.x;
  16201. if ( p.y > maxY ) maxY = p.y;
  16202. else if ( p.y < minY ) minY = p.y;
  16203. if (v3) {
  16204. if ( p.z > maxZ ) maxZ = p.z;
  16205. else if ( p.z < minZ ) minZ = p.z;
  16206. }
  16207. sum.addSelf( p );
  16208. }
  16209. var ret = {
  16210. minX: minX,
  16211. minY: minY,
  16212. maxX: maxX,
  16213. maxY: maxY,
  16214. centroid: sum.divideScalar( il )
  16215. };
  16216. if (v3) {
  16217. ret.maxZ = maxZ;
  16218. ret.minZ = minZ;
  16219. }
  16220. return ret;
  16221. };
  16222. /**************************************************************
  16223. * Create Geometries Helpers
  16224. **************************************************************/
  16225. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16226. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16227. var pts = this.getPoints( divisions, true );
  16228. return this.createGeometry( pts );
  16229. };
  16230. // Generate geometry from equidistance sampling along the path
  16231. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16232. var pts = this.getSpacedPoints( divisions, true );
  16233. return this.createGeometry( pts );
  16234. };
  16235. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16236. var geometry = new THREE.Geometry();
  16237. for ( var i = 0; i < points.length; i ++ ) {
  16238. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16239. }
  16240. return geometry;
  16241. };
  16242. /**************************************************************
  16243. * Bend / Wrap Helper Methods
  16244. **************************************************************/
  16245. // Wrap path / Bend modifiers?
  16246. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16247. this.bends.push( bendpath );
  16248. };
  16249. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16250. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16251. var i, il;
  16252. if ( !bends ) {
  16253. bends = this.bends;
  16254. }
  16255. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16256. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16257. }
  16258. return oldPts;
  16259. };
  16260. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16261. var oldPts = this.getSpacedPoints( segments );
  16262. var i, il;
  16263. if ( !bends ) {
  16264. bends = this.bends;
  16265. }
  16266. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16267. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16268. }
  16269. return oldPts;
  16270. };
  16271. // This returns getPoints() bend/wrapped around the contour of a path.
  16272. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16273. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16274. var bounds = this.getBoundingBox();
  16275. var i, il, p, oldX, oldY, xNorm;
  16276. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16277. p = oldPts[ i ];
  16278. oldX = p.x;
  16279. oldY = p.y;
  16280. xNorm = oldX / bounds.maxX;
  16281. // If using actual distance, for length > path, requires line extrusions
  16282. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16283. xNorm = path.getUtoTmapping( xNorm, oldX );
  16284. // check for out of bounds?
  16285. var pathPt = path.getPoint( xNorm );
  16286. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16287. p.x = pathPt.x + normal.x;
  16288. p.y = pathPt.y + normal.y;
  16289. }
  16290. return oldPts;
  16291. };
  16292. /**
  16293. * @author alteredq / http://alteredqualia.com/
  16294. */
  16295. THREE.Gyroscope = function () {
  16296. THREE.Object3D.call( this );
  16297. };
  16298. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16299. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16300. this.matrixAutoUpdate && this.updateMatrix();
  16301. // update matrixWorld
  16302. if ( this.matrixWorldNeedsUpdate || force ) {
  16303. if ( this.parent ) {
  16304. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  16305. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16306. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16307. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16308. } else {
  16309. this.matrixWorld.copy( this.matrix );
  16310. }
  16311. this.matrixWorldNeedsUpdate = false;
  16312. force = true;
  16313. }
  16314. // update children
  16315. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16316. this.children[ i ].updateMatrixWorld( force );
  16317. }
  16318. };
  16319. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16320. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16321. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16322. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16323. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16324. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16325. /**
  16326. * @author zz85 / http://www.lab4games.net/zz85/blog
  16327. * Creates free form 2d path using series of points, lines or curves.
  16328. *
  16329. **/
  16330. THREE.Path = function ( points ) {
  16331. THREE.CurvePath.call(this);
  16332. this.actions = [];
  16333. if ( points ) {
  16334. this.fromPoints( points );
  16335. }
  16336. };
  16337. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16338. THREE.PathActions = {
  16339. MOVE_TO: 'moveTo',
  16340. LINE_TO: 'lineTo',
  16341. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16342. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16343. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16344. ARC: 'arc', // Circle
  16345. ELLIPSE: 'ellipse'
  16346. };
  16347. // TODO Clean up PATH API
  16348. // Create path using straight lines to connect all points
  16349. // - vectors: array of Vector2
  16350. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16351. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16352. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16353. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16354. };
  16355. };
  16356. // startPath() endPath()?
  16357. THREE.Path.prototype.moveTo = function ( x, y ) {
  16358. var args = Array.prototype.slice.call( arguments );
  16359. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16360. };
  16361. THREE.Path.prototype.lineTo = function ( x, y ) {
  16362. var args = Array.prototype.slice.call( arguments );
  16363. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16364. var x0 = lastargs[ lastargs.length - 2 ];
  16365. var y0 = lastargs[ lastargs.length - 1 ];
  16366. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16367. this.curves.push( curve );
  16368. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16369. };
  16370. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16371. var args = Array.prototype.slice.call( arguments );
  16372. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16373. var x0 = lastargs[ lastargs.length - 2 ];
  16374. var y0 = lastargs[ lastargs.length - 1 ];
  16375. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16376. new THREE.Vector2( aCPx, aCPy ),
  16377. new THREE.Vector2( aX, aY ) );
  16378. this.curves.push( curve );
  16379. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16380. };
  16381. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16382. aCP2x, aCP2y,
  16383. aX, aY ) {
  16384. var args = Array.prototype.slice.call( arguments );
  16385. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16386. var x0 = lastargs[ lastargs.length - 2 ];
  16387. var y0 = lastargs[ lastargs.length - 1 ];
  16388. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16389. new THREE.Vector2( aCP1x, aCP1y ),
  16390. new THREE.Vector2( aCP2x, aCP2y ),
  16391. new THREE.Vector2( aX, aY ) );
  16392. this.curves.push( curve );
  16393. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16394. };
  16395. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16396. var args = Array.prototype.slice.call( arguments );
  16397. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16398. var x0 = lastargs[ lastargs.length - 2 ];
  16399. var y0 = lastargs[ lastargs.length - 1 ];
  16400. //---
  16401. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16402. Array.prototype.push.apply( npts, pts );
  16403. var curve = new THREE.SplineCurve( npts );
  16404. this.curves.push( curve );
  16405. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16406. };
  16407. // FUTURE: Change the API or follow canvas API?
  16408. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16409. aStartAngle, aEndAngle, aClockwise ) {
  16410. var lastargs = this.actions[ this.actions.length - 1].args;
  16411. var x0 = lastargs[ lastargs.length - 2 ];
  16412. var y0 = lastargs[ lastargs.length - 1 ];
  16413. this.absarc(aX + x0, aY + y0, aRadius,
  16414. aStartAngle, aEndAngle, aClockwise );
  16415. };
  16416. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16417. aStartAngle, aEndAngle, aClockwise ) {
  16418. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16419. };
  16420. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16421. aStartAngle, aEndAngle, aClockwise ) {
  16422. var lastargs = this.actions[ this.actions.length - 1].args;
  16423. var x0 = lastargs[ lastargs.length - 2 ];
  16424. var y0 = lastargs[ lastargs.length - 1 ];
  16425. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16426. aStartAngle, aEndAngle, aClockwise );
  16427. };
  16428. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16429. aStartAngle, aEndAngle, aClockwise ) {
  16430. var args = Array.prototype.slice.call( arguments );
  16431. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16432. aStartAngle, aEndAngle, aClockwise );
  16433. this.curves.push( curve );
  16434. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16435. args.push(lastPoint.x);
  16436. args.push(lastPoint.y);
  16437. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16438. };
  16439. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16440. if ( ! divisions ) divisions = 40;
  16441. var points = [];
  16442. for ( var i = 0; i < divisions; i ++ ) {
  16443. points.push( this.getPoint( i / divisions ) );
  16444. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16445. }
  16446. // if ( closedPath ) {
  16447. //
  16448. // points.push( points[ 0 ] );
  16449. //
  16450. // }
  16451. return points;
  16452. };
  16453. /* Return an array of vectors based on contour of the path */
  16454. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16455. if (this.useSpacedPoints) {
  16456. console.log('tata');
  16457. return this.getSpacedPoints( divisions, closedPath );
  16458. }
  16459. divisions = divisions || 12;
  16460. var points = [];
  16461. var i, il, item, action, args;
  16462. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16463. laste, j,
  16464. t, tx, ty;
  16465. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16466. item = this.actions[ i ];
  16467. action = item.action;
  16468. args = item.args;
  16469. switch( action ) {
  16470. case THREE.PathActions.MOVE_TO:
  16471. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16472. break;
  16473. case THREE.PathActions.LINE_TO:
  16474. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16475. break;
  16476. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16477. cpx = args[ 2 ];
  16478. cpy = args[ 3 ];
  16479. cpx1 = args[ 0 ];
  16480. cpy1 = args[ 1 ];
  16481. if ( points.length > 0 ) {
  16482. laste = points[ points.length - 1 ];
  16483. cpx0 = laste.x;
  16484. cpy0 = laste.y;
  16485. } else {
  16486. laste = this.actions[ i - 1 ].args;
  16487. cpx0 = laste[ laste.length - 2 ];
  16488. cpy0 = laste[ laste.length - 1 ];
  16489. }
  16490. for ( j = 1; j <= divisions; j ++ ) {
  16491. t = j / divisions;
  16492. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16493. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16494. points.push( new THREE.Vector2( tx, ty ) );
  16495. }
  16496. break;
  16497. case THREE.PathActions.BEZIER_CURVE_TO:
  16498. cpx = args[ 4 ];
  16499. cpy = args[ 5 ];
  16500. cpx1 = args[ 0 ];
  16501. cpy1 = args[ 1 ];
  16502. cpx2 = args[ 2 ];
  16503. cpy2 = args[ 3 ];
  16504. if ( points.length > 0 ) {
  16505. laste = points[ points.length - 1 ];
  16506. cpx0 = laste.x;
  16507. cpy0 = laste.y;
  16508. } else {
  16509. laste = this.actions[ i - 1 ].args;
  16510. cpx0 = laste[ laste.length - 2 ];
  16511. cpy0 = laste[ laste.length - 1 ];
  16512. }
  16513. for ( j = 1; j <= divisions; j ++ ) {
  16514. t = j / divisions;
  16515. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16516. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16517. points.push( new THREE.Vector2( tx, ty ) );
  16518. }
  16519. break;
  16520. case THREE.PathActions.CSPLINE_THRU:
  16521. laste = this.actions[ i - 1 ].args;
  16522. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16523. var spts = [ last ];
  16524. var n = divisions * args[ 0 ].length;
  16525. spts = spts.concat( args[ 0 ] );
  16526. var spline = new THREE.SplineCurve( spts );
  16527. for ( j = 1; j <= n; j ++ ) {
  16528. points.push( spline.getPointAt( j / n ) ) ;
  16529. }
  16530. break;
  16531. case THREE.PathActions.ARC:
  16532. var aX = args[ 0 ], aY = args[ 1 ],
  16533. aRadius = args[ 2 ],
  16534. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16535. aClockwise = !!args[ 5 ];
  16536. var deltaAngle = aEndAngle - aStartAngle;
  16537. var angle;
  16538. var tdivisions = divisions * 2;
  16539. for ( j = 1; j <= tdivisions; j ++ ) {
  16540. t = j / tdivisions;
  16541. if ( ! aClockwise ) {
  16542. t = 1 - t;
  16543. }
  16544. angle = aStartAngle + t * deltaAngle;
  16545. tx = aX + aRadius * Math.cos( angle );
  16546. ty = aY + aRadius * Math.sin( angle );
  16547. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16548. points.push( new THREE.Vector2( tx, ty ) );
  16549. }
  16550. //console.log(points);
  16551. break;
  16552. case THREE.PathActions.ELLIPSE:
  16553. var aX = args[ 0 ], aY = args[ 1 ],
  16554. xRadius = args[ 2 ],
  16555. yRadius = args[ 3 ],
  16556. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16557. aClockwise = !!args[ 6 ];
  16558. var deltaAngle = aEndAngle - aStartAngle;
  16559. var angle;
  16560. var tdivisions = divisions * 2;
  16561. for ( j = 1; j <= tdivisions; j ++ ) {
  16562. t = j / tdivisions;
  16563. if ( ! aClockwise ) {
  16564. t = 1 - t;
  16565. }
  16566. angle = aStartAngle + t * deltaAngle;
  16567. tx = aX + xRadius * Math.cos( angle );
  16568. ty = aY + yRadius * Math.sin( angle );
  16569. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16570. points.push( new THREE.Vector2( tx, ty ) );
  16571. }
  16572. //console.log(points);
  16573. break;
  16574. } // end switch
  16575. }
  16576. // Normalize to remove the closing point by default.
  16577. var lastPoint = points[ points.length - 1];
  16578. var EPSILON = 0.0000000001;
  16579. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16580. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16581. points.splice( points.length - 1, 1);
  16582. if ( closedPath ) {
  16583. points.push( points[ 0 ] );
  16584. }
  16585. return points;
  16586. };
  16587. // Breaks path into shapes
  16588. THREE.Path.prototype.toShapes = function() {
  16589. var i, il, item, action, args;
  16590. var subPaths = [], lastPath = new THREE.Path();
  16591. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16592. item = this.actions[ i ];
  16593. args = item.args;
  16594. action = item.action;
  16595. if ( action == THREE.PathActions.MOVE_TO ) {
  16596. if ( lastPath.actions.length != 0 ) {
  16597. subPaths.push( lastPath );
  16598. lastPath = new THREE.Path();
  16599. }
  16600. }
  16601. lastPath[ action ].apply( lastPath, args );
  16602. }
  16603. if ( lastPath.actions.length != 0 ) {
  16604. subPaths.push( lastPath );
  16605. }
  16606. // console.log(subPaths);
  16607. if ( subPaths.length == 0 ) return [];
  16608. var tmpPath, tmpShape, shapes = [];
  16609. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16610. // console.log("Holes first", holesFirst);
  16611. if ( subPaths.length == 1) {
  16612. tmpPath = subPaths[0];
  16613. tmpShape = new THREE.Shape();
  16614. tmpShape.actions = tmpPath.actions;
  16615. tmpShape.curves = tmpPath.curves;
  16616. shapes.push( tmpShape );
  16617. return shapes;
  16618. };
  16619. if ( holesFirst ) {
  16620. tmpShape = new THREE.Shape();
  16621. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16622. tmpPath = subPaths[ i ];
  16623. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16624. tmpShape.actions = tmpPath.actions;
  16625. tmpShape.curves = tmpPath.curves;
  16626. shapes.push( tmpShape );
  16627. tmpShape = new THREE.Shape();
  16628. //console.log('cw', i);
  16629. } else {
  16630. tmpShape.holes.push( tmpPath );
  16631. //console.log('ccw', i);
  16632. }
  16633. }
  16634. } else {
  16635. // Shapes first
  16636. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16637. tmpPath = subPaths[ i ];
  16638. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16639. if ( tmpShape ) shapes.push( tmpShape );
  16640. tmpShape = new THREE.Shape();
  16641. tmpShape.actions = tmpPath.actions;
  16642. tmpShape.curves = tmpPath.curves;
  16643. } else {
  16644. tmpShape.holes.push( tmpPath );
  16645. }
  16646. }
  16647. shapes.push( tmpShape );
  16648. }
  16649. //console.log("shape", shapes);
  16650. return shapes;
  16651. };
  16652. /**
  16653. * @author zz85 / http://www.lab4games.net/zz85/blog
  16654. * Defines a 2d shape plane using paths.
  16655. **/
  16656. // STEP 1 Create a path.
  16657. // STEP 2 Turn path into shape.
  16658. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16659. // STEP 3a - Extract points from each shape, turn to vertices
  16660. // STEP 3b - Triangulate each shape, add faces.
  16661. THREE.Shape = function ( ) {
  16662. THREE.Path.apply( this, arguments );
  16663. this.holes = [];
  16664. };
  16665. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16666. // Convenience method to return ExtrudeGeometry
  16667. THREE.Shape.prototype.extrude = function ( options ) {
  16668. var extruded = new THREE.ExtrudeGeometry( this, options );
  16669. return extruded;
  16670. };
  16671. // Convenience method to return ShapeGeometry
  16672. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16673. var geometry = new THREE.ShapeGeometry( this, options );
  16674. return geometry;
  16675. };
  16676. // Get points of holes
  16677. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16678. var i, il = this.holes.length, holesPts = [];
  16679. for ( i = 0; i < il; i ++ ) {
  16680. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16681. }
  16682. return holesPts;
  16683. };
  16684. // Get points of holes (spaced by regular distance)
  16685. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16686. var i, il = this.holes.length, holesPts = [];
  16687. for ( i = 0; i < il; i ++ ) {
  16688. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16689. }
  16690. return holesPts;
  16691. };
  16692. // Get points of shape and holes (keypoints based on segments parameter)
  16693. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16694. return {
  16695. shape: this.getTransformedPoints( divisions ),
  16696. holes: this.getPointsHoles( divisions )
  16697. };
  16698. };
  16699. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16700. if (this.useSpacedPoints) {
  16701. return this.extractAllSpacedPoints(divisions);
  16702. }
  16703. return this.extractAllPoints(divisions);
  16704. };
  16705. //
  16706. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16707. //
  16708. // return {
  16709. //
  16710. // shape: this.transform( bend, divisions ),
  16711. // holes: this.getPointsHoles( divisions, bend )
  16712. //
  16713. // };
  16714. //
  16715. // };
  16716. // Get points of shape and holes (spaced by regular distance)
  16717. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16718. return {
  16719. shape: this.getTransformedSpacedPoints( divisions ),
  16720. holes: this.getSpacedPointsHoles( divisions )
  16721. };
  16722. };
  16723. /**************************************************************
  16724. * Utils
  16725. **************************************************************/
  16726. THREE.Shape.Utils = {
  16727. /*
  16728. contour - array of vector2 for contour
  16729. holes - array of array of vector2
  16730. */
  16731. removeHoles: function ( contour, holes ) {
  16732. var shape = contour.concat(); // work on this shape
  16733. var allpoints = shape.concat();
  16734. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  16735. var prevShapeVert, nextShapeVert,
  16736. prevHoleVert, nextHoleVert,
  16737. holeIndex, shapeIndex,
  16738. shapeId, shapeGroup,
  16739. h, h2,
  16740. hole, shortest, d,
  16741. p, pts1, pts2,
  16742. tmpShape1, tmpShape2,
  16743. tmpHole1, tmpHole2,
  16744. verts = [];
  16745. for ( h = 0; h < holes.length; h ++ ) {
  16746. hole = holes[ h ];
  16747. /*
  16748. shapeholes[ h ].concat(); // preserves original
  16749. holes.push( hole );
  16750. */
  16751. Array.prototype.push.apply( allpoints, hole );
  16752. shortest = Number.POSITIVE_INFINITY;
  16753. // Find the shortest pair of pts between shape and hole
  16754. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  16755. // Using distanceToSquared() intead of distanceTo() should speed a little
  16756. // since running square roots operations are reduced.
  16757. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  16758. pts1 = hole[ h2 ];
  16759. var dist = [];
  16760. for ( p = 0; p < shape.length; p++ ) {
  16761. pts2 = shape[ p ];
  16762. d = pts1.distanceToSquared( pts2 );
  16763. dist.push( d );
  16764. if ( d < shortest ) {
  16765. shortest = d;
  16766. holeIndex = h2;
  16767. shapeIndex = p;
  16768. }
  16769. }
  16770. }
  16771. //console.log("shortest", shortest, dist);
  16772. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16773. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16774. var areaapts = [
  16775. hole[ holeIndex ],
  16776. shape[ shapeIndex ],
  16777. shape[ prevShapeVert ]
  16778. ];
  16779. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  16780. var areabpts = [
  16781. hole[ holeIndex ],
  16782. hole[ prevHoleVert ],
  16783. shape[ shapeIndex ]
  16784. ];
  16785. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  16786. var shapeOffset = 1;
  16787. var holeOffset = -1;
  16788. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  16789. shapeIndex += shapeOffset;
  16790. holeIndex += holeOffset;
  16791. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16792. shapeIndex %= shape.length;
  16793. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16794. holeIndex %= hole.length;
  16795. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16796. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16797. areaapts = [
  16798. hole[ holeIndex ],
  16799. shape[ shapeIndex ],
  16800. shape[ prevShapeVert ]
  16801. ];
  16802. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  16803. areabpts = [
  16804. hole[ holeIndex ],
  16805. hole[ prevHoleVert ],
  16806. shape[ shapeIndex ]
  16807. ];
  16808. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  16809. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  16810. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  16811. // In case areas are not correct.
  16812. //console.log("USE THIS");
  16813. shapeIndex = oldShapeIndex;
  16814. holeIndex = oldHoleIndex ;
  16815. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16816. shapeIndex %= shape.length;
  16817. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16818. holeIndex %= hole.length;
  16819. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16820. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16821. } else {
  16822. //console.log("USE THAT ")
  16823. }
  16824. tmpShape1 = shape.slice( 0, shapeIndex );
  16825. tmpShape2 = shape.slice( shapeIndex );
  16826. tmpHole1 = hole.slice( holeIndex );
  16827. tmpHole2 = hole.slice( 0, holeIndex );
  16828. // Should check orders here again?
  16829. var trianglea = [
  16830. hole[ holeIndex ],
  16831. shape[ shapeIndex ],
  16832. shape[ prevShapeVert ]
  16833. ];
  16834. var triangleb = [
  16835. hole[ holeIndex ] ,
  16836. hole[ prevHoleVert ],
  16837. shape[ shapeIndex ]
  16838. ];
  16839. verts.push( trianglea );
  16840. verts.push( triangleb );
  16841. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16842. }
  16843. return {
  16844. shape:shape, /* shape with no holes */
  16845. isolatedPts: verts, /* isolated faces */
  16846. allpoints: allpoints
  16847. }
  16848. },
  16849. triangulateShape: function ( contour, holes ) {
  16850. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  16851. var shape = shapeWithoutHoles.shape,
  16852. allpoints = shapeWithoutHoles.allpoints,
  16853. isolatedPts = shapeWithoutHoles.isolatedPts;
  16854. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  16855. // 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.
  16856. //console.log( "triangles",triangles, triangles.length );
  16857. //console.log( "allpoints",allpoints, allpoints.length );
  16858. var i, il, f, face,
  16859. key, index,
  16860. allPointsMap = {},
  16861. isolatedPointsMap = {};
  16862. // prepare all points map
  16863. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16864. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  16865. if ( allPointsMap[ key ] !== undefined ) {
  16866. console.log( "Duplicate point", key );
  16867. }
  16868. allPointsMap[ key ] = i;
  16869. }
  16870. // check all face vertices against all points map
  16871. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  16872. face = triangles[ i ];
  16873. for ( f = 0; f < 3; f ++ ) {
  16874. key = face[ f ].x + ":" + face[ f ].y;
  16875. index = allPointsMap[ key ];
  16876. if ( index !== undefined ) {
  16877. face[ f ] = index;
  16878. }
  16879. }
  16880. }
  16881. // check isolated points vertices against all points map
  16882. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  16883. face = isolatedPts[ i ];
  16884. for ( f = 0; f < 3; f ++ ) {
  16885. key = face[ f ].x + ":" + face[ f ].y;
  16886. index = allPointsMap[ key ];
  16887. if ( index !== undefined ) {
  16888. face[ f ] = index;
  16889. }
  16890. }
  16891. }
  16892. return triangles.concat( isolatedPts );
  16893. }, // end triangulate shapes
  16894. /*
  16895. triangulate2 : function( pts, holes ) {
  16896. // For use with Poly2Tri.js
  16897. var allpts = pts.concat();
  16898. var shape = [];
  16899. for (var p in pts) {
  16900. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  16901. }
  16902. var swctx = new js.poly2tri.SweepContext(shape);
  16903. for (var h in holes) {
  16904. var aHole = holes[h];
  16905. var newHole = []
  16906. for (i in aHole) {
  16907. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  16908. allpts.push(aHole[i]);
  16909. }
  16910. swctx.AddHole(newHole);
  16911. }
  16912. var find;
  16913. var findIndexForPt = function (pt) {
  16914. find = new THREE.Vector2(pt.x, pt.y);
  16915. var p;
  16916. for (p=0, pl = allpts.length; p<pl; p++) {
  16917. if (allpts[p].equals(find)) return p;
  16918. }
  16919. return -1;
  16920. };
  16921. // triangulate
  16922. js.poly2tri.sweep.Triangulate(swctx);
  16923. var triangles = swctx.GetTriangles();
  16924. var tr ;
  16925. var facesPts = [];
  16926. for (var t in triangles) {
  16927. tr = triangles[t];
  16928. facesPts.push([
  16929. findIndexForPt(tr.GetPoint(0)),
  16930. findIndexForPt(tr.GetPoint(1)),
  16931. findIndexForPt(tr.GetPoint(2))
  16932. ]);
  16933. }
  16934. // console.log(facesPts);
  16935. // console.log("triangles", triangles.length, triangles);
  16936. // Returns array of faces with 3 element each
  16937. return facesPts;
  16938. },
  16939. */
  16940. isClockWise: function ( pts ) {
  16941. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  16942. },
  16943. // Bezier Curves formulas obtained from
  16944. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  16945. // Quad Bezier Functions
  16946. b2p0: function ( t, p ) {
  16947. var k = 1 - t;
  16948. return k * k * p;
  16949. },
  16950. b2p1: function ( t, p ) {
  16951. return 2 * ( 1 - t ) * t * p;
  16952. },
  16953. b2p2: function ( t, p ) {
  16954. return t * t * p;
  16955. },
  16956. b2: function ( t, p0, p1, p2 ) {
  16957. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  16958. },
  16959. // Cubic Bezier Functions
  16960. b3p0: function ( t, p ) {
  16961. var k = 1 - t;
  16962. return k * k * k * p;
  16963. },
  16964. b3p1: function ( t, p ) {
  16965. var k = 1 - t;
  16966. return 3 * k * k * t * p;
  16967. },
  16968. b3p2: function ( t, p ) {
  16969. var k = 1 - t;
  16970. return 3 * k * t * t * p;
  16971. },
  16972. b3p3: function ( t, p ) {
  16973. return t * t * t * p;
  16974. },
  16975. b3: function ( t, p0, p1, p2, p3 ) {
  16976. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  16977. }
  16978. };
  16979. /**
  16980. * @author mikael emtinger / http://gomo.se/
  16981. */
  16982. THREE.AnimationHandler = (function() {
  16983. var playing = [];
  16984. var library = {};
  16985. var that = {};
  16986. //--- update ---
  16987. that.update = function( deltaTimeMS ) {
  16988. for( var i = 0; i < playing.length; i ++ )
  16989. playing[ i ].update( deltaTimeMS );
  16990. };
  16991. //--- add ---
  16992. that.addToUpdate = function( animation ) {
  16993. if ( playing.indexOf( animation ) === -1 )
  16994. playing.push( animation );
  16995. };
  16996. //--- remove ---
  16997. that.removeFromUpdate = function( animation ) {
  16998. var index = playing.indexOf( animation );
  16999. if( index !== -1 )
  17000. playing.splice( index, 1 );
  17001. };
  17002. //--- add ---
  17003. that.add = function( data ) {
  17004. if ( library[ data.name ] !== undefined )
  17005. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17006. library[ data.name ] = data;
  17007. initData( data );
  17008. };
  17009. //--- get ---
  17010. that.get = function( name ) {
  17011. if ( typeof name === "string" ) {
  17012. if ( library[ name ] ) {
  17013. return library[ name ];
  17014. } else {
  17015. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17016. return null;
  17017. }
  17018. } else {
  17019. // todo: add simple tween library
  17020. }
  17021. };
  17022. //--- parse ---
  17023. that.parse = function( root ) {
  17024. // setup hierarchy
  17025. var hierarchy = [];
  17026. if ( root instanceof THREE.SkinnedMesh ) {
  17027. for( var b = 0; b < root.bones.length; b++ ) {
  17028. hierarchy.push( root.bones[ b ] );
  17029. }
  17030. } else {
  17031. parseRecurseHierarchy( root, hierarchy );
  17032. }
  17033. return hierarchy;
  17034. };
  17035. var parseRecurseHierarchy = function( root, hierarchy ) {
  17036. hierarchy.push( root );
  17037. for( var c = 0; c < root.children.length; c++ )
  17038. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17039. }
  17040. //--- init data ---
  17041. var initData = function( data ) {
  17042. if( data.initialized === true )
  17043. return;
  17044. // loop through all keys
  17045. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17046. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17047. // remove minus times
  17048. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17049. data.hierarchy[ h ].keys[ k ].time = 0;
  17050. // create quaternions
  17051. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17052. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17053. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17054. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17055. }
  17056. }
  17057. // prepare morph target keys
  17058. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17059. // get all used
  17060. var usedMorphTargets = {};
  17061. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17062. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17063. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17064. usedMorphTargets[ morphTargetName ] = -1;
  17065. }
  17066. }
  17067. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17068. // set all used on all frames
  17069. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17070. var influences = {};
  17071. for ( var morphTargetName in usedMorphTargets ) {
  17072. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17073. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17074. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17075. break;
  17076. }
  17077. }
  17078. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17079. influences[ morphTargetName ] = 0;
  17080. }
  17081. }
  17082. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17083. }
  17084. }
  17085. // remove all keys that are on the same time
  17086. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17087. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17088. data.hierarchy[ h ].keys.splice( k, 1 );
  17089. k --;
  17090. }
  17091. }
  17092. // set index
  17093. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17094. data.hierarchy[ h ].keys[ k ].index = k;
  17095. }
  17096. }
  17097. // JIT
  17098. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17099. data.JIT = {};
  17100. data.JIT.hierarchy = [];
  17101. for( var h = 0; h < data.hierarchy.length; h ++ )
  17102. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17103. // done
  17104. data.initialized = true;
  17105. };
  17106. // interpolation types
  17107. that.LINEAR = 0;
  17108. that.CATMULLROM = 1;
  17109. that.CATMULLROM_FORWARD = 2;
  17110. return that;
  17111. }());
  17112. /**
  17113. * @author mikael emtinger / http://gomo.se/
  17114. * @author mrdoob / http://mrdoob.com/
  17115. * @author alteredq / http://alteredqualia.com/
  17116. */
  17117. THREE.Animation = function ( root, name, interpolationType ) {
  17118. this.root = root;
  17119. this.data = THREE.AnimationHandler.get( name );
  17120. this.hierarchy = THREE.AnimationHandler.parse( root );
  17121. this.currentTime = 0;
  17122. this.timeScale = 1;
  17123. this.isPlaying = false;
  17124. this.isPaused = true;
  17125. this.loop = true;
  17126. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17127. this.points = [];
  17128. this.target = new THREE.Vector3();
  17129. };
  17130. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17131. if ( this.isPlaying === false ) {
  17132. this.isPlaying = true;
  17133. this.loop = loop !== undefined ? loop : true;
  17134. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17135. // reset key cache
  17136. var h, hl = this.hierarchy.length,
  17137. object;
  17138. for ( h = 0; h < hl; h ++ ) {
  17139. object = this.hierarchy[ h ];
  17140. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17141. object.useQuaternion = true;
  17142. }
  17143. object.matrixAutoUpdate = true;
  17144. if ( object.animationCache === undefined ) {
  17145. object.animationCache = {};
  17146. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17147. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17148. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17149. }
  17150. var prevKey = object.animationCache.prevKey;
  17151. var nextKey = object.animationCache.nextKey;
  17152. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17153. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17154. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17155. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17156. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17157. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17158. }
  17159. this.update( 0 );
  17160. }
  17161. this.isPaused = false;
  17162. THREE.AnimationHandler.addToUpdate( this );
  17163. };
  17164. THREE.Animation.prototype.pause = function() {
  17165. if ( this.isPaused === true ) {
  17166. THREE.AnimationHandler.addToUpdate( this );
  17167. } else {
  17168. THREE.AnimationHandler.removeFromUpdate( this );
  17169. }
  17170. this.isPaused = !this.isPaused;
  17171. };
  17172. THREE.Animation.prototype.stop = function() {
  17173. this.isPlaying = false;
  17174. this.isPaused = false;
  17175. THREE.AnimationHandler.removeFromUpdate( this );
  17176. };
  17177. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17178. // early out
  17179. if ( this.isPlaying === false ) return;
  17180. // vars
  17181. var types = [ "pos", "rot", "scl" ];
  17182. var type;
  17183. var scale;
  17184. var vector;
  17185. var prevXYZ, nextXYZ;
  17186. var prevKey, nextKey;
  17187. var object;
  17188. var animationCache;
  17189. var frame;
  17190. var JIThierarchy = this.data.JIT.hierarchy;
  17191. var currentTime, unloopedCurrentTime;
  17192. var currentPoint, forwardPoint, angle;
  17193. this.currentTime += deltaTimeMS * this.timeScale;
  17194. unloopedCurrentTime = this.currentTime;
  17195. currentTime = this.currentTime = this.currentTime % this.data.length;
  17196. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17197. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17198. object = this.hierarchy[ h ];
  17199. animationCache = object.animationCache;
  17200. // loop through pos/rot/scl
  17201. for ( var t = 0; t < 3; t ++ ) {
  17202. // get keys
  17203. type = types[ t ];
  17204. prevKey = animationCache.prevKey[ type ];
  17205. nextKey = animationCache.nextKey[ type ];
  17206. // switch keys?
  17207. if ( nextKey.time <= unloopedCurrentTime ) {
  17208. // did we loop?
  17209. if ( currentTime < unloopedCurrentTime ) {
  17210. if ( this.loop ) {
  17211. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17212. nextKey = this.getNextKeyWith( type, h, 1 );
  17213. while( nextKey.time < currentTime ) {
  17214. prevKey = nextKey;
  17215. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17216. }
  17217. } else {
  17218. this.stop();
  17219. return;
  17220. }
  17221. } else {
  17222. do {
  17223. prevKey = nextKey;
  17224. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17225. } while( nextKey.time < currentTime )
  17226. }
  17227. animationCache.prevKey[ type ] = prevKey;
  17228. animationCache.nextKey[ type ] = nextKey;
  17229. }
  17230. object.matrixAutoUpdate = true;
  17231. object.matrixWorldNeedsUpdate = true;
  17232. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17233. prevXYZ = prevKey[ type ];
  17234. nextXYZ = nextKey[ type ];
  17235. // check scale error
  17236. if ( scale < 0 || scale > 1 ) {
  17237. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17238. scale = scale < 0 ? 0 : 1;
  17239. }
  17240. // interpolate
  17241. if ( type === "pos" ) {
  17242. vector = object.position;
  17243. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17244. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17245. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17246. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17247. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17248. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17249. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17250. this.points[ 1 ] = prevXYZ;
  17251. this.points[ 2 ] = nextXYZ;
  17252. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17253. scale = scale * 0.33 + 0.33;
  17254. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17255. vector.x = currentPoint[ 0 ];
  17256. vector.y = currentPoint[ 1 ];
  17257. vector.z = currentPoint[ 2 ];
  17258. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17259. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17260. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17261. this.target.subSelf( vector );
  17262. this.target.y = 0;
  17263. this.target.normalize();
  17264. angle = Math.atan2( this.target.x, this.target.z );
  17265. object.rotation.set( 0, angle, 0 );
  17266. }
  17267. }
  17268. } else if ( type === "rot" ) {
  17269. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17270. } else if ( type === "scl" ) {
  17271. vector = object.scale;
  17272. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17273. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17274. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17275. }
  17276. }
  17277. }
  17278. };
  17279. // Catmull-Rom spline
  17280. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17281. var c = [], v3 = [],
  17282. point, intPoint, weight, w2, w3,
  17283. pa, pb, pc, pd;
  17284. point = ( points.length - 1 ) * scale;
  17285. intPoint = Math.floor( point );
  17286. weight = point - intPoint;
  17287. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17288. c[ 1 ] = intPoint;
  17289. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17290. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17291. pa = points[ c[ 0 ] ];
  17292. pb = points[ c[ 1 ] ];
  17293. pc = points[ c[ 2 ] ];
  17294. pd = points[ c[ 3 ] ];
  17295. w2 = weight * weight;
  17296. w3 = weight * w2;
  17297. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17298. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17299. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17300. return v3;
  17301. };
  17302. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17303. var v0 = ( p2 - p0 ) * 0.5,
  17304. v1 = ( p3 - p1 ) * 0.5;
  17305. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17306. };
  17307. // Get next key with
  17308. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17309. var keys = this.data.hierarchy[ h ].keys;
  17310. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17311. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17312. key = key < keys.length - 1 ? key : keys.length - 1;
  17313. } else {
  17314. key = key % keys.length;
  17315. }
  17316. for ( ; key < keys.length; key++ ) {
  17317. if ( keys[ key ][ type ] !== undefined ) {
  17318. return keys[ key ];
  17319. }
  17320. }
  17321. return this.data.hierarchy[ h ].keys[ 0 ];
  17322. };
  17323. // Get previous key with
  17324. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17325. var keys = this.data.hierarchy[ h ].keys;
  17326. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17327. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17328. key = key > 0 ? key : 0;
  17329. } else {
  17330. key = key >= 0 ? key : key + keys.length;
  17331. }
  17332. for ( ; key >= 0; key -- ) {
  17333. if ( keys[ key ][ type ] !== undefined ) {
  17334. return keys[ key ];
  17335. }
  17336. }
  17337. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17338. };
  17339. /**
  17340. * @author mikael emtinger / http://gomo.se/
  17341. * @author mrdoob / http://mrdoob.com/
  17342. * @author alteredq / http://alteredqualia.com/
  17343. * @author khang duong
  17344. * @author erik kitson
  17345. */
  17346. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17347. this.root = root;
  17348. this.data = THREE.AnimationHandler.get( data );
  17349. this.hierarchy = THREE.AnimationHandler.parse( root );
  17350. this.currentTime = 0;
  17351. this.timeScale = 0.001;
  17352. this.isPlaying = false;
  17353. this.isPaused = true;
  17354. this.loop = true;
  17355. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17356. // initialize to first keyframes
  17357. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17358. var keys = this.data.hierarchy[h].keys,
  17359. sids = this.data.hierarchy[h].sids,
  17360. obj = this.hierarchy[h];
  17361. if ( keys.length && sids ) {
  17362. for ( var s = 0; s < sids.length; s++ ) {
  17363. var sid = sids[ s ],
  17364. next = this.getNextKeyWith( sid, h, 0 );
  17365. if ( next ) {
  17366. next.apply( sid );
  17367. }
  17368. }
  17369. obj.matrixAutoUpdate = false;
  17370. this.data.hierarchy[h].node.updateMatrix();
  17371. obj.matrixWorldNeedsUpdate = true;
  17372. }
  17373. }
  17374. };
  17375. // Play
  17376. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17377. if( !this.isPlaying ) {
  17378. this.isPlaying = true;
  17379. this.loop = loop !== undefined ? loop : true;
  17380. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17381. this.startTimeMs = startTimeMS;
  17382. this.startTime = 10000000;
  17383. this.endTime = -this.startTime;
  17384. // reset key cache
  17385. var h, hl = this.hierarchy.length,
  17386. object,
  17387. node;
  17388. for ( h = 0; h < hl; h++ ) {
  17389. object = this.hierarchy[ h ];
  17390. node = this.data.hierarchy[ h ];
  17391. object.useQuaternion = true;
  17392. if ( node.animationCache === undefined ) {
  17393. node.animationCache = {};
  17394. node.animationCache.prevKey = null;
  17395. node.animationCache.nextKey = null;
  17396. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17397. }
  17398. var keys = this.data.hierarchy[h].keys;
  17399. if (keys.length) {
  17400. node.animationCache.prevKey = keys[ 0 ];
  17401. node.animationCache.nextKey = keys[ 1 ];
  17402. this.startTime = Math.min( keys[0].time, this.startTime );
  17403. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17404. }
  17405. }
  17406. this.update( 0 );
  17407. }
  17408. this.isPaused = false;
  17409. THREE.AnimationHandler.addToUpdate( this );
  17410. };
  17411. // Pause
  17412. THREE.KeyFrameAnimation.prototype.pause = function() {
  17413. if( this.isPaused ) {
  17414. THREE.AnimationHandler.addToUpdate( this );
  17415. } else {
  17416. THREE.AnimationHandler.removeFromUpdate( this );
  17417. }
  17418. this.isPaused = !this.isPaused;
  17419. };
  17420. // Stop
  17421. THREE.KeyFrameAnimation.prototype.stop = function() {
  17422. this.isPlaying = false;
  17423. this.isPaused = false;
  17424. THREE.AnimationHandler.removeFromUpdate( this );
  17425. // reset JIT matrix and remove cache
  17426. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17427. var obj = this.hierarchy[ h ];
  17428. var node = this.data.hierarchy[ h ];
  17429. if ( node.animationCache !== undefined ) {
  17430. var original = node.animationCache.originalMatrix;
  17431. if( obj instanceof THREE.Bone ) {
  17432. original.copy( obj.skinMatrix );
  17433. obj.skinMatrix = original;
  17434. } else {
  17435. original.copy( obj.matrix );
  17436. obj.matrix = original;
  17437. }
  17438. delete node.animationCache;
  17439. }
  17440. }
  17441. };
  17442. // Update
  17443. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17444. // early out
  17445. if( !this.isPlaying ) return;
  17446. // vars
  17447. var prevKey, nextKey;
  17448. var object;
  17449. var node;
  17450. var frame;
  17451. var JIThierarchy = this.data.JIT.hierarchy;
  17452. var currentTime, unloopedCurrentTime;
  17453. var looped;
  17454. // update
  17455. this.currentTime += deltaTimeMS * this.timeScale;
  17456. unloopedCurrentTime = this.currentTime;
  17457. currentTime = this.currentTime = this.currentTime % this.data.length;
  17458. // if looped around, the current time should be based on the startTime
  17459. if ( currentTime < this.startTimeMs ) {
  17460. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17461. }
  17462. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17463. looped = currentTime < unloopedCurrentTime;
  17464. if ( looped && !this.loop ) {
  17465. // Set the animation to the last keyframes and stop
  17466. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17467. var keys = this.data.hierarchy[h].keys,
  17468. sids = this.data.hierarchy[h].sids,
  17469. end = keys.length-1,
  17470. obj = this.hierarchy[h];
  17471. if ( keys.length ) {
  17472. for ( var s = 0; s < sids.length; s++ ) {
  17473. var sid = sids[ s ],
  17474. prev = this.getPrevKeyWith( sid, h, end );
  17475. if ( prev ) {
  17476. prev.apply( sid );
  17477. }
  17478. }
  17479. this.data.hierarchy[h].node.updateMatrix();
  17480. obj.matrixWorldNeedsUpdate = true;
  17481. }
  17482. }
  17483. this.stop();
  17484. return;
  17485. }
  17486. // check pre-infinity
  17487. if ( currentTime < this.startTime ) {
  17488. return;
  17489. }
  17490. // update
  17491. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17492. object = this.hierarchy[ h ];
  17493. node = this.data.hierarchy[ h ];
  17494. var keys = node.keys,
  17495. animationCache = node.animationCache;
  17496. // use JIT?
  17497. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17498. if( object instanceof THREE.Bone ) {
  17499. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17500. object.matrixWorldNeedsUpdate = false;
  17501. } else {
  17502. object.matrix = JIThierarchy[ h ][ frame ];
  17503. object.matrixWorldNeedsUpdate = true;
  17504. }
  17505. // use interpolation
  17506. } else if ( keys.length ) {
  17507. // make sure so original matrix and not JIT matrix is set
  17508. if ( this.JITCompile && animationCache ) {
  17509. if( object instanceof THREE.Bone ) {
  17510. object.skinMatrix = animationCache.originalMatrix;
  17511. } else {
  17512. object.matrix = animationCache.originalMatrix;
  17513. }
  17514. }
  17515. prevKey = animationCache.prevKey;
  17516. nextKey = animationCache.nextKey;
  17517. if ( prevKey && nextKey ) {
  17518. // switch keys?
  17519. if ( nextKey.time <= unloopedCurrentTime ) {
  17520. // did we loop?
  17521. if ( looped && this.loop ) {
  17522. prevKey = keys[ 0 ];
  17523. nextKey = keys[ 1 ];
  17524. while ( nextKey.time < currentTime ) {
  17525. prevKey = nextKey;
  17526. nextKey = keys[ prevKey.index + 1 ];
  17527. }
  17528. } else if ( !looped ) {
  17529. var lastIndex = keys.length - 1;
  17530. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17531. prevKey = nextKey;
  17532. nextKey = keys[ prevKey.index + 1 ];
  17533. }
  17534. }
  17535. animationCache.prevKey = prevKey;
  17536. animationCache.nextKey = nextKey;
  17537. }
  17538. if(nextKey.time >= currentTime)
  17539. prevKey.interpolate( nextKey, currentTime );
  17540. else
  17541. prevKey.interpolate( nextKey, nextKey.time);
  17542. }
  17543. this.data.hierarchy[h].node.updateMatrix();
  17544. object.matrixWorldNeedsUpdate = true;
  17545. }
  17546. }
  17547. // update JIT?
  17548. if ( this.JITCompile ) {
  17549. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17550. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17551. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17552. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17553. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17554. } else {
  17555. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17556. }
  17557. }
  17558. }
  17559. }
  17560. };
  17561. // Get next key with
  17562. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17563. var keys = this.data.hierarchy[ h ].keys;
  17564. key = key % keys.length;
  17565. for ( ; key < keys.length; key++ ) {
  17566. if ( keys[ key ].hasTarget( sid ) ) {
  17567. return keys[ key ];
  17568. }
  17569. }
  17570. return keys[ 0 ];
  17571. };
  17572. // Get previous key with
  17573. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17574. var keys = this.data.hierarchy[ h ].keys;
  17575. key = key >= 0 ? key : key + keys.length;
  17576. for ( ; key >= 0; key-- ) {
  17577. if ( keys[ key ].hasTarget( sid ) ) {
  17578. return keys[ key ];
  17579. }
  17580. }
  17581. return keys[ keys.length - 1 ];
  17582. };
  17583. /**
  17584. * Camera for rendering cube maps
  17585. * - renders scene into axis-aligned cube
  17586. *
  17587. * @author alteredq / http://alteredqualia.com/
  17588. */
  17589. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17590. THREE.Object3D.call( this );
  17591. var fov = 90, aspect = 1;
  17592. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17593. cameraPX.up.set( 0, -1, 0 );
  17594. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17595. this.add( cameraPX );
  17596. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17597. cameraNX.up.set( 0, -1, 0 );
  17598. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17599. this.add( cameraNX );
  17600. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17601. cameraPY.up.set( 0, 0, 1 );
  17602. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17603. this.add( cameraPY );
  17604. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17605. cameraNY.up.set( 0, 0, -1 );
  17606. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17607. this.add( cameraNY );
  17608. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17609. cameraPZ.up.set( 0, -1, 0 );
  17610. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  17611. this.add( cameraPZ );
  17612. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17613. cameraNZ.up.set( 0, -1, 0 );
  17614. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  17615. this.add( cameraNZ );
  17616. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  17617. this.updateCubeMap = function ( renderer, scene ) {
  17618. var renderTarget = this.renderTarget;
  17619. var generateMipmaps = renderTarget.generateMipmaps;
  17620. renderTarget.generateMipmaps = false;
  17621. renderTarget.activeCubeFace = 0;
  17622. renderer.render( scene, cameraPX, renderTarget );
  17623. renderTarget.activeCubeFace = 1;
  17624. renderer.render( scene, cameraNX, renderTarget );
  17625. renderTarget.activeCubeFace = 2;
  17626. renderer.render( scene, cameraPY, renderTarget );
  17627. renderTarget.activeCubeFace = 3;
  17628. renderer.render( scene, cameraNY, renderTarget );
  17629. renderTarget.activeCubeFace = 4;
  17630. renderer.render( scene, cameraPZ, renderTarget );
  17631. renderTarget.generateMipmaps = generateMipmaps;
  17632. renderTarget.activeCubeFace = 5;
  17633. renderer.render( scene, cameraNZ, renderTarget );
  17634. };
  17635. };
  17636. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  17637. /*
  17638. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  17639. *
  17640. * A general perpose camera, for setting FOV, Lens Focal Length,
  17641. * and switching between perspective and orthographic views easily.
  17642. * Use this only if you do not wish to manage
  17643. * both a Orthographic and Perspective Camera
  17644. *
  17645. */
  17646. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  17647. THREE.Camera.call( this );
  17648. this.fov = fov;
  17649. this.left = -width / 2;
  17650. this.right = width / 2
  17651. this.top = height / 2;
  17652. this.bottom = -height / 2;
  17653. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  17654. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  17655. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  17656. this.zoom = 1;
  17657. this.toPerspective();
  17658. var aspect = width/height;
  17659. };
  17660. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  17661. THREE.CombinedCamera.prototype.toPerspective = function () {
  17662. // Switches to the Perspective Camera
  17663. this.near = this.cameraP.near;
  17664. this.far = this.cameraP.far;
  17665. this.cameraP.fov = this.fov / this.zoom ;
  17666. this.cameraP.updateProjectionMatrix();
  17667. this.projectionMatrix = this.cameraP.projectionMatrix;
  17668. this.inPerspectiveMode = true;
  17669. this.inOrthographicMode = false;
  17670. };
  17671. THREE.CombinedCamera.prototype.toOrthographic = function () {
  17672. // Switches to the Orthographic camera estimating viewport from Perspective
  17673. var fov = this.fov;
  17674. var aspect = this.cameraP.aspect;
  17675. var near = this.cameraP.near;
  17676. var far = this.cameraP.far;
  17677. // The size that we set is the mid plane of the viewing frustum
  17678. var hyperfocus = ( near + far ) / 2;
  17679. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  17680. var planeHeight = 2 * halfHeight;
  17681. var planeWidth = planeHeight * aspect;
  17682. var halfWidth = planeWidth / 2;
  17683. halfHeight /= this.zoom;
  17684. halfWidth /= this.zoom;
  17685. this.cameraO.left = -halfWidth;
  17686. this.cameraO.right = halfWidth;
  17687. this.cameraO.top = halfHeight;
  17688. this.cameraO.bottom = -halfHeight;
  17689. // this.cameraO.left = -farHalfWidth;
  17690. // this.cameraO.right = farHalfWidth;
  17691. // this.cameraO.top = farHalfHeight;
  17692. // this.cameraO.bottom = -farHalfHeight;
  17693. // this.cameraO.left = this.left / this.zoom;
  17694. // this.cameraO.right = this.right / this.zoom;
  17695. // this.cameraO.top = this.top / this.zoom;
  17696. // this.cameraO.bottom = this.bottom / this.zoom;
  17697. this.cameraO.updateProjectionMatrix();
  17698. this.near = this.cameraO.near;
  17699. this.far = this.cameraO.far;
  17700. this.projectionMatrix = this.cameraO.projectionMatrix;
  17701. this.inPerspectiveMode = false;
  17702. this.inOrthographicMode = true;
  17703. };
  17704. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  17705. this.cameraP.aspect = width / height;
  17706. this.left = -width / 2;
  17707. this.right = width / 2
  17708. this.top = height / 2;
  17709. this.bottom = -height / 2;
  17710. };
  17711. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  17712. this.fov = fov;
  17713. if ( this.inPerspectiveMode ) {
  17714. this.toPerspective();
  17715. } else {
  17716. this.toOrthographic();
  17717. }
  17718. };
  17719. // For mantaining similar API with PerspectiveCamera
  17720. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  17721. if ( this.inPerspectiveMode ) {
  17722. this.toPerspective();
  17723. } else {
  17724. this.toPerspective();
  17725. this.toOrthographic();
  17726. }
  17727. };
  17728. /*
  17729. * Uses Focal Length (in mm) to estimate and set FOV
  17730. * 35mm (fullframe) camera is used if frame size is not specified;
  17731. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  17732. */
  17733. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  17734. if ( frameHeight === undefined ) frameHeight = 24;
  17735. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  17736. this.setFov( fov );
  17737. return fov;
  17738. };
  17739. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  17740. this.zoom = zoom;
  17741. if ( this.inPerspectiveMode ) {
  17742. this.toPerspective();
  17743. } else {
  17744. this.toOrthographic();
  17745. }
  17746. };
  17747. THREE.CombinedCamera.prototype.toFrontView = function() {
  17748. this.rotation.x = 0;
  17749. this.rotation.y = 0;
  17750. this.rotation.z = 0;
  17751. // should we be modifing the matrix instead?
  17752. this.rotationAutoUpdate = false;
  17753. };
  17754. THREE.CombinedCamera.prototype.toBackView = function() {
  17755. this.rotation.x = 0;
  17756. this.rotation.y = Math.PI;
  17757. this.rotation.z = 0;
  17758. this.rotationAutoUpdate = false;
  17759. };
  17760. THREE.CombinedCamera.prototype.toLeftView = function() {
  17761. this.rotation.x = 0;
  17762. this.rotation.y = - Math.PI / 2;
  17763. this.rotation.z = 0;
  17764. this.rotationAutoUpdate = false;
  17765. };
  17766. THREE.CombinedCamera.prototype.toRightView = function() {
  17767. this.rotation.x = 0;
  17768. this.rotation.y = Math.PI / 2;
  17769. this.rotation.z = 0;
  17770. this.rotationAutoUpdate = false;
  17771. };
  17772. THREE.CombinedCamera.prototype.toTopView = function() {
  17773. this.rotation.x = - Math.PI / 2;
  17774. this.rotation.y = 0;
  17775. this.rotation.z = 0;
  17776. this.rotationAutoUpdate = false;
  17777. };
  17778. THREE.CombinedCamera.prototype.toBottomView = function() {
  17779. this.rotation.x = Math.PI / 2;
  17780. this.rotation.y = 0;
  17781. this.rotation.z = 0;
  17782. this.rotationAutoUpdate = false;
  17783. };
  17784. /**
  17785. * @author alteredq / http://alteredqualia.com/
  17786. *
  17787. * - 3d asterisk shape (for line pieces THREE.Line)
  17788. */
  17789. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  17790. THREE.Geometry.call( this );
  17791. var sd = innerRadius;
  17792. var ed = outerRadius;
  17793. var sd2 = 0.707 * sd;
  17794. var ed2 = 0.707 * ed;
  17795. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  17796. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  17797. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  17798. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  17799. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  17800. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  17801. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  17802. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  17803. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  17804. ];
  17805. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  17806. var x = rays[ i ][ 0 ];
  17807. var y = rays[ i ][ 1 ];
  17808. var z = rays[ i ][ 2 ];
  17809. this.vertices.push( new THREE.Vector3( x, y, z ) );
  17810. }
  17811. };
  17812. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  17813. * @author hughes
  17814. */
  17815. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17816. THREE.Geometry.call( this );
  17817. radius = radius || 50;
  17818. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17819. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17820. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17821. var i, uvs = [],
  17822. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17823. this.vertices.push(center);
  17824. uvs.push( centerUV );
  17825. for ( i = 0; i <= segments; i ++ ) {
  17826. var vertex = new THREE.Vector3();
  17827. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17828. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17829. this.vertices.push( vertex );
  17830. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17831. }
  17832. var n = new THREE.Vector3( 0, 0, -1 );
  17833. for ( i = 1; i <= segments; i ++ ) {
  17834. var v1 = i;
  17835. var v2 = i + 1 ;
  17836. var v3 = 0;
  17837. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17838. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17839. }
  17840. this.computeCentroids();
  17841. this.computeFaceNormals();
  17842. this.boundingSphere = { radius: radius };
  17843. };
  17844. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17845. /**
  17846. * @author mrdoob / http://mrdoob.com/
  17847. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17848. */
  17849. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17850. THREE.Geometry.call( this );
  17851. var scope = this;
  17852. this.width = width;
  17853. this.height = height;
  17854. this.depth = depth;
  17855. this.widthSegments = widthSegments || 1;
  17856. this.heightSegments = heightSegments || 1;
  17857. this.depthSegments = depthSegments || 1;
  17858. var width_half = this.width / 2;
  17859. var height_half = this.height / 2;
  17860. var depth_half = this.depth / 2;
  17861. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  17862. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  17863. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  17864. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  17865. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  17866. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  17867. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  17868. var w, ix, iy,
  17869. gridX = scope.widthSegments,
  17870. gridY = scope.heightSegments,
  17871. width_half = width / 2,
  17872. height_half = height / 2,
  17873. offset = scope.vertices.length;
  17874. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17875. w = 'z';
  17876. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17877. w = 'y';
  17878. gridY = scope.depthSegments;
  17879. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17880. w = 'x';
  17881. gridX = scope.depthSegments;
  17882. }
  17883. var gridX1 = gridX + 1,
  17884. gridY1 = gridY + 1,
  17885. segment_width = width / gridX,
  17886. segment_height = height / gridY,
  17887. normal = new THREE.Vector3();
  17888. normal[ w ] = depth > 0 ? 1 : - 1;
  17889. for ( iy = 0; iy < gridY1; iy ++ ) {
  17890. for ( ix = 0; ix < gridX1; ix ++ ) {
  17891. var vector = new THREE.Vector3();
  17892. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  17893. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  17894. vector[ w ] = depth;
  17895. scope.vertices.push( vector );
  17896. }
  17897. }
  17898. for ( iy = 0; iy < gridY; iy++ ) {
  17899. for ( ix = 0; ix < gridX; ix++ ) {
  17900. var a = ix + gridX1 * iy;
  17901. var b = ix + gridX1 * ( iy + 1 );
  17902. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  17903. var d = ( ix + 1 ) + gridX1 * iy;
  17904. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  17905. face.normal.copy( normal );
  17906. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  17907. face.materialIndex = materialIndex;
  17908. scope.faces.push( face );
  17909. scope.faceVertexUvs[ 0 ].push( [
  17910. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  17911. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  17912. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  17913. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  17914. ] );
  17915. }
  17916. }
  17917. }
  17918. this.computeCentroids();
  17919. this.mergeVertices();
  17920. };
  17921. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17922. /**
  17923. * @author mrdoob / http://mrdoob.com/
  17924. */
  17925. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  17926. THREE.Geometry.call( this );
  17927. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17928. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17929. height = height !== undefined ? height : 100;
  17930. var heightHalf = height / 2;
  17931. var segmentsX = radiusSegments || 8;
  17932. var segmentsY = heightSegments || 1;
  17933. var x, y, vertices = [], uvs = [];
  17934. for ( y = 0; y <= segmentsY; y ++ ) {
  17935. var verticesRow = [];
  17936. var uvsRow = [];
  17937. var v = y / segmentsY;
  17938. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17939. for ( x = 0; x <= segmentsX; x ++ ) {
  17940. var u = x / segmentsX;
  17941. var vertex = new THREE.Vector3();
  17942. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  17943. vertex.y = - v * height + heightHalf;
  17944. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  17945. this.vertices.push( vertex );
  17946. verticesRow.push( this.vertices.length - 1 );
  17947. uvsRow.push( new THREE.UV( u, 1 - v ) );
  17948. }
  17949. vertices.push( verticesRow );
  17950. uvs.push( uvsRow );
  17951. }
  17952. var tanTheta = ( radiusBottom - radiusTop ) / height;
  17953. var na, nb;
  17954. for ( x = 0; x < segmentsX; x ++ ) {
  17955. if ( radiusTop !== 0 ) {
  17956. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  17957. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  17958. } else {
  17959. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  17960. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  17961. }
  17962. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  17963. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  17964. for ( y = 0; y < segmentsY; y ++ ) {
  17965. var v1 = vertices[ y ][ x ];
  17966. var v2 = vertices[ y + 1 ][ x ];
  17967. var v3 = vertices[ y + 1 ][ x + 1 ];
  17968. var v4 = vertices[ y ][ x + 1 ];
  17969. var n1 = na.clone();
  17970. var n2 = na.clone();
  17971. var n3 = nb.clone();
  17972. var n4 = nb.clone();
  17973. var uv1 = uvs[ y ][ x ].clone();
  17974. var uv2 = uvs[ y + 1 ][ x ].clone();
  17975. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  17976. var uv4 = uvs[ y ][ x + 1 ].clone();
  17977. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  17978. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  17979. }
  17980. }
  17981. // top cap
  17982. if ( !openEnded && radiusTop > 0 ) {
  17983. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  17984. for ( x = 0; x < segmentsX; x ++ ) {
  17985. var v1 = vertices[ 0 ][ x ];
  17986. var v2 = vertices[ 0 ][ x + 1 ];
  17987. var v3 = this.vertices.length - 1;
  17988. var n1 = new THREE.Vector3( 0, 1, 0 );
  17989. var n2 = new THREE.Vector3( 0, 1, 0 );
  17990. var n3 = new THREE.Vector3( 0, 1, 0 );
  17991. var uv1 = uvs[ 0 ][ x ].clone();
  17992. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  17993. var uv3 = new THREE.UV( uv2.u, 0 );
  17994. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17995. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17996. }
  17997. }
  17998. // bottom cap
  17999. if ( !openEnded && radiusBottom > 0 ) {
  18000. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18001. for ( x = 0; x < segmentsX; x ++ ) {
  18002. var v1 = vertices[ y ][ x + 1 ];
  18003. var v2 = vertices[ y ][ x ];
  18004. var v3 = this.vertices.length - 1;
  18005. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18006. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18007. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18008. var uv1 = uvs[ y ][ x + 1 ].clone();
  18009. var uv2 = uvs[ y ][ x ].clone();
  18010. var uv3 = new THREE.UV( uv2.u, 1 );
  18011. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18012. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18013. }
  18014. }
  18015. this.computeCentroids();
  18016. this.computeFaceNormals();
  18017. }
  18018. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18019. /**
  18020. * @author zz85 / http://www.lab4games.net/zz85/blog
  18021. *
  18022. * Creates extruded geometry from a path shape.
  18023. *
  18024. * parameters = {
  18025. *
  18026. * size: <float>, // size of the text
  18027. * height: <float>, // thickness to extrude text
  18028. * curveSegments: <int>, // number of points on the curves
  18029. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18030. * amount: <int>, // Amount
  18031. *
  18032. * bevelEnabled: <bool>, // turn on bevel
  18033. * bevelThickness: <float>, // how deep into text bevel goes
  18034. * bevelSize: <float>, // how far from text outline is bevel
  18035. * bevelSegments: <int>, // number of bevel layers
  18036. *
  18037. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18038. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18039. *
  18040. * material: <int> // material index for front and back faces
  18041. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18042. * uvGenerator: <Object> // object that provides UV generator functions
  18043. *
  18044. * }
  18045. **/
  18046. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18047. if ( typeof( shapes ) === "undefined" ) {
  18048. shapes = [];
  18049. return;
  18050. }
  18051. THREE.Geometry.call( this );
  18052. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18053. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18054. this.addShapeList( shapes, options );
  18055. this.computeCentroids();
  18056. this.computeFaceNormals();
  18057. // can't really use automatic vertex normals
  18058. // as then front and back sides get smoothed too
  18059. // should do separate smoothing just for sides
  18060. //this.computeVertexNormals();
  18061. //console.log( "took", ( Date.now() - startTime ) );
  18062. };
  18063. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18064. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18065. var sl = shapes.length;
  18066. for ( var s = 0; s < sl; s ++ ) {
  18067. var shape = shapes[ s ];
  18068. this.addShape( shape, options );
  18069. }
  18070. };
  18071. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18072. var amount = options.amount !== undefined ? options.amount : 100;
  18073. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18074. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18075. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18076. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18077. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18078. var steps = options.steps !== undefined ? options.steps : 1;
  18079. var extrudePath = options.extrudePath;
  18080. var extrudePts, extrudeByPath = false;
  18081. var material = options.material;
  18082. var extrudeMaterial = options.extrudeMaterial;
  18083. // Use default WorldUVGenerator if no UV generators are specified.
  18084. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18085. var shapebb = this.shapebb;
  18086. //shapebb = shape.getBoundingBox();
  18087. var splineTube, binormal, normal, position2;
  18088. if ( extrudePath ) {
  18089. extrudePts = extrudePath.getSpacedPoints( steps );
  18090. extrudeByPath = true;
  18091. bevelEnabled = false; // bevels not supported for path extrusion
  18092. // SETUP TNB variables
  18093. // Reuse TNB from TubeGeomtry for now.
  18094. // TODO1 - have a .isClosed in spline?
  18095. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18096. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18097. binormal = new THREE.Vector3();
  18098. normal = new THREE.Vector3();
  18099. position2 = new THREE.Vector3();
  18100. }
  18101. // Safeguards if bevels are not enabled
  18102. if ( ! bevelEnabled ) {
  18103. bevelSegments = 0;
  18104. bevelThickness = 0;
  18105. bevelSize = 0;
  18106. }
  18107. // Variables initalization
  18108. var ahole, h, hl; // looping of holes
  18109. var scope = this;
  18110. var bevelPoints = [];
  18111. var shapesOffset = this.vertices.length;
  18112. var shapePoints = shape.extractPoints( curveSegments );
  18113. var vertices = shapePoints.shape;
  18114. var holes = shapePoints.holes;
  18115. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18116. if ( reverse ) {
  18117. vertices = vertices.reverse();
  18118. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18119. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18120. ahole = holes[ h ];
  18121. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18122. holes[ h ] = ahole.reverse();
  18123. }
  18124. }
  18125. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18126. }
  18127. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18128. /* Vertices */
  18129. var contour = vertices; // vertices has all points but contour has only points of circumference
  18130. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18131. ahole = holes[ h ];
  18132. vertices = vertices.concat( ahole );
  18133. }
  18134. function scalePt2 ( pt, vec, size ) {
  18135. if ( !vec ) console.log( "die" );
  18136. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18137. }
  18138. var b, bs, t, z,
  18139. vert, vlen = vertices.length,
  18140. face, flen = faces.length,
  18141. cont, clen = contour.length;
  18142. // Find directions for point movement
  18143. var RAD_TO_DEGREES = 180 / Math.PI;
  18144. function getBevelVec( pt_i, pt_j, pt_k ) {
  18145. // Algorithm 2
  18146. return getBevelVec2( pt_i, pt_j, pt_k );
  18147. }
  18148. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18149. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18150. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18151. if ( anglea > angleb ) {
  18152. angleb += Math.PI * 2;
  18153. }
  18154. var anglec = ( anglea + angleb ) / 2;
  18155. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18156. var x = - Math.cos( anglec );
  18157. var y = - Math.sin( anglec );
  18158. var vec = new THREE.Vector2( x, y ); //.normalize();
  18159. return vec;
  18160. }
  18161. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18162. var a = THREE.ExtrudeGeometry.__v1,
  18163. b = THREE.ExtrudeGeometry.__v2,
  18164. v_hat = THREE.ExtrudeGeometry.__v3,
  18165. w_hat = THREE.ExtrudeGeometry.__v4,
  18166. p = THREE.ExtrudeGeometry.__v5,
  18167. q = THREE.ExtrudeGeometry.__v6,
  18168. v, w,
  18169. v_dot_w_hat, q_sub_p_dot_w_hat,
  18170. s, intersection;
  18171. // good reading for line-line intersection
  18172. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18173. // define a as vector j->i
  18174. // define b as vectot k->i
  18175. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18176. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18177. // get unit vectors
  18178. v = a.normalize();
  18179. w = b.normalize();
  18180. // normals from pt i
  18181. v_hat.set( -v.y, v.x );
  18182. w_hat.set( w.y, -w.x );
  18183. // pts from i
  18184. p.copy( pt_i ).addSelf( v_hat );
  18185. q.copy( pt_i ).addSelf( w_hat );
  18186. if ( p.equals( q ) ) {
  18187. //console.log("Warning: lines are straight");
  18188. return w_hat.clone();
  18189. }
  18190. // Points from j, k. helps prevents points cross overover most of the time
  18191. p.copy( pt_j ).addSelf( v_hat );
  18192. q.copy( pt_k ).addSelf( w_hat );
  18193. v_dot_w_hat = v.dot( w_hat );
  18194. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18195. // We should not reach these conditions
  18196. if ( v_dot_w_hat === 0 ) {
  18197. console.log( "Either infinite or no solutions!" );
  18198. if ( q_sub_p_dot_w_hat === 0 ) {
  18199. console.log( "Its finite solutions." );
  18200. } else {
  18201. console.log( "Too bad, no solutions." );
  18202. }
  18203. }
  18204. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18205. if ( s < 0 ) {
  18206. // in case of emergecy, revert to algorithm 1.
  18207. return getBevelVec1( pt_i, pt_j, pt_k );
  18208. }
  18209. intersection = v.multiplyScalar( s ).addSelf( p );
  18210. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18211. }
  18212. var contourMovements = [];
  18213. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18214. if ( j === il ) j = 0;
  18215. if ( k === il ) k = 0;
  18216. // (j)---(i)---(k)
  18217. // console.log('i,j,k', i, j , k)
  18218. var pt_i = contour[ i ];
  18219. var pt_j = contour[ j ];
  18220. var pt_k = contour[ k ];
  18221. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18222. }
  18223. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18224. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18225. ahole = holes[ h ];
  18226. oneHoleMovements = [];
  18227. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18228. if ( j === il ) j = 0;
  18229. if ( k === il ) k = 0;
  18230. // (j)---(i)---(k)
  18231. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18232. }
  18233. holesMovements.push( oneHoleMovements );
  18234. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18235. }
  18236. // Loop bevelSegments, 1 for the front, 1 for the back
  18237. for ( b = 0; b < bevelSegments; b ++ ) {
  18238. //for ( b = bevelSegments; b > 0; b -- ) {
  18239. t = b / bevelSegments;
  18240. z = bevelThickness * ( 1 - t );
  18241. //z = bevelThickness * t;
  18242. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18243. //bs = bevelSize * t ; // linear
  18244. // contract shape
  18245. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18246. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18247. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18248. v( vert.x, vert.y, - z );
  18249. }
  18250. // expand holes
  18251. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18252. ahole = holes[ h ];
  18253. oneHoleMovements = holesMovements[ h ];
  18254. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18255. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18256. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18257. v( vert.x, vert.y, -z );
  18258. }
  18259. }
  18260. }
  18261. bs = bevelSize;
  18262. // Back facing vertices
  18263. for ( i = 0; i < vlen; i ++ ) {
  18264. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18265. if ( !extrudeByPath ) {
  18266. v( vert.x, vert.y, 0 );
  18267. } else {
  18268. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18269. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18270. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18271. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18272. v( position2.x, position2.y, position2.z );
  18273. }
  18274. }
  18275. // Add stepped vertices...
  18276. // Including front facing vertices
  18277. var s;
  18278. for ( s = 1; s <= steps; s ++ ) {
  18279. for ( i = 0; i < vlen; i ++ ) {
  18280. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18281. if ( !extrudeByPath ) {
  18282. v( vert.x, vert.y, amount / steps * s );
  18283. } else {
  18284. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18285. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18286. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18287. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18288. v( position2.x, position2.y, position2.z );
  18289. }
  18290. }
  18291. }
  18292. // Add bevel segments planes
  18293. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18294. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18295. t = b / bevelSegments;
  18296. z = bevelThickness * ( 1 - t );
  18297. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18298. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18299. // contract shape
  18300. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18301. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18302. v( vert.x, vert.y, amount + z );
  18303. }
  18304. // expand holes
  18305. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18306. ahole = holes[ h ];
  18307. oneHoleMovements = holesMovements[ h ];
  18308. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18309. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18310. if ( !extrudeByPath ) {
  18311. v( vert.x, vert.y, amount + z );
  18312. } else {
  18313. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18314. }
  18315. }
  18316. }
  18317. }
  18318. /* Faces */
  18319. // Top and bottom faces
  18320. buildLidFaces();
  18321. // Sides faces
  18322. buildSideFaces();
  18323. ///// Internal functions
  18324. function buildLidFaces() {
  18325. if ( bevelEnabled ) {
  18326. var layer = 0 ; // steps + 1
  18327. var offset = vlen * layer;
  18328. // Bottom faces
  18329. for ( i = 0; i < flen; i ++ ) {
  18330. face = faces[ i ];
  18331. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18332. }
  18333. layer = steps + bevelSegments * 2;
  18334. offset = vlen * layer;
  18335. // Top faces
  18336. for ( i = 0; i < flen; i ++ ) {
  18337. face = faces[ i ];
  18338. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18339. }
  18340. } else {
  18341. // Bottom faces
  18342. for ( i = 0; i < flen; i++ ) {
  18343. face = faces[ i ];
  18344. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18345. }
  18346. // Top faces
  18347. for ( i = 0; i < flen; i ++ ) {
  18348. face = faces[ i ];
  18349. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18350. }
  18351. }
  18352. }
  18353. // Create faces for the z-sides of the shape
  18354. function buildSideFaces() {
  18355. var layeroffset = 0;
  18356. sidewalls( contour, layeroffset );
  18357. layeroffset += contour.length;
  18358. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18359. ahole = holes[ h ];
  18360. sidewalls( ahole, layeroffset );
  18361. //, true
  18362. layeroffset += ahole.length;
  18363. }
  18364. }
  18365. function sidewalls( contour, layeroffset ) {
  18366. var j, k;
  18367. i = contour.length;
  18368. while ( --i >= 0 ) {
  18369. j = i;
  18370. k = i - 1;
  18371. if ( k < 0 ) k = contour.length - 1;
  18372. //console.log('b', i,j, i-1, k,vertices.length);
  18373. var s = 0, sl = steps + bevelSegments * 2;
  18374. for ( s = 0; s < sl; s ++ ) {
  18375. var slen1 = vlen * s;
  18376. var slen2 = vlen * ( s + 1 );
  18377. var a = layeroffset + j + slen1,
  18378. b = layeroffset + k + slen1,
  18379. c = layeroffset + k + slen2,
  18380. d = layeroffset + j + slen2;
  18381. f4( a, b, c, d, contour, s, sl, j, k );
  18382. }
  18383. }
  18384. }
  18385. function v( x, y, z ) {
  18386. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18387. }
  18388. function f3( a, b, c, isBottom ) {
  18389. a += shapesOffset;
  18390. b += shapesOffset;
  18391. c += shapesOffset;
  18392. // normal, color, material
  18393. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18394. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18395. scope.faceVertexUvs[ 0 ].push( uvs );
  18396. }
  18397. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18398. a += shapesOffset;
  18399. b += shapesOffset;
  18400. c += shapesOffset;
  18401. d += shapesOffset;
  18402. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18403. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18404. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18405. scope.faceVertexUvs[ 0 ].push( uvs );
  18406. }
  18407. };
  18408. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18409. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18410. var ax = geometry.vertices[ indexA ].x,
  18411. ay = geometry.vertices[ indexA ].y,
  18412. bx = geometry.vertices[ indexB ].x,
  18413. by = geometry.vertices[ indexB ].y,
  18414. cx = geometry.vertices[ indexC ].x,
  18415. cy = geometry.vertices[ indexC ].y;
  18416. return [
  18417. new THREE.UV( ax, ay ),
  18418. new THREE.UV( bx, by ),
  18419. new THREE.UV( cx, cy )
  18420. ];
  18421. },
  18422. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18423. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18424. },
  18425. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18426. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18427. contourIndex1, contourIndex2 ) {
  18428. var ax = geometry.vertices[ indexA ].x,
  18429. ay = geometry.vertices[ indexA ].y,
  18430. az = geometry.vertices[ indexA ].z,
  18431. bx = geometry.vertices[ indexB ].x,
  18432. by = geometry.vertices[ indexB ].y,
  18433. bz = geometry.vertices[ indexB ].z,
  18434. cx = geometry.vertices[ indexC ].x,
  18435. cy = geometry.vertices[ indexC ].y,
  18436. cz = geometry.vertices[ indexC ].z,
  18437. dx = geometry.vertices[ indexD ].x,
  18438. dy = geometry.vertices[ indexD ].y,
  18439. dz = geometry.vertices[ indexD ].z;
  18440. if ( Math.abs( ay - by ) < 0.01 ) {
  18441. return [
  18442. new THREE.UV( ax, 1 - az ),
  18443. new THREE.UV( bx, 1 - bz ),
  18444. new THREE.UV( cx, 1 - cz ),
  18445. new THREE.UV( dx, 1 - dz )
  18446. ];
  18447. } else {
  18448. return [
  18449. new THREE.UV( ay, 1 - az ),
  18450. new THREE.UV( by, 1 - bz ),
  18451. new THREE.UV( cy, 1 - cz ),
  18452. new THREE.UV( dy, 1 - dz )
  18453. ];
  18454. }
  18455. }
  18456. };
  18457. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18458. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18459. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18460. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18461. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18462. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18463. /**
  18464. * @author jonobr1 / http://jonobr1.com
  18465. *
  18466. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18467. * ExtrudeGeometry.
  18468. *
  18469. * parameters = {
  18470. *
  18471. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18472. *
  18473. * material: <int> // material index for front and back faces
  18474. * uvGenerator: <Object> // object that provides UV generator functions
  18475. *
  18476. * }
  18477. **/
  18478. THREE.ShapeGeometry = function ( shapes, options ) {
  18479. THREE.Geometry.call( this );
  18480. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18481. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18482. this.addShapeList( shapes, options );
  18483. this.computeCentroids();
  18484. this.computeFaceNormals();
  18485. };
  18486. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18487. /**
  18488. * Add an array of shapes to THREE.ShapeGeometry.
  18489. */
  18490. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18491. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18492. this.addShape( shapes[ i ], options );
  18493. }
  18494. return this;
  18495. };
  18496. /**
  18497. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18498. */
  18499. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18500. if ( options === undefined ) options = {};
  18501. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18502. var material = options.material;
  18503. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18504. var shapebb = this.shapebb;
  18505. //
  18506. var i, l, hole, s;
  18507. var shapesOffset = this.vertices.length;
  18508. var shapePoints = shape.extractPoints( curveSegments );
  18509. var vertices = shapePoints.shape;
  18510. var holes = shapePoints.holes;
  18511. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18512. if ( reverse ) {
  18513. vertices = vertices.reverse();
  18514. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18515. for ( i = 0, l = holes.length; i < l; i++ ) {
  18516. hole = holes[ i ];
  18517. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18518. holes[ i ] = hole.reverse();
  18519. }
  18520. }
  18521. reverse = false;
  18522. }
  18523. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18524. // Vertices
  18525. var contour = vertices;
  18526. for ( i = 0, l = holes.length; i < l; i++ ) {
  18527. hole = holes[ i ];
  18528. vertices = vertices.concat( hole );
  18529. }
  18530. //
  18531. var vert, vlen = vertices.length;
  18532. var face, flen = faces.length;
  18533. var cont, clen = contour.length;
  18534. for ( i = 0; i < vlen; i++ ) {
  18535. vert = vertices[ i ];
  18536. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18537. }
  18538. for ( i = 0; i < flen; i++ ) {
  18539. face = faces[ i ];
  18540. var a = face[ 0 ] + shapesOffset;
  18541. var b = face[ 1 ] + shapesOffset;
  18542. var c = face[ 2 ] + shapesOffset;
  18543. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18544. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18545. }
  18546. };
  18547. /**
  18548. * @author astrodud / http://astrodud.isgreat.org/
  18549. * @author zz85 / https://github.com/zz85
  18550. */
  18551. THREE.LatheGeometry = function ( points, steps, angle ) {
  18552. THREE.Geometry.call( this );
  18553. var _steps = steps || 12;
  18554. var _angle = angle || 2 * Math.PI;
  18555. var _newV = [];
  18556. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18557. for ( var j = 0; j < points.length; j ++ ) {
  18558. _newV[ j ] = points[ j ].clone();
  18559. this.vertices.push( _newV[ j ] );
  18560. }
  18561. var i, il = _steps + 1;
  18562. for ( i = 0; i < il; i ++ ) {
  18563. for ( var j = 0; j < _newV.length; j ++ ) {
  18564. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18565. this.vertices.push( _newV[ j ] );
  18566. }
  18567. }
  18568. for ( i = 0; i < _steps; i ++ ) {
  18569. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18570. var a = i * kl + k;
  18571. var b = ( ( i + 1 ) % il ) * kl + k;
  18572. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18573. var d = i * kl + ( k + 1 ) % kl;
  18574. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18575. this.faceVertexUvs[ 0 ].push( [
  18576. new THREE.UV( 1 - i / _steps, k / kl ),
  18577. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18578. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18579. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18580. ] );
  18581. }
  18582. }
  18583. this.computeCentroids();
  18584. this.computeFaceNormals();
  18585. this.computeVertexNormals();
  18586. };
  18587. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18588. /**
  18589. * @author mrdoob / http://mrdoob.com/
  18590. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18591. */
  18592. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18593. THREE.Geometry.call( this );
  18594. this.width = width;
  18595. this.height = height;
  18596. this.widthSegments = widthSegments || 1;
  18597. this.heightSegments = heightSegments || 1;
  18598. var ix, iz;
  18599. var width_half = width / 2;
  18600. var height_half = height / 2;
  18601. var gridX = this.widthSegments;
  18602. var gridZ = this.heightSegments;
  18603. var gridX1 = gridX + 1;
  18604. var gridZ1 = gridZ + 1;
  18605. var segment_width = this.width / gridX;
  18606. var segment_height = this.height / gridZ;
  18607. var normal = new THREE.Vector3( 0, 0, 1 );
  18608. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18609. for ( ix = 0; ix < gridX1; ix ++ ) {
  18610. var x = ix * segment_width - width_half;
  18611. var y = iz * segment_height - height_half;
  18612. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18613. }
  18614. }
  18615. for ( iz = 0; iz < gridZ; iz ++ ) {
  18616. for ( ix = 0; ix < gridX; ix ++ ) {
  18617. var a = ix + gridX1 * iz;
  18618. var b = ix + gridX1 * ( iz + 1 );
  18619. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18620. var d = ( ix + 1 ) + gridX1 * iz;
  18621. var face = new THREE.Face4( a, b, c, d );
  18622. face.normal.copy( normal );
  18623. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18624. this.faces.push( face );
  18625. this.faceVertexUvs[ 0 ].push( [
  18626. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18627. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18628. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18629. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18630. ] );
  18631. }
  18632. }
  18633. this.computeCentroids();
  18634. };
  18635. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18636. /**
  18637. * @author mrdoob / http://mrdoob.com/
  18638. */
  18639. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18640. THREE.Geometry.call( this );
  18641. this.radius = radius || 50;
  18642. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  18643. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  18644. phiStart = phiStart !== undefined ? phiStart : 0;
  18645. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18646. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18647. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18648. var x, y, vertices = [], uvs = [];
  18649. for ( y = 0; y <= this.heightSegments; y ++ ) {
  18650. var verticesRow = [];
  18651. var uvsRow = [];
  18652. for ( x = 0; x <= this.widthSegments; x ++ ) {
  18653. var u = x / this.widthSegments;
  18654. var v = y / this.heightSegments;
  18655. var vertex = new THREE.Vector3();
  18656. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18657. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  18658. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18659. this.vertices.push( vertex );
  18660. verticesRow.push( this.vertices.length - 1 );
  18661. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18662. }
  18663. vertices.push( verticesRow );
  18664. uvs.push( uvsRow );
  18665. }
  18666. for ( y = 0; y < this.heightSegments; y ++ ) {
  18667. for ( x = 0; x < this.widthSegments; x ++ ) {
  18668. var v1 = vertices[ y ][ x + 1 ];
  18669. var v2 = vertices[ y ][ x ];
  18670. var v3 = vertices[ y + 1 ][ x ];
  18671. var v4 = vertices[ y + 1 ][ x + 1 ];
  18672. var n1 = this.vertices[ v1 ].clone().normalize();
  18673. var n2 = this.vertices[ v2 ].clone().normalize();
  18674. var n3 = this.vertices[ v3 ].clone().normalize();
  18675. var n4 = this.vertices[ v4 ].clone().normalize();
  18676. var uv1 = uvs[ y ][ x + 1 ].clone();
  18677. var uv2 = uvs[ y ][ x ].clone();
  18678. var uv3 = uvs[ y + 1 ][ x ].clone();
  18679. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18680. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  18681. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18682. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18683. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  18684. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18685. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18686. } else {
  18687. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18688. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18689. }
  18690. }
  18691. }
  18692. this.computeCentroids();
  18693. this.computeFaceNormals();
  18694. this.boundingSphere = { radius: this.radius };
  18695. };
  18696. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18697. /**
  18698. * @author zz85 / http://www.lab4games.net/zz85/blog
  18699. * @author alteredq / http://alteredqualia.com/
  18700. *
  18701. * For creating 3D text geometry in three.js
  18702. *
  18703. * Text = 3D Text
  18704. *
  18705. * parameters = {
  18706. * size: <float>, // size of the text
  18707. * height: <float>, // thickness to extrude text
  18708. * curveSegments: <int>, // number of points on the curves
  18709. *
  18710. * font: <string>, // font name
  18711. * weight: <string>, // font weight (normal, bold)
  18712. * style: <string>, // font style (normal, italics)
  18713. *
  18714. * bevelEnabled: <bool>, // turn on bevel
  18715. * bevelThickness: <float>, // how deep into text bevel goes
  18716. * bevelSize: <float>, // how far from text outline is bevel
  18717. * }
  18718. *
  18719. */
  18720. /* Usage Examples
  18721. // TextGeometry wrapper
  18722. var text3d = new TextGeometry( text, options );
  18723. // Complete manner
  18724. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18725. var text3d = new ExtrudeGeometry( textShapes, options );
  18726. */
  18727. THREE.TextGeometry = function ( text, parameters ) {
  18728. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18729. // translate parameters to ExtrudeGeometry API
  18730. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18731. // defaults
  18732. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18733. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18734. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18735. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18736. };
  18737. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18738. /**
  18739. * @author oosmoxiecode
  18740. * @author mrdoob / http://mrdoob.com/
  18741. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18742. */
  18743. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  18744. THREE.Geometry.call( this );
  18745. var scope = this;
  18746. this.radius = radius || 100;
  18747. this.tube = tube || 40;
  18748. this.radialSegments = radialSegments || 8;
  18749. this.tubularSegments = tubularSegments || 6;
  18750. this.arc = arc || Math.PI * 2;
  18751. var center = new THREE.Vector3(), uvs = [], normals = [];
  18752. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  18753. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  18754. var u = i / this.tubularSegments * this.arc;
  18755. var v = j / this.radialSegments * Math.PI * 2;
  18756. center.x = this.radius * Math.cos( u );
  18757. center.y = this.radius * Math.sin( u );
  18758. var vertex = new THREE.Vector3();
  18759. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18760. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18761. vertex.z = this.tube * Math.sin( v );
  18762. this.vertices.push( vertex );
  18763. uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
  18764. normals.push( vertex.clone().subSelf( center ).normalize() );
  18765. }
  18766. }
  18767. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  18768. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  18769. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  18770. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  18771. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  18772. var d = ( this.tubularSegments + 1 ) * j + i;
  18773. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18774. face.normal.addSelf( normals[ a ] );
  18775. face.normal.addSelf( normals[ b ] );
  18776. face.normal.addSelf( normals[ c ] );
  18777. face.normal.addSelf( normals[ d ] );
  18778. face.normal.normalize();
  18779. this.faces.push( face );
  18780. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18781. }
  18782. }
  18783. this.computeCentroids();
  18784. };
  18785. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18786. /**
  18787. * @author oosmoxiecode
  18788. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18789. */
  18790. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  18791. THREE.Geometry.call( this );
  18792. var scope = this;
  18793. this.radius = radius || 200;
  18794. this.tube = tube || 40;
  18795. this.radialSegments = radialSegments || 64;
  18796. this.tubularSegments = tubularSegments || 8;
  18797. this.p = p || 2;
  18798. this.q = q || 3;
  18799. this.heightScale = heightScale || 1;
  18800. this.grid = new Array(this.radialSegments);
  18801. var tang = new THREE.Vector3();
  18802. var n = new THREE.Vector3();
  18803. var bitan = new THREE.Vector3();
  18804. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18805. this.grid[ i ] = new Array( this.tubularSegments );
  18806. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18807. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  18808. var v = j / this.tubularSegments * 2 * Math.PI;
  18809. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18810. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18811. var cx, cy;
  18812. tang.sub( p2, p1 );
  18813. n.add( p2, p1 );
  18814. bitan.cross( tang, n );
  18815. n.cross( bitan, tang );
  18816. bitan.normalize();
  18817. n.normalize();
  18818. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18819. cy = this.tube * Math.sin( v );
  18820. p1.x += cx * n.x + cy * bitan.x;
  18821. p1.y += cx * n.y + cy * bitan.y;
  18822. p1.z += cx * n.z + cy * bitan.z;
  18823. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18824. }
  18825. }
  18826. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18827. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18828. var ip = ( i + 1 ) % this.radialSegments;
  18829. var jp = ( j + 1 ) % this.tubularSegments;
  18830. var a = this.grid[ i ][ j ];
  18831. var b = this.grid[ ip ][ j ];
  18832. var c = this.grid[ ip ][ jp ];
  18833. var d = this.grid[ i ][ jp ];
  18834. var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
  18835. var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  18836. var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18837. var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18838. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18839. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18840. }
  18841. }
  18842. this.computeCentroids();
  18843. this.computeFaceNormals();
  18844. this.computeVertexNormals();
  18845. function vert( x, y, z ) {
  18846. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18847. }
  18848. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18849. var cu = Math.cos( u );
  18850. var cv = Math.cos( v );
  18851. var su = Math.sin( u );
  18852. var quOverP = in_q / in_p * u;
  18853. var cs = Math.cos( quOverP );
  18854. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18855. var ty = radius * ( 2 + cs ) * su * 0.5;
  18856. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18857. return new THREE.Vector3( tx, ty, tz );
  18858. }
  18859. };
  18860. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18861. /**
  18862. * @author WestLangley / https://github.com/WestLangley
  18863. * @author zz85 / https://github.com/zz85
  18864. * @author miningold / https://github.com/miningold
  18865. *
  18866. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18867. *
  18868. * Creates a tube which extrudes along a 3d spline
  18869. *
  18870. * Uses parallel transport frames as described in
  18871. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18872. */
  18873. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  18874. THREE.Geometry.call( this );
  18875. this.path = path;
  18876. this.segments = segments || 64;
  18877. this.radius = radius || 1;
  18878. this.radiusSegments = radiusSegments || 8;
  18879. this.closed = closed || false;
  18880. if ( debug ) this.debug = new THREE.Object3D();
  18881. this.grid = [];
  18882. var scope = this,
  18883. tangent,
  18884. normal,
  18885. binormal,
  18886. numpoints = this.segments + 1,
  18887. x, y, z,
  18888. tx, ty, tz,
  18889. u, v,
  18890. cx, cy,
  18891. pos, pos2 = new THREE.Vector3(),
  18892. i, j,
  18893. ip, jp,
  18894. a, b, c, d,
  18895. uva, uvb, uvc, uvd;
  18896. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  18897. tangents = frames.tangents,
  18898. normals = frames.normals,
  18899. binormals = frames.binormals;
  18900. // proxy internals
  18901. this.tangents = tangents;
  18902. this.normals = normals;
  18903. this.binormals = binormals;
  18904. function vert( x, y, z ) {
  18905. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18906. }
  18907. // consruct the grid
  18908. for ( i = 0; i < numpoints; i++ ) {
  18909. this.grid[ i ] = [];
  18910. u = i / ( numpoints - 1 );
  18911. pos = path.getPointAt( u );
  18912. tangent = tangents[ i ];
  18913. normal = normals[ i ];
  18914. binormal = binormals[ i ];
  18915. if ( this.debug ) {
  18916. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  18917. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  18918. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  18919. }
  18920. for ( j = 0; j < this.radiusSegments; j++ ) {
  18921. v = j / this.radiusSegments * 2 * Math.PI;
  18922. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18923. cy = this.radius * Math.sin( v );
  18924. pos2.copy( pos );
  18925. pos2.x += cx * normal.x + cy * binormal.x;
  18926. pos2.y += cx * normal.y + cy * binormal.y;
  18927. pos2.z += cx * normal.z + cy * binormal.z;
  18928. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18929. }
  18930. }
  18931. // construct the mesh
  18932. for ( i = 0; i < this.segments; i++ ) {
  18933. for ( j = 0; j < this.radiusSegments; j++ ) {
  18934. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  18935. jp = (j + 1) % this.radiusSegments;
  18936. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18937. b = this.grid[ ip ][ j ];
  18938. c = this.grid[ ip ][ jp ];
  18939. d = this.grid[ i ][ jp ];
  18940. uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
  18941. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
  18942. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  18943. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
  18944. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18945. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18946. }
  18947. }
  18948. this.computeCentroids();
  18949. this.computeFaceNormals();
  18950. this.computeVertexNormals();
  18951. };
  18952. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18953. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18954. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  18955. var tangent = new THREE.Vector3(),
  18956. normal = new THREE.Vector3(),
  18957. binormal = new THREE.Vector3(),
  18958. tangents = [],
  18959. normals = [],
  18960. binormals = [],
  18961. vec = new THREE.Vector3(),
  18962. mat = new THREE.Matrix4(),
  18963. numpoints = segments + 1,
  18964. theta,
  18965. epsilon = 0.0001,
  18966. smallest,
  18967. tx, ty, tz,
  18968. i, u, v;
  18969. // expose internals
  18970. this.tangents = tangents;
  18971. this.normals = normals;
  18972. this.binormals = binormals;
  18973. // compute the tangent vectors for each segment on the path
  18974. for ( i = 0; i < numpoints; i++ ) {
  18975. u = i / ( numpoints - 1 );
  18976. tangents[ i ] = path.getTangentAt( u );
  18977. tangents[ i ].normalize();
  18978. }
  18979. initialNormal3();
  18980. function initialNormal1(lastBinormal) {
  18981. // fixed start binormal. Has dangers of 0 vectors
  18982. normals[ 0 ] = new THREE.Vector3();
  18983. binormals[ 0 ] = new THREE.Vector3();
  18984. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18985. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  18986. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18987. }
  18988. function initialNormal2() {
  18989. // This uses the Frenet-Serret formula for deriving binormal
  18990. var t2 = path.getTangentAt( epsilon );
  18991. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  18992. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  18993. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18994. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18995. }
  18996. function initialNormal3() {
  18997. // select an initial normal vector perpenicular to the first tangent vector,
  18998. // and in the direction of the smallest tangent xyz component
  18999. normals[ 0 ] = new THREE.Vector3();
  19000. binormals[ 0 ] = new THREE.Vector3();
  19001. smallest = Number.MAX_VALUE;
  19002. tx = Math.abs( tangents[ 0 ].x );
  19003. ty = Math.abs( tangents[ 0 ].y );
  19004. tz = Math.abs( tangents[ 0 ].z );
  19005. if ( tx <= smallest ) {
  19006. smallest = tx;
  19007. normal.set( 1, 0, 0 );
  19008. }
  19009. if ( ty <= smallest ) {
  19010. smallest = ty;
  19011. normal.set( 0, 1, 0 );
  19012. }
  19013. if ( tz <= smallest ) {
  19014. normal.set( 0, 0, 1 );
  19015. }
  19016. vec.cross( tangents[ 0 ], normal ).normalize();
  19017. normals[ 0 ].cross( tangents[ 0 ], vec );
  19018. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  19019. }
  19020. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19021. for ( i = 1; i < numpoints; i++ ) {
  19022. normals[ i ] = normals[ i-1 ].clone();
  19023. binormals[ i ] = binormals[ i-1 ].clone();
  19024. vec.cross( tangents[ i-1 ], tangents[ i ] );
  19025. if ( vec.length() > epsilon ) {
  19026. vec.normalize();
  19027. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19028. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19029. }
  19030. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19031. }
  19032. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19033. if ( closed ) {
  19034. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19035. theta /= ( numpoints - 1 );
  19036. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19037. theta = -theta;
  19038. }
  19039. for ( i = 1; i < numpoints; i++ ) {
  19040. // twist a little...
  19041. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19042. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19043. }
  19044. }
  19045. };
  19046. /**
  19047. * @author clockworkgeek / https://github.com/clockworkgeek
  19048. * @author timothypratley / https://github.com/timothypratley
  19049. */
  19050. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19051. THREE.Geometry.call( this );
  19052. radius = radius || 1;
  19053. detail = detail || 0;
  19054. var that = this;
  19055. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19056. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19057. }
  19058. var midpoints = [], p = this.vertices;
  19059. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19060. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19061. }
  19062. this.mergeVertices();
  19063. // Apply radius
  19064. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19065. this.vertices[ i ].multiplyScalar( radius );
  19066. }
  19067. // Project vector onto sphere's surface
  19068. function prepare( vector ) {
  19069. var vertex = vector.normalize().clone();
  19070. vertex.index = that.vertices.push( vertex ) - 1;
  19071. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19072. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19073. var v = inclination( vector ) / Math.PI + 0.5;
  19074. vertex.uv = new THREE.UV( u, 1 - v );
  19075. return vertex;
  19076. }
  19077. // Approximate a curved face with recursively sub-divided triangles.
  19078. function make( v1, v2, v3, detail ) {
  19079. if ( detail < 1 ) {
  19080. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19081. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19082. face.normal = face.centroid.clone().normalize();
  19083. that.faces.push( face );
  19084. var azi = azimuth( face.centroid );
  19085. that.faceVertexUvs[ 0 ].push( [
  19086. correctUV( v1.uv, v1, azi ),
  19087. correctUV( v2.uv, v2, azi ),
  19088. correctUV( v3.uv, v3, azi )
  19089. ] );
  19090. } else {
  19091. detail -= 1;
  19092. // split triangle into 4 smaller triangles
  19093. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19094. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19095. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19096. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19097. }
  19098. }
  19099. function midpoint( v1, v2 ) {
  19100. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19101. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19102. var mid = midpoints[ v1.index ][ v2.index ];
  19103. if ( mid === undefined ) {
  19104. // generate mean point and project to surface with prepare()
  19105. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19106. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19107. );
  19108. }
  19109. return mid;
  19110. }
  19111. // Angle around the Y axis, counter-clockwise when looking from above.
  19112. function azimuth( vector ) {
  19113. return Math.atan2( vector.z, -vector.x );
  19114. }
  19115. // Angle above the XZ plane.
  19116. function inclination( vector ) {
  19117. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19118. }
  19119. // Texture fixing helper. Spheres have some odd behaviours.
  19120. function correctUV( uv, vector, azimuth ) {
  19121. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  19122. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  19123. return uv;
  19124. }
  19125. this.computeCentroids();
  19126. this.boundingSphere = { radius: radius };
  19127. };
  19128. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19129. /**
  19130. * @author timothypratley / https://github.com/timothypratley
  19131. */
  19132. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19133. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19134. var vertices = [
  19135. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19136. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19137. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19138. ];
  19139. var faces = [
  19140. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19141. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19142. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19143. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19144. ];
  19145. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19146. };
  19147. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19148. /**
  19149. * @author timothypratley / https://github.com/timothypratley
  19150. */
  19151. THREE.OctahedronGeometry = function ( radius, detail ) {
  19152. var vertices = [
  19153. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19154. ];
  19155. var faces = [
  19156. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19157. ];
  19158. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19159. };
  19160. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19161. /**
  19162. * @author timothypratley / https://github.com/timothypratley
  19163. */
  19164. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19165. var vertices = [
  19166. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19167. ];
  19168. var faces = [
  19169. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19170. ];
  19171. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19172. };
  19173. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19174. /**
  19175. * @author zz85 / https://github.com/zz85
  19176. * Parametric Surfaces Geometry
  19177. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19178. *
  19179. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19180. *
  19181. */
  19182. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19183. THREE.Geometry.call( this );
  19184. var verts = this.vertices;
  19185. var faces = this.faces;
  19186. var uvs = this.faceVertexUvs[ 0 ];
  19187. useTris = (useTris === undefined) ? false : useTris;
  19188. var i, il, j, p;
  19189. var u, v;
  19190. var stackCount = stacks + 1;
  19191. var sliceCount = slices + 1;
  19192. for ( i = 0; i <= stacks; i ++ ) {
  19193. v = i / stacks;
  19194. for ( j = 0; j <= slices; j ++ ) {
  19195. u = j / slices;
  19196. p = func( u, v );
  19197. verts.push( p );
  19198. }
  19199. }
  19200. var a, b, c, d;
  19201. var uva, uvb, uvc, uvd;
  19202. for ( i = 0; i < stacks; i ++ ) {
  19203. for ( j = 0; j < slices; j ++ ) {
  19204. a = i * sliceCount + j;
  19205. b = i * sliceCount + j + 1;
  19206. c = (i + 1) * sliceCount + j;
  19207. d = (i + 1) * sliceCount + j + 1;
  19208. uva = new THREE.UV( j / slices, i / stacks );
  19209. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19210. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19211. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19212. if ( useTris ) {
  19213. faces.push( new THREE.Face3( a, b, c ) );
  19214. faces.push( new THREE.Face3( b, d, c ) );
  19215. uvs.push( [ uva, uvb, uvc ] );
  19216. uvs.push( [ uvb, uvd, uvc ] );
  19217. } else {
  19218. faces.push( new THREE.Face4( a, b, d, c ) );
  19219. uvs.push( [ uva, uvb, uvd, uvc ] );
  19220. }
  19221. }
  19222. }
  19223. // console.log(this);
  19224. // magic bullet
  19225. // var diff = this.mergeVertices();
  19226. // console.log('removed ', diff, ' vertices by merging');
  19227. this.computeCentroids();
  19228. this.computeFaceNormals();
  19229. this.computeVertexNormals();
  19230. };
  19231. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19232. /**
  19233. * @author qiao / https://github.com/qiao
  19234. * @fileoverview This is a convex hull generator using the incremental method.
  19235. * The complexity is O(n^2) where n is the number of vertices.
  19236. * O(nlogn) algorithms do exist, but they are much more complicated.
  19237. *
  19238. * Benchmark:
  19239. *
  19240. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19241. *
  19242. * Num Vertices Time(ms)
  19243. *
  19244. * 10 1
  19245. * 20 3
  19246. * 30 19
  19247. * 40 48
  19248. * 50 107
  19249. */
  19250. THREE.ConvexGeometry = function( vertices ) {
  19251. THREE.Geometry.call( this );
  19252. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19253. for ( var i = 3; i < vertices.length; i++ ) {
  19254. addPoint( i );
  19255. }
  19256. function addPoint( vertexId ) {
  19257. var vertex = vertices[ vertexId ].clone();
  19258. var mag = vertex.length();
  19259. vertex.x += mag * randomOffset();
  19260. vertex.y += mag * randomOffset();
  19261. vertex.z += mag * randomOffset();
  19262. var hole = [];
  19263. for ( var f = 0; f < faces.length; ) {
  19264. var face = faces[ f ];
  19265. // for each face, if the vertex can see it,
  19266. // then we try to add the face's edges into the hole.
  19267. if ( visible( face, vertex ) ) {
  19268. for ( var e = 0; e < 3; e++ ) {
  19269. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19270. var boundary = true;
  19271. // remove duplicated edges.
  19272. for ( var h = 0; h < hole.length; h++ ) {
  19273. if ( equalEdge( hole[ h ], edge ) ) {
  19274. hole[ h ] = hole[ hole.length - 1 ];
  19275. hole.pop();
  19276. boundary = false;
  19277. break;
  19278. }
  19279. }
  19280. if ( boundary ) {
  19281. hole.push( edge );
  19282. }
  19283. }
  19284. // remove faces[ f ]
  19285. faces[ f ] = faces[ faces.length - 1 ];
  19286. faces.pop();
  19287. } else { // not visible
  19288. f++;
  19289. }
  19290. }
  19291. // construct the new faces formed by the edges of the hole and the vertex
  19292. for ( var h = 0; h < hole.length; h++ ) {
  19293. faces.push( [
  19294. hole[ h ][ 0 ],
  19295. hole[ h ][ 1 ],
  19296. vertexId
  19297. ] );
  19298. }
  19299. }
  19300. /**
  19301. * Whether the face is visible from the vertex
  19302. */
  19303. function visible( face, vertex ) {
  19304. var va = vertices[ face[ 0 ] ];
  19305. var vb = vertices[ face[ 1 ] ];
  19306. var vc = vertices[ face[ 2 ] ];
  19307. var n = normal( va, vb, vc );
  19308. // distance from face to origin
  19309. var dist = n.dot( va );
  19310. return n.dot( vertex ) >= dist;
  19311. }
  19312. /**
  19313. * Face normal
  19314. */
  19315. function normal( va, vb, vc ) {
  19316. var cb = new THREE.Vector3();
  19317. var ab = new THREE.Vector3();
  19318. cb.sub( vc, vb );
  19319. ab.sub( va, vb );
  19320. cb.crossSelf( ab );
  19321. cb.normalize();
  19322. return cb;
  19323. }
  19324. /**
  19325. * Detect whether two edges are equal.
  19326. * Note that when constructing the convex hull, two same edges can only
  19327. * be of the negative direction.
  19328. */
  19329. function equalEdge( ea, eb ) {
  19330. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19331. }
  19332. /**
  19333. * Create a random offset between -1e-6 and 1e-6.
  19334. */
  19335. function randomOffset() {
  19336. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19337. }
  19338. /**
  19339. * XXX: Not sure if this is the correct approach. Need someone to review.
  19340. */
  19341. function vertexUv( vertex ) {
  19342. var mag = vertex.length();
  19343. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19344. }
  19345. // Push vertices into `this.vertices`, skipping those inside the hull
  19346. var id = 0;
  19347. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19348. for ( var i = 0; i < faces.length; i++ ) {
  19349. var face = faces[ i ];
  19350. for ( var j = 0; j < 3; j++ ) {
  19351. if ( newId[ face[ j ] ] === undefined ) {
  19352. newId[ face[ j ] ] = id++;
  19353. this.vertices.push( vertices[ face[ j ] ] );
  19354. }
  19355. face[ j ] = newId[ face[ j ] ];
  19356. }
  19357. }
  19358. // Convert faces into instances of THREE.Face3
  19359. for ( var i = 0; i < faces.length; i++ ) {
  19360. this.faces.push( new THREE.Face3(
  19361. faces[ i ][ 0 ],
  19362. faces[ i ][ 1 ],
  19363. faces[ i ][ 2 ]
  19364. ) );
  19365. }
  19366. // Compute UVs
  19367. for ( var i = 0; i < this.faces.length; i++ ) {
  19368. var face = this.faces[ i ];
  19369. this.faceVertexUvs[ 0 ].push( [
  19370. vertexUv( this.vertices[ face.a ] ),
  19371. vertexUv( this.vertices[ face.b ] ),
  19372. vertexUv( this.vertices[ face.c ])
  19373. ] );
  19374. }
  19375. this.computeCentroids();
  19376. this.computeFaceNormals();
  19377. this.computeVertexNormals();
  19378. };
  19379. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19380. /**
  19381. * @author sroucheray / http://sroucheray.org/
  19382. * @author mrdoob / http://mrdoob.com/
  19383. */
  19384. THREE.AxisHelper = function ( size ) {
  19385. var geometry = new THREE.Geometry();
  19386. geometry.vertices.push(
  19387. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19388. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19389. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19390. );
  19391. geometry.colors.push(
  19392. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19393. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19394. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19395. );
  19396. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19397. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19398. };
  19399. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19400. /**
  19401. * @author WestLangley / http://github.com/WestLangley
  19402. * @author zz85 / https://github.com/zz85
  19403. *
  19404. * Creates an arrow for visualizing directions
  19405. *
  19406. * Parameters:
  19407. * dir - Vector3
  19408. * origin - Vector3
  19409. * length - Number
  19410. * hex - color in hex value
  19411. */
  19412. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19413. THREE.Object3D.call( this );
  19414. if ( hex === undefined ) hex = 0xffff00;
  19415. if ( length === undefined ) length = 20;
  19416. var lineGeometry = new THREE.Geometry();
  19417. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19418. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19419. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19420. this.add( this.line );
  19421. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19422. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19423. this.cone.position.set( 0, 1, 0 );
  19424. this.add( this.cone );
  19425. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19426. this.setDirection( dir );
  19427. this.setLength( length );
  19428. };
  19429. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19430. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19431. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19432. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19433. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19434. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19435. };
  19436. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19437. this.scale.set( length, length, length );
  19438. };
  19439. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19440. this.line.material.color.setHex( hex );
  19441. this.cone.material.color.setHex( hex );
  19442. };
  19443. /**
  19444. * @author alteredq / http://alteredqualia.com/
  19445. *
  19446. * - shows frustum, line of sight and up of the camera
  19447. * - suitable for fast updates
  19448. * - based on frustum visualization in lightgl.js shadowmap example
  19449. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19450. */
  19451. THREE.CameraHelper = function ( camera ) {
  19452. THREE.Line.call( this );
  19453. var scope = this;
  19454. this.geometry = new THREE.Geometry();
  19455. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19456. this.type = THREE.LinePieces;
  19457. this.matrixWorld = camera.matrixWorld;
  19458. this.matrixAutoUpdate = false;
  19459. this.pointMap = {};
  19460. // colors
  19461. var hexFrustum = 0xffaa00;
  19462. var hexCone = 0xff0000;
  19463. var hexUp = 0x00aaff;
  19464. var hexTarget = 0xffffff;
  19465. var hexCross = 0x333333;
  19466. // near
  19467. addLine( "n1", "n2", hexFrustum );
  19468. addLine( "n2", "n4", hexFrustum );
  19469. addLine( "n4", "n3", hexFrustum );
  19470. addLine( "n3", "n1", hexFrustum );
  19471. // far
  19472. addLine( "f1", "f2", hexFrustum );
  19473. addLine( "f2", "f4", hexFrustum );
  19474. addLine( "f4", "f3", hexFrustum );
  19475. addLine( "f3", "f1", hexFrustum );
  19476. // sides
  19477. addLine( "n1", "f1", hexFrustum );
  19478. addLine( "n2", "f2", hexFrustum );
  19479. addLine( "n3", "f3", hexFrustum );
  19480. addLine( "n4", "f4", hexFrustum );
  19481. // cone
  19482. addLine( "p", "n1", hexCone );
  19483. addLine( "p", "n2", hexCone );
  19484. addLine( "p", "n3", hexCone );
  19485. addLine( "p", "n4", hexCone );
  19486. // up
  19487. addLine( "u1", "u2", hexUp );
  19488. addLine( "u2", "u3", hexUp );
  19489. addLine( "u3", "u1", hexUp );
  19490. // target
  19491. addLine( "c", "t", hexTarget );
  19492. addLine( "p", "c", hexCross );
  19493. // cross
  19494. addLine( "cn1", "cn2", hexCross );
  19495. addLine( "cn3", "cn4", hexCross );
  19496. addLine( "cf1", "cf2", hexCross );
  19497. addLine( "cf3", "cf4", hexCross );
  19498. this.camera = camera;
  19499. function addLine( a, b, hex ) {
  19500. addPoint( a, hex );
  19501. addPoint( b, hex );
  19502. }
  19503. function addPoint( id, hex ) {
  19504. scope.geometry.vertices.push( new THREE.Vector3() );
  19505. scope.geometry.colors.push( new THREE.Color( hex ) );
  19506. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19507. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19508. }
  19509. this.update( camera );
  19510. };
  19511. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19512. THREE.CameraHelper.prototype.update = function () {
  19513. var scope = this;
  19514. var w = 1, h = 1;
  19515. // we need just camera projection matrix
  19516. // world matrix must be identity
  19517. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19518. // center / target
  19519. setPoint( "c", 0, 0, -1 );
  19520. setPoint( "t", 0, 0, 1 );
  19521. // near
  19522. setPoint( "n1", -w, -h, -1 );
  19523. setPoint( "n2", w, -h, -1 );
  19524. setPoint( "n3", -w, h, -1 );
  19525. setPoint( "n4", w, h, -1 );
  19526. // far
  19527. setPoint( "f1", -w, -h, 1 );
  19528. setPoint( "f2", w, -h, 1 );
  19529. setPoint( "f3", -w, h, 1 );
  19530. setPoint( "f4", w, h, 1 );
  19531. // up
  19532. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19533. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19534. setPoint( "u3", 0, h * 2, -1 );
  19535. // cross
  19536. setPoint( "cf1", -w, 0, 1 );
  19537. setPoint( "cf2", w, 0, 1 );
  19538. setPoint( "cf3", 0, -h, 1 );
  19539. setPoint( "cf4", 0, h, 1 );
  19540. setPoint( "cn1", -w, 0, -1 );
  19541. setPoint( "cn2", w, 0, -1 );
  19542. setPoint( "cn3", 0, -h, -1 );
  19543. setPoint( "cn4", 0, h, -1 );
  19544. function setPoint( point, x, y, z ) {
  19545. THREE.CameraHelper.__v.set( x, y, z );
  19546. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19547. var points = scope.pointMap[ point ];
  19548. if ( points !== undefined ) {
  19549. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19550. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19551. }
  19552. }
  19553. }
  19554. this.geometry.verticesNeedUpdate = true;
  19555. };
  19556. THREE.CameraHelper.__projector = new THREE.Projector();
  19557. THREE.CameraHelper.__v = new THREE.Vector3();
  19558. THREE.CameraHelper.__c = new THREE.Camera();
  19559. /**
  19560. * @author alteredq / http://alteredqualia.com/
  19561. *
  19562. * - shows directional light color, intensity, position, orientation and target
  19563. */
  19564. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  19565. THREE.Object3D.call( this );
  19566. this.light = light;
  19567. // position
  19568. this.position = light.position;
  19569. // direction
  19570. this.direction = new THREE.Vector3();
  19571. this.direction.sub( light.target.position, light.position );
  19572. // color
  19573. this.color = light.color.clone();
  19574. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19575. this.color.r *= intensity;
  19576. this.color.g *= intensity;
  19577. this.color.b *= intensity;
  19578. var hexColor = this.color.getHex();
  19579. // light helper
  19580. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19581. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19582. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19583. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19584. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19585. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19586. this.lightArrow.cone.material.fog = false;
  19587. this.lightArrow.line.material.fog = false;
  19588. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19589. this.add( this.lightArrow );
  19590. this.add( this.lightSphere );
  19591. this.add( this.lightRays );
  19592. this.lightSphere.properties.isGizmo = true;
  19593. this.lightSphere.properties.gizmoSubject = light;
  19594. this.lightSphere.properties.gizmoRoot = this;
  19595. // light target helper
  19596. this.targetSphere = null;
  19597. if ( light.target.properties.targetInverse ) {
  19598. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19599. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19600. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19601. this.targetSphere.position = light.target.position;
  19602. this.targetSphere.properties.isGizmo = true;
  19603. this.targetSphere.properties.gizmoSubject = light.target;
  19604. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19605. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19606. var lineGeometry = new THREE.Geometry();
  19607. lineGeometry.vertices.push( this.position.clone() );
  19608. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19609. lineGeometry.computeLineDistances();
  19610. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19611. this.targetLine.properties.isGizmo = true;
  19612. }
  19613. //
  19614. this.properties.isGizmo = true;
  19615. }
  19616. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19617. THREE.DirectionalLightHelper.prototype.update = function () {
  19618. // update arrow orientation
  19619. // pointing from light to target
  19620. this.direction.sub( this.light.target.position, this.light.position );
  19621. this.lightArrow.setDirection( this.direction );
  19622. // update arrow, spheres, rays and line colors to light color * light intensity
  19623. this.color.copy( this.light.color );
  19624. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19625. this.color.r *= intensity;
  19626. this.color.g *= intensity;
  19627. this.color.b *= intensity;
  19628. this.lightArrow.setColor( this.color.getHex() );
  19629. this.lightSphere.material.color.copy( this.color );
  19630. this.lightRays.material.color.copy( this.color );
  19631. this.targetSphere.material.color.copy( this.color );
  19632. this.targetLine.material.color.copy( this.color );
  19633. // update target line vertices
  19634. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19635. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19636. this.targetLine.geometry.computeLineDistances();
  19637. this.targetLine.geometry.verticesNeedUpdate = true;
  19638. }
  19639. /**
  19640. * @author alteredq / http://alteredqualia.com/
  19641. *
  19642. * - shows hemisphere light intensity, sky and ground colors and directions
  19643. */
  19644. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  19645. THREE.Object3D.call( this );
  19646. this.light = light;
  19647. // position
  19648. this.position = light.position;
  19649. //
  19650. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19651. // sky color
  19652. this.color = light.color.clone();
  19653. this.color.r *= intensity;
  19654. this.color.g *= intensity;
  19655. this.color.b *= intensity;
  19656. var hexColor = this.color.getHex();
  19657. // ground color
  19658. this.groundColor = light.groundColor.clone();
  19659. this.groundColor.r *= intensity;
  19660. this.groundColor.g *= intensity;
  19661. this.groundColor.b *= intensity;
  19662. var hexColorGround = this.groundColor.getHex();
  19663. // double colored light bulb
  19664. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  19665. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  19666. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19667. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  19668. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  19669. bulbGeometry.faces[ i ].materialIndex = 0;
  19670. }
  19671. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  19672. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  19673. }
  19674. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  19675. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  19676. // arrows for sky and ground light directions
  19677. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  19678. this.lightArrow.rotation.x = Math.PI;
  19679. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  19680. var joint = new THREE.Object3D();
  19681. joint.rotation.x = -Math.PI * 0.5;
  19682. joint.add( this.lightSphere );
  19683. joint.add( this.lightArrow );
  19684. joint.add( this.lightArrowGround );
  19685. this.add( joint );
  19686. //
  19687. this.lightSphere.properties.isGizmo = true;
  19688. this.lightSphere.properties.gizmoSubject = light;
  19689. this.lightSphere.properties.gizmoRoot = this;
  19690. //
  19691. this.properties.isGizmo = true;
  19692. //
  19693. this.target = new THREE.Vector3();
  19694. this.lookAt( this.target );
  19695. }
  19696. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19697. THREE.HemisphereLightHelper.prototype.update = function () {
  19698. // update sphere sky and ground colors to light color * light intensity
  19699. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19700. this.color.copy( this.light.color );
  19701. this.groundColor.copy( this.light.groundColor );
  19702. this.color.r *= intensity;
  19703. this.color.g *= intensity;
  19704. this.color.b *= intensity;
  19705. this.groundColor.r *= intensity;
  19706. this.groundColor.g *= intensity;
  19707. this.groundColor.b *= intensity;
  19708. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  19709. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  19710. this.lightArrow.setColor( this.color.getHex() );
  19711. this.lightArrowGround.setColor( this.groundColor.getHex() );
  19712. this.lookAt( this.target );
  19713. }
  19714. /**
  19715. * @author alteredq / http://alteredqualia.com/
  19716. *
  19717. * - shows point light color, intensity, position and distance
  19718. */
  19719. THREE.PointLightHelper = function ( light, sphereSize ) {
  19720. THREE.Object3D.call( this );
  19721. this.light = light;
  19722. // position
  19723. this.position = light.position;
  19724. // color
  19725. this.color = light.color.clone();
  19726. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19727. this.color.r *= intensity;
  19728. this.color.g *= intensity;
  19729. this.color.b *= intensity;
  19730. var hexColor = this.color.getHex();
  19731. // light helper
  19732. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19733. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19734. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  19735. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19736. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19737. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  19738. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19739. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19740. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  19741. var d = light.distance;
  19742. if ( d === 0.0 ) {
  19743. this.lightDistance.visible = false;
  19744. } else {
  19745. this.lightDistance.scale.set( d, d, d );
  19746. }
  19747. this.add( this.lightSphere );
  19748. this.add( this.lightRays );
  19749. this.add( this.lightDistance );
  19750. //
  19751. this.lightSphere.properties.isGizmo = true;
  19752. this.lightSphere.properties.gizmoSubject = light;
  19753. this.lightSphere.properties.gizmoRoot = this;
  19754. //
  19755. this.properties.isGizmo = true;
  19756. }
  19757. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19758. THREE.PointLightHelper.prototype.update = function () {
  19759. // update sphere and rays colors to light color * light intensity
  19760. this.color.copy( this.light.color );
  19761. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19762. this.color.r *= intensity;
  19763. this.color.g *= intensity;
  19764. this.color.b *= intensity;
  19765. this.lightSphere.material.color.copy( this.color );
  19766. this.lightRays.material.color.copy( this.color );
  19767. this.lightDistance.material.color.copy( this.color );
  19768. //
  19769. var d = this.light.distance;
  19770. if ( d === 0.0 ) {
  19771. this.lightDistance.visible = false;
  19772. } else {
  19773. this.lightDistance.visible = true;
  19774. this.lightDistance.scale.set( d, d, d );
  19775. }
  19776. }
  19777. /**
  19778. * @author alteredq / http://alteredqualia.com/
  19779. *
  19780. * - shows spot light color, intensity, position, orientation, light cone and target
  19781. */
  19782. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  19783. THREE.Object3D.call( this );
  19784. this.light = light;
  19785. // position
  19786. this.position = light.position;
  19787. // direction
  19788. this.direction = new THREE.Vector3();
  19789. this.direction.sub( light.target.position, light.position );
  19790. // color
  19791. this.color = light.color.clone();
  19792. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19793. this.color.r *= intensity;
  19794. this.color.g *= intensity;
  19795. this.color.b *= intensity;
  19796. var hexColor = this.color.getHex();
  19797. // light helper
  19798. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19799. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19800. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  19801. var coneMatrix = new THREE.Matrix4();
  19802. coneMatrix.rotateX( -Math.PI/2 );
  19803. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  19804. coneGeometry.applyMatrix( coneMatrix );
  19805. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19806. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19807. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  19808. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19809. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19810. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  19811. var coneLength = light.distance ? light.distance : 10000;
  19812. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  19813. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19814. this.lightArrow.cone.material.fog = false;
  19815. this.lightArrow.line.material.fog = false;
  19816. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19817. this.gyroscope = new THREE.Gyroscope();
  19818. this.gyroscope.add( this.lightArrow );
  19819. this.gyroscope.add( this.lightSphere );
  19820. this.gyroscope.add( this.lightRays );
  19821. this.add( this.gyroscope );
  19822. this.add( this.lightCone );
  19823. this.lookAt( light.target.position );
  19824. this.lightSphere.properties.isGizmo = true;
  19825. this.lightSphere.properties.gizmoSubject = light;
  19826. this.lightSphere.properties.gizmoRoot = this;
  19827. // light target helper
  19828. this.targetSphere = null;
  19829. if ( light.target.properties.targetInverse ) {
  19830. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19831. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19832. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19833. this.targetSphere.position = light.target.position;
  19834. this.targetSphere.properties.isGizmo = true;
  19835. this.targetSphere.properties.gizmoSubject = light.target;
  19836. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19837. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19838. var lineGeometry = new THREE.Geometry();
  19839. lineGeometry.vertices.push( this.position.clone() );
  19840. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19841. lineGeometry.computeLineDistances();
  19842. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19843. this.targetLine.properties.isGizmo = true;
  19844. }
  19845. //
  19846. this.properties.isGizmo = true;
  19847. }
  19848. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19849. THREE.SpotLightHelper.prototype.update = function () {
  19850. // update arrow orientation
  19851. // pointing from light to target
  19852. this.direction.sub( this.light.target.position, this.light.position );
  19853. this.lightArrow.setDirection( this.direction );
  19854. // update light cone orientation and size
  19855. this.lookAt( this.light.target.position );
  19856. var coneLength = this.light.distance ? this.light.distance : 10000;
  19857. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  19858. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19859. // update arrow, spheres, rays and line colors to light color * light intensity
  19860. this.color.copy( this.light.color );
  19861. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19862. this.color.r *= intensity;
  19863. this.color.g *= intensity;
  19864. this.color.b *= intensity;
  19865. this.lightArrow.setColor( this.color.getHex() );
  19866. this.lightSphere.material.color.copy( this.color );
  19867. this.lightRays.material.color.copy( this.color );
  19868. this.lightCone.material.color.copy( this.color );
  19869. this.targetSphere.material.color.copy( this.color );
  19870. this.targetLine.material.color.copy( this.color );
  19871. // update target line vertices
  19872. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19873. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19874. this.targetLine.geometry.computeLineDistances();
  19875. this.targetLine.geometry.verticesNeedUpdate = true;
  19876. }
  19877. /*
  19878. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19879. *
  19880. * Subdivision Geometry Modifier
  19881. * using Catmull-Clark Subdivision Surfaces
  19882. * for creating smooth geometry meshes
  19883. *
  19884. * Note: a modifier modifies vertices and faces of geometry,
  19885. * so use geometry.clone() if original geometry needs to be retained
  19886. *
  19887. * Readings:
  19888. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19889. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19890. * http://xrt.wikidot.com/blog:31
  19891. * "Subdivision Surfaces in Character Animation"
  19892. *
  19893. * (on boundary edges)
  19894. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19895. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  19896. *
  19897. * Supports:
  19898. * Closed and Open geometries.
  19899. *
  19900. * TODO:
  19901. * crease vertex and "semi-sharp" features
  19902. * selective subdivision
  19903. */
  19904. THREE.SubdivisionModifier = function( subdivisions ) {
  19905. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19906. // Settings
  19907. this.useOldVertexColors = false;
  19908. this.supportUVs = true;
  19909. this.debug = false;
  19910. };
  19911. // Applies the "modify" pattern
  19912. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19913. var repeats = this.subdivisions;
  19914. while ( repeats-- > 0 ) {
  19915. this.smooth( geometry );
  19916. }
  19917. };
  19918. /// REFACTORING THIS OUT
  19919. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  19920. return Math.min( a, b ) + "_" + Math.max( a, b );
  19921. };
  19922. // Returns a hashmap - of { edge_key: face_index }
  19923. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  19924. var i, il, v1, v2, j, k,
  19925. face, faceIndices, faceIndex,
  19926. edge,
  19927. hash,
  19928. edgeFaceMap = {};
  19929. var orderedKey = THREE.GeometryUtils.orderedKey;
  19930. function mapEdgeHash( hash, i ) {
  19931. if ( edgeFaceMap[ hash ] === undefined ) {
  19932. edgeFaceMap[ hash ] = [];
  19933. }
  19934. edgeFaceMap[ hash ].push( i );
  19935. }
  19936. // construct vertex -> face map
  19937. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19938. face = geometry.faces[ i ];
  19939. if ( face instanceof THREE.Face3 ) {
  19940. hash = orderedKey( face.a, face.b );
  19941. mapEdgeHash( hash, i );
  19942. hash = orderedKey( face.b, face.c );
  19943. mapEdgeHash( hash, i );
  19944. hash = orderedKey( face.c, face.a );
  19945. mapEdgeHash( hash, i );
  19946. } else if ( face instanceof THREE.Face4 ) {
  19947. hash = orderedKey( face.a, face.b );
  19948. mapEdgeHash( hash, i );
  19949. hash = orderedKey( face.b, face.c );
  19950. mapEdgeHash( hash, i );
  19951. hash = orderedKey( face.c, face.d );
  19952. mapEdgeHash( hash, i );
  19953. hash = orderedKey( face.d, face.a );
  19954. mapEdgeHash( hash, i );
  19955. }
  19956. }
  19957. // extract faces
  19958. // var edges = [];
  19959. //
  19960. // var numOfEdges = 0;
  19961. // for (i in edgeFaceMap) {
  19962. // numOfEdges++;
  19963. //
  19964. // edge = edgeFaceMap[i];
  19965. // edges.push(edge);
  19966. //
  19967. // }
  19968. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19969. return edgeFaceMap;
  19970. }
  19971. /////////////////////////////
  19972. // Performs an iteration of Catmull-Clark Subdivision
  19973. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19974. //debug( 'running smooth' );
  19975. // New set of vertices, faces and uvs
  19976. var newVertices = [], newFaces = [], newUVs = [];
  19977. function v( x, y, z ) {
  19978. newVertices.push( new THREE.Vector3( x, y, z ) );
  19979. }
  19980. var scope = this;
  19981. var orderedKey = THREE.GeometryUtils.orderedKey;
  19982. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  19983. function assert() {
  19984. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  19985. }
  19986. function debug() {
  19987. if (scope.debug) console.log.apply(console, arguments);
  19988. }
  19989. function warn() {
  19990. if (console)
  19991. console.log.apply(console, arguments);
  19992. }
  19993. function f4( a, b, c, d, oldFace, orders, facei ) {
  19994. // TODO move vertex selection over here!
  19995. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19996. if (scope.useOldVertexColors) {
  19997. newFace.vertexColors = [];
  19998. var color, tmpColor, order;
  19999. for (var i=0;i<4;i++) {
  20000. order = orders[i];
  20001. color = new THREE.Color(),
  20002. color.setRGB(0,0,0);
  20003. for (var j=0, jl=0; j<order.length;j++) {
  20004. tmpColor = oldFace.vertexColors[order[j]-1];
  20005. color.r += tmpColor.r;
  20006. color.g += tmpColor.g;
  20007. color.b += tmpColor.b;
  20008. }
  20009. color.r /= order.length;
  20010. color.g /= order.length;
  20011. color.b /= order.length;
  20012. newFace.vertexColors[i] = color;
  20013. }
  20014. }
  20015. newFaces.push( newFace );
  20016. if (scope.supportUVs) {
  20017. var aUv = [
  20018. getUV(a, ''),
  20019. getUV(b, facei),
  20020. getUV(c, facei),
  20021. getUV(d, facei)
  20022. ];
  20023. if (!aUv[0]) debug('a :( ', a+':'+facei);
  20024. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  20025. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  20026. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  20027. else
  20028. newUVs.push( aUv );
  20029. }
  20030. }
  20031. var originalPoints = oldGeometry.vertices;
  20032. var originalFaces = oldGeometry.faces;
  20033. var originalVerticesLength = originalPoints.length;
  20034. var newPoints = originalPoints.concat(); // New set of vertices to work on
  20035. var facePoints = [], // these are new points on exisiting faces
  20036. edgePoints = {}; // these are new points on exisiting edges
  20037. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  20038. // TODO: handle this correctly.
  20039. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  20040. function debugCoreStuff() {
  20041. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  20042. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  20043. }
  20044. function getUV(vertexNo, oldFaceNo) {
  20045. var j,jl;
  20046. var key = vertexNo+':'+oldFaceNo;
  20047. var theUV = uvForVertices[key];
  20048. if (!theUV) {
  20049. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  20050. debug('face pt');
  20051. } else {
  20052. debug('edge pt');
  20053. }
  20054. warn('warning, UV not found for', key);
  20055. return null;
  20056. }
  20057. return theUV;
  20058. // Original faces -> Vertex Nos.
  20059. // new Facepoint -> Vertex Nos.
  20060. // edge Points
  20061. }
  20062. function addUV(vertexNo, oldFaceNo, value) {
  20063. var key = vertexNo+':'+oldFaceNo;
  20064. if (!(key in uvForVertices)) {
  20065. uvForVertices[key] = value;
  20066. } else {
  20067. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  20068. }
  20069. }
  20070. // Step 1
  20071. // For each face, add a face point
  20072. // Set each face point to be the centroid of all original points for the respective face.
  20073. // debug(oldGeometry);
  20074. var i, il, j, jl, face;
  20075. // For Uvs
  20076. var uvs = oldGeometry.faceVertexUvs[0];
  20077. var abcd = 'abcd', vertice;
  20078. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  20079. if (scope.supportUVs)
  20080. for (i=0, il = uvs.length; i<il; i++ ) {
  20081. for (j=0,jl=uvs[i].length;j<jl;j++) {
  20082. vertice = originalFaces[i][abcd.charAt(j)];
  20083. addUV(vertice, i, uvs[i][j]);
  20084. }
  20085. }
  20086. if (uvs.length == 0) scope.supportUVs = false;
  20087. // Additional UVs check, if we index original
  20088. var uvCount = 0;
  20089. for (var u in uvForVertices) {
  20090. uvCount++;
  20091. }
  20092. if (!uvCount) {
  20093. scope.supportUVs = false;
  20094. debug('no uvs');
  20095. }
  20096. var avgUv ;
  20097. for (i=0, il = originalFaces.length; i<il ;i++) {
  20098. face = originalFaces[ i ];
  20099. facePoints.push( face.centroid );
  20100. newPoints.push( face.centroid );
  20101. if (!scope.supportUVs) continue;
  20102. // Prepare subdivided uv
  20103. avgUv = new THREE.UV();
  20104. if ( face instanceof THREE.Face3 ) {
  20105. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  20106. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  20107. avgUv.u /= 3;
  20108. avgUv.v /= 3;
  20109. } else if ( face instanceof THREE.Face4 ) {
  20110. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  20111. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  20112. avgUv.u /= 4;
  20113. avgUv.v /= 4;
  20114. }
  20115. addUV(originalVerticesLength + i, '', avgUv);
  20116. }
  20117. // Step 2
  20118. // For each edge, add an edge point.
  20119. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  20120. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  20121. var edge, faceIndexA, faceIndexB, avg;
  20122. // debug('edgeFaceMap', edgeFaceMap);
  20123. var edgeCount = 0;
  20124. var edgeVertex, edgeVertexA, edgeVertexB;
  20125. ////
  20126. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  20127. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  20128. function addVertexEdgeMap(vertex, edge) {
  20129. if (vertexEdgeMap[vertex]===undefined) {
  20130. vertexEdgeMap[vertex] = [];
  20131. }
  20132. vertexEdgeMap[vertex].push(edge);
  20133. }
  20134. function addVertexFaceMap(vertex, face, edge) {
  20135. if (vertexFaceMap[vertex]===undefined) {
  20136. vertexFaceMap[vertex] = {};
  20137. }
  20138. vertexFaceMap[vertex][face] = edge;
  20139. // vertexFaceMap[vertex][face] = null;
  20140. }
  20141. // Prepares vertexEdgeMap and vertexFaceMap
  20142. for (i in edgeFaceMap) { // This is for every edge
  20143. edge = edgeFaceMap[i];
  20144. edgeVertex = i.split('_');
  20145. edgeVertexA = edgeVertex[0];
  20146. edgeVertexB = edgeVertex[1];
  20147. // Maps an edgeVertex to connecting edges
  20148. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  20149. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  20150. for (j=0,jl=edge.length;j<jl;j++) {
  20151. face = edge[j];
  20152. addVertexFaceMap(edgeVertexA, face, i);
  20153. addVertexFaceMap(edgeVertexB, face, i);
  20154. }
  20155. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  20156. // this thing is fishy right now.
  20157. if (edge.length < 2) {
  20158. // edge is "sharp";
  20159. sharpEdges[i] = true;
  20160. sharpVertices[edgeVertexA] = true;
  20161. sharpVertices[edgeVertexB] = true;
  20162. }
  20163. }
  20164. for (i in edgeFaceMap) {
  20165. edge = edgeFaceMap[i];
  20166. faceIndexA = edge[0]; // face index a
  20167. faceIndexB = edge[1]; // face index b
  20168. edgeVertex = i.split('_');
  20169. edgeVertexA = edgeVertex[0];
  20170. edgeVertexB = edgeVertex[1];
  20171. avg = new THREE.Vector3();
  20172. //debug(i, faceIndexB,facePoints[faceIndexB]);
  20173. assert(edge.length > 0, 'an edge without faces?!');
  20174. if (edge.length==1) {
  20175. avg.addSelf(originalPoints[edgeVertexA]);
  20176. avg.addSelf(originalPoints[edgeVertexB]);
  20177. avg.multiplyScalar(0.5);
  20178. sharpVertices[newPoints.length] = true;
  20179. } else {
  20180. avg.addSelf(facePoints[faceIndexA]);
  20181. avg.addSelf(facePoints[faceIndexB]);
  20182. avg.addSelf(originalPoints[edgeVertexA]);
  20183. avg.addSelf(originalPoints[edgeVertexB]);
  20184. avg.multiplyScalar(0.25);
  20185. }
  20186. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  20187. newPoints.push( avg );
  20188. edgeCount ++;
  20189. if (!scope.supportUVs) {
  20190. continue;
  20191. }
  20192. // Prepare subdivided uv
  20193. avgUv = new THREE.UV();
  20194. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  20195. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  20196. avgUv.u /= 2;
  20197. avgUv.v /= 2;
  20198. addUV(edgePoints[i], faceIndexA, avgUv);
  20199. if (edge.length>=2) {
  20200. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  20201. avgUv = new THREE.UV();
  20202. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  20203. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  20204. avgUv.u /= 2;
  20205. avgUv.v /= 2;
  20206. addUV(edgePoints[i], faceIndexB, avgUv);
  20207. }
  20208. }
  20209. debug('-- Step 2 done');
  20210. // Step 3
  20211. // For each face point, add an edge for every edge of the face,
  20212. // connecting the face point to each edge point for the face.
  20213. var facePt, currentVerticeIndex;
  20214. var hashAB, hashBC, hashCD, hashDA, hashCA;
  20215. var abc123 = ['123', '12', '2', '23'];
  20216. var bca123 = ['123', '23', '3', '31'];
  20217. var cab123 = ['123', '31', '1', '12'];
  20218. var abc1234 = ['1234', '12', '2', '23'];
  20219. var bcd1234 = ['1234', '23', '3', '34'];
  20220. var cda1234 = ['1234', '34', '4', '41'];
  20221. var dab1234 = ['1234', '41', '1', '12'];
  20222. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  20223. facePt = facePoints[i];
  20224. face = originalFaces[i];
  20225. currentVerticeIndex = originalVerticesLength+ i;
  20226. if ( face instanceof THREE.Face3 ) {
  20227. // create 3 face4s
  20228. hashAB = orderedKey( face.a, face.b );
  20229. hashBC = orderedKey( face.b, face.c );
  20230. hashCA = orderedKey( face.c, face.a );
  20231. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  20232. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  20233. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  20234. } else if ( face instanceof THREE.Face4 ) {
  20235. // create 4 face4s
  20236. hashAB = orderedKey( face.a, face.b );
  20237. hashBC = orderedKey( face.b, face.c );
  20238. hashCD = orderedKey( face.c, face.d );
  20239. hashDA = orderedKey( face.d, face.a );
  20240. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  20241. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  20242. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  20243. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  20244. } else {
  20245. debug('face should be a face!', face);
  20246. }
  20247. }
  20248. newVertices = newPoints;
  20249. // Step 4
  20250. // For each original point P,
  20251. // take the average F of all n face points for faces touching P,
  20252. // and take the average R of all n edge midpoints for edges touching P,
  20253. // where each edge midpoint is the average of its two endpoint vertices.
  20254. // Move each original point to the point
  20255. var F = new THREE.Vector3();
  20256. var R = new THREE.Vector3();
  20257. var n;
  20258. for (i=0, il = originalPoints.length; i<il; i++) {
  20259. // (F + 2R + (n-3)P) / n
  20260. if (vertexEdgeMap[i]===undefined) continue;
  20261. F.set(0,0,0);
  20262. R.set(0,0,0);
  20263. var newPos = new THREE.Vector3(0,0,0);
  20264. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  20265. for (j in vertexFaceMap[i]) {
  20266. F.addSelf(facePoints[j]);
  20267. f++;
  20268. }
  20269. var sharpEdgeCount = 0;
  20270. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  20271. // Are we on the border?
  20272. var boundary_case = f != n;
  20273. // if (boundary_case) {
  20274. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  20275. // }
  20276. for (j=0;j<n;j++) {
  20277. if (
  20278. sharpEdges[
  20279. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20280. ]) {
  20281. sharpEdgeCount++;
  20282. }
  20283. }
  20284. // if ( sharpEdgeCount==2 ) {
  20285. // continue;
  20286. // // Do not move vertex if there's 2 connecting sharp edges.
  20287. // }
  20288. /*
  20289. if (sharpEdgeCount>2) {
  20290. // TODO
  20291. }
  20292. */
  20293. F.divideScalar(f);
  20294. var boundary_edges = 0;
  20295. if (boundary_case) {
  20296. var bb_edge;
  20297. for (j=0; j<n;j++) {
  20298. edge = vertexEdgeMap[i][j];
  20299. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  20300. if (bb_edge) {
  20301. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20302. R.addSelf(midPt);
  20303. boundary_edges++;
  20304. }
  20305. }
  20306. R.divideScalar(4);
  20307. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  20308. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  20309. } else {
  20310. for (j=0; j<n;j++) {
  20311. edge = vertexEdgeMap[i][j];
  20312. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20313. R.addSelf(midPt);
  20314. }
  20315. R.divideScalar(n);
  20316. }
  20317. // Sum the formula
  20318. newPos.addSelf(originalPoints[i]);
  20319. if (boundary_case) {
  20320. newPos.divideScalar(2);
  20321. newPos.addSelf(R);
  20322. } else {
  20323. newPos.multiplyScalar(n - 3);
  20324. newPos.addSelf(F);
  20325. newPos.addSelf(R.multiplyScalar(2));
  20326. newPos.divideScalar(n);
  20327. }
  20328. newVertices[i] = newPos;
  20329. }
  20330. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20331. newGeometry.vertices = newVertices;
  20332. newGeometry.faces = newFaces;
  20333. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20334. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20335. newGeometry.computeCentroids();
  20336. newGeometry.computeFaceNormals();
  20337. newGeometry.computeVertexNormals();
  20338. };
  20339. /**
  20340. * @author alteredq / http://alteredqualia.com/
  20341. */
  20342. THREE.ImmediateRenderObject = function ( ) {
  20343. THREE.Object3D.call( this );
  20344. this.render = function ( renderCallback ) { };
  20345. };
  20346. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20347. /**
  20348. * @author mikael emtinger / http://gomo.se/
  20349. * @author alteredq / http://alteredqualia.com/
  20350. */
  20351. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20352. THREE.Object3D.call( this );
  20353. this.lensFlares = [];
  20354. this.positionScreen = new THREE.Vector3();
  20355. this.customUpdateCallback = undefined;
  20356. if( texture !== undefined ) {
  20357. this.add( texture, size, distance, blending, color );
  20358. }
  20359. };
  20360. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20361. /*
  20362. * Add: adds another flare
  20363. */
  20364. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20365. if( size === undefined ) size = -1;
  20366. if( distance === undefined ) distance = 0;
  20367. if( opacity === undefined ) opacity = 1;
  20368. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20369. if( blending === undefined ) blending = THREE.NormalBlending;
  20370. distance = Math.min( distance, Math.max( 0, distance ) );
  20371. this.lensFlares.push( { texture: texture, // THREE.Texture
  20372. size: size, // size in pixels (-1 = use texture.width)
  20373. distance: distance, // distance (0-1) from light source (0=at light source)
  20374. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20375. scale: 1, // scale
  20376. rotation: 1, // rotation
  20377. opacity: opacity, // opacity
  20378. color: color, // color
  20379. blending: blending } ); // blending
  20380. };
  20381. /*
  20382. * Update lens flares update positions on all flares based on the screen position
  20383. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20384. */
  20385. THREE.LensFlare.prototype.updateLensFlares = function () {
  20386. var f, fl = this.lensFlares.length;
  20387. var flare;
  20388. var vecX = -this.positionScreen.x * 2;
  20389. var vecY = -this.positionScreen.y * 2;
  20390. for( f = 0; f < fl; f ++ ) {
  20391. flare = this.lensFlares[ f ];
  20392. flare.x = this.positionScreen.x + vecX * flare.distance;
  20393. flare.y = this.positionScreen.y + vecY * flare.distance;
  20394. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20395. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20396. }
  20397. };
  20398. /**
  20399. * @author alteredq / http://alteredqualia.com/
  20400. */
  20401. THREE.MorphBlendMesh = function( geometry, material ) {
  20402. THREE.Mesh.call( this, geometry, material );
  20403. this.animationsMap = {};
  20404. this.animationsList = [];
  20405. // prepare default animation
  20406. // (all frames played together in 1 second)
  20407. var numFrames = this.geometry.morphTargets.length;
  20408. var name = "__default";
  20409. var startFrame = 0;
  20410. var endFrame = numFrames - 1;
  20411. var fps = numFrames / 1;
  20412. this.createAnimation( name, startFrame, endFrame, fps );
  20413. this.setAnimationWeight( name, 1 );
  20414. };
  20415. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20416. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20417. var animation = {
  20418. startFrame: start,
  20419. endFrame: end,
  20420. length: end - start + 1,
  20421. fps: fps,
  20422. duration: ( end - start ) / fps,
  20423. lastFrame: 0,
  20424. currentFrame: 0,
  20425. active: false,
  20426. time: 0,
  20427. direction: 1,
  20428. weight: 1,
  20429. directionBackwards: false,
  20430. mirroredLoop: false
  20431. };
  20432. this.animationsMap[ name ] = animation;
  20433. this.animationsList.push( animation );
  20434. };
  20435. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20436. var pattern = /([a-z]+)(\d+)/;
  20437. var firstAnimation, frameRanges = {};
  20438. var geometry = this.geometry;
  20439. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20440. var morph = geometry.morphTargets[ i ];
  20441. var chunks = morph.name.match( pattern );
  20442. if ( chunks && chunks.length > 1 ) {
  20443. var name = chunks[ 1 ];
  20444. var num = chunks[ 2 ];
  20445. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20446. var range = frameRanges[ name ];
  20447. if ( i < range.start ) range.start = i;
  20448. if ( i > range.end ) range.end = i;
  20449. if ( ! firstAnimation ) firstAnimation = name;
  20450. }
  20451. }
  20452. for ( var name in frameRanges ) {
  20453. var range = frameRanges[ name ];
  20454. this.createAnimation( name, range.start, range.end, fps );
  20455. }
  20456. this.firstAnimation = firstAnimation;
  20457. };
  20458. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20459. var animation = this.animationsMap[ name ];
  20460. if ( animation ) {
  20461. animation.direction = 1;
  20462. animation.directionBackwards = false;
  20463. }
  20464. };
  20465. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20466. var animation = this.animationsMap[ name ];
  20467. if ( animation ) {
  20468. animation.direction = -1;
  20469. animation.directionBackwards = true;
  20470. }
  20471. };
  20472. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20473. var animation = this.animationsMap[ name ];
  20474. if ( animation ) {
  20475. animation.fps = fps;
  20476. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20477. }
  20478. };
  20479. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20480. var animation = this.animationsMap[ name ];
  20481. if ( animation ) {
  20482. animation.duration = duration;
  20483. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20484. }
  20485. };
  20486. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20487. var animation = this.animationsMap[ name ];
  20488. if ( animation ) {
  20489. animation.weight = weight;
  20490. }
  20491. };
  20492. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20493. var animation = this.animationsMap[ name ];
  20494. if ( animation ) {
  20495. animation.time = time;
  20496. }
  20497. };
  20498. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20499. var time = 0;
  20500. var animation = this.animationsMap[ name ];
  20501. if ( animation ) {
  20502. time = animation.time;
  20503. }
  20504. return time;
  20505. };
  20506. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20507. var duration = -1;
  20508. var animation = this.animationsMap[ name ];
  20509. if ( animation ) {
  20510. duration = animation.duration;
  20511. }
  20512. return duration;
  20513. };
  20514. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20515. var animation = this.animationsMap[ name ];
  20516. if ( animation ) {
  20517. animation.time = 0;
  20518. animation.active = true;
  20519. } else {
  20520. console.warn( "animation[" + name + "] undefined" );
  20521. }
  20522. };
  20523. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20524. var animation = this.animationsMap[ name ];
  20525. if ( animation ) {
  20526. animation.active = false;
  20527. }
  20528. };
  20529. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20530. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20531. var animation = this.animationsList[ i ];
  20532. if ( ! animation.active ) continue;
  20533. var frameTime = animation.duration / animation.length;
  20534. animation.time += animation.direction * delta;
  20535. if ( animation.mirroredLoop ) {
  20536. if ( animation.time > animation.duration || animation.time < 0 ) {
  20537. animation.direction *= -1;
  20538. if ( animation.time > animation.duration ) {
  20539. animation.time = animation.duration;
  20540. animation.directionBackwards = true;
  20541. }
  20542. if ( animation.time < 0 ) {
  20543. animation.time = 0;
  20544. animation.directionBackwards = false;
  20545. }
  20546. }
  20547. } else {
  20548. animation.time = animation.time % animation.duration;
  20549. if ( animation.time < 0 ) animation.time += animation.duration;
  20550. }
  20551. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20552. var weight = animation.weight;
  20553. if ( keyframe !== animation.currentFrame ) {
  20554. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20555. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20556. this.morphTargetInfluences[ keyframe ] = 0;
  20557. animation.lastFrame = animation.currentFrame;
  20558. animation.currentFrame = keyframe;
  20559. }
  20560. var mix = ( animation.time % frameTime ) / frameTime;
  20561. if ( animation.directionBackwards ) mix = 1 - mix;
  20562. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20563. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20564. }
  20565. };
  20566. /**
  20567. * @author mikael emtinger / http://gomo.se/
  20568. * @author alteredq / http://alteredqualia.com/
  20569. */
  20570. THREE.LensFlarePlugin = function ( ) {
  20571. var _gl, _renderer, _lensFlare = {};
  20572. this.init = function ( renderer ) {
  20573. _gl = renderer.context;
  20574. _renderer = renderer;
  20575. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20576. _lensFlare.faces = new Uint16Array( 6 );
  20577. var i = 0;
  20578. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20579. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20580. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20581. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20582. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20583. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20584. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20585. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20586. i = 0;
  20587. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20588. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20589. // buffers
  20590. _lensFlare.vertexBuffer = _gl.createBuffer();
  20591. _lensFlare.elementBuffer = _gl.createBuffer();
  20592. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20593. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20594. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20595. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20596. // textures
  20597. _lensFlare.tempTexture = _gl.createTexture();
  20598. _lensFlare.occlusionTexture = _gl.createTexture();
  20599. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20600. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20601. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20602. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20603. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20604. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20605. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20606. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20607. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20608. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20609. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20610. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20611. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20612. _lensFlare.hasVertexTexture = false;
  20613. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20614. } else {
  20615. _lensFlare.hasVertexTexture = true;
  20616. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20617. }
  20618. _lensFlare.attributes = {};
  20619. _lensFlare.uniforms = {};
  20620. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20621. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20622. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20623. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20624. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20625. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20626. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20627. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20628. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20629. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20630. };
  20631. /*
  20632. * Render lens flares
  20633. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20634. * reads these back and calculates occlusion.
  20635. * Then _lensFlare.update_lensFlares() is called to re-position and
  20636. * update transparency of flares. Then they are rendered.
  20637. *
  20638. */
  20639. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20640. var flares = scene.__webglFlares,
  20641. nFlares = flares.length;
  20642. if ( ! nFlares ) return;
  20643. var tempPosition = new THREE.Vector3();
  20644. var invAspect = viewportHeight / viewportWidth,
  20645. halfViewportWidth = viewportWidth * 0.5,
  20646. halfViewportHeight = viewportHeight * 0.5;
  20647. var size = 16 / viewportHeight,
  20648. scale = new THREE.Vector2( size * invAspect, size );
  20649. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20650. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20651. var uniforms = _lensFlare.uniforms,
  20652. attributes = _lensFlare.attributes;
  20653. // set _lensFlare program and reset blending
  20654. _gl.useProgram( _lensFlare.program );
  20655. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20656. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20657. // loop through all lens flares to update their occlusion and positions
  20658. // setup gl and common used attribs/unforms
  20659. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20660. _gl.uniform1i( uniforms.map, 1 );
  20661. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20662. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20663. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20664. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20665. _gl.disable( _gl.CULL_FACE );
  20666. _gl.depthMask( false );
  20667. var i, j, jl, flare, sprite;
  20668. for ( i = 0; i < nFlares; i ++ ) {
  20669. size = 16 / viewportHeight;
  20670. scale.set( size * invAspect, size );
  20671. // calc object screen position
  20672. flare = flares[ i ];
  20673. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20674. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20675. camera.projectionMatrix.multiplyVector3( tempPosition );
  20676. // setup arrays for gl programs
  20677. screenPosition.copy( tempPosition )
  20678. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20679. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20680. // screen cull
  20681. if ( _lensFlare.hasVertexTexture || (
  20682. screenPositionPixels.x > 0 &&
  20683. screenPositionPixels.x < viewportWidth &&
  20684. screenPositionPixels.y > 0 &&
  20685. screenPositionPixels.y < viewportHeight ) ) {
  20686. // save current RGB to temp texture
  20687. _gl.activeTexture( _gl.TEXTURE1 );
  20688. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20689. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20690. // render pink quad
  20691. _gl.uniform1i( uniforms.renderType, 0 );
  20692. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20693. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20694. _gl.disable( _gl.BLEND );
  20695. _gl.enable( _gl.DEPTH_TEST );
  20696. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20697. // copy result to occlusionMap
  20698. _gl.activeTexture( _gl.TEXTURE0 );
  20699. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20700. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20701. // restore graphics
  20702. _gl.uniform1i( uniforms.renderType, 1 );
  20703. _gl.disable( _gl.DEPTH_TEST );
  20704. _gl.activeTexture( _gl.TEXTURE1 );
  20705. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20706. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20707. // update object positions
  20708. flare.positionScreen.copy( screenPosition )
  20709. if ( flare.customUpdateCallback ) {
  20710. flare.customUpdateCallback( flare );
  20711. } else {
  20712. flare.updateLensFlares();
  20713. }
  20714. // render flares
  20715. _gl.uniform1i( uniforms.renderType, 2 );
  20716. _gl.enable( _gl.BLEND );
  20717. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20718. sprite = flare.lensFlares[ j ];
  20719. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20720. screenPosition.x = sprite.x;
  20721. screenPosition.y = sprite.y;
  20722. screenPosition.z = sprite.z;
  20723. size = sprite.size * sprite.scale / viewportHeight;
  20724. scale.x = size * invAspect;
  20725. scale.y = size;
  20726. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20727. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20728. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20729. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20730. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20731. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20732. _renderer.setTexture( sprite.texture, 1 );
  20733. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20734. }
  20735. }
  20736. }
  20737. }
  20738. // restore gl
  20739. _gl.enable( _gl.CULL_FACE );
  20740. _gl.enable( _gl.DEPTH_TEST );
  20741. _gl.depthMask( true );
  20742. };
  20743. function createProgram ( shader ) {
  20744. var program = _gl.createProgram();
  20745. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20746. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20747. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20748. _gl.shaderSource( vertexShader, shader.vertexShader );
  20749. _gl.compileShader( fragmentShader );
  20750. _gl.compileShader( vertexShader );
  20751. _gl.attachShader( program, fragmentShader );
  20752. _gl.attachShader( program, vertexShader );
  20753. _gl.linkProgram( program );
  20754. return program;
  20755. };
  20756. };/**
  20757. * @author alteredq / http://alteredqualia.com/
  20758. */
  20759. THREE.ShadowMapPlugin = function ( ) {
  20760. var _gl,
  20761. _renderer,
  20762. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20763. _frustum = new THREE.Frustum(),
  20764. _projScreenMatrix = new THREE.Matrix4(),
  20765. _min = new THREE.Vector3(),
  20766. _max = new THREE.Vector3();
  20767. this.init = function ( renderer ) {
  20768. _gl = renderer.context;
  20769. _renderer = renderer;
  20770. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20771. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20772. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20773. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20774. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20775. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20776. _depthMaterial._shadowPass = true;
  20777. _depthMaterialMorph._shadowPass = true;
  20778. _depthMaterialSkin._shadowPass = true;
  20779. _depthMaterialMorphSkin._shadowPass = true;
  20780. };
  20781. this.render = function ( scene, camera ) {
  20782. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20783. this.update( scene, camera );
  20784. };
  20785. this.update = function ( scene, camera ) {
  20786. var i, il, j, jl, n,
  20787. shadowMap, shadowMatrix, shadowCamera,
  20788. program, buffer, material,
  20789. webglObject, object, light,
  20790. renderList,
  20791. lights = [],
  20792. k = 0,
  20793. fog = null;
  20794. // set GL state for depth map
  20795. _gl.clearColor( 1, 1, 1, 1 );
  20796. _gl.disable( _gl.BLEND );
  20797. _gl.enable( _gl.CULL_FACE );
  20798. _gl.frontFace( _gl.CCW );
  20799. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20800. _gl.cullFace( _gl.FRONT );
  20801. } else {
  20802. _gl.cullFace( _gl.BACK );
  20803. }
  20804. _renderer.setDepthTest( true );
  20805. // preprocess lights
  20806. // - skip lights that are not casting shadows
  20807. // - create virtual lights for cascaded shadow maps
  20808. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20809. light = scene.__lights[ i ];
  20810. if ( ! light.castShadow ) continue;
  20811. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20812. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20813. var virtualLight;
  20814. if ( ! light.shadowCascadeArray[ n ] ) {
  20815. virtualLight = createVirtualLight( light, n );
  20816. virtualLight.originalCamera = camera;
  20817. var gyro = new THREE.Gyroscope();
  20818. gyro.position = light.shadowCascadeOffset;
  20819. gyro.add( virtualLight );
  20820. gyro.add( virtualLight.target );
  20821. camera.add( gyro );
  20822. light.shadowCascadeArray[ n ] = virtualLight;
  20823. console.log( "Created virtualLight", virtualLight );
  20824. } else {
  20825. virtualLight = light.shadowCascadeArray[ n ];
  20826. }
  20827. updateVirtualLight( light, n );
  20828. lights[ k ] = virtualLight;
  20829. k ++;
  20830. }
  20831. } else {
  20832. lights[ k ] = light;
  20833. k ++;
  20834. }
  20835. }
  20836. // render depth map
  20837. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20838. light = lights[ i ];
  20839. if ( ! light.shadowMap ) {
  20840. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20841. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20842. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20843. light.shadowMatrix = new THREE.Matrix4();
  20844. }
  20845. if ( ! light.shadowCamera ) {
  20846. if ( light instanceof THREE.SpotLight ) {
  20847. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20848. } else if ( light instanceof THREE.DirectionalLight ) {
  20849. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20850. } else {
  20851. console.error( "Unsupported light type for shadow" );
  20852. continue;
  20853. }
  20854. scene.add( light.shadowCamera );
  20855. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20856. }
  20857. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20858. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20859. light.shadowCamera.add( light.cameraHelper );
  20860. }
  20861. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20862. updateShadowCamera( camera, light );
  20863. }
  20864. shadowMap = light.shadowMap;
  20865. shadowMatrix = light.shadowMatrix;
  20866. shadowCamera = light.shadowCamera;
  20867. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20868. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20869. shadowCamera.updateMatrixWorld();
  20870. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20871. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20872. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20873. // compute shadow matrix
  20874. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20875. 0.0, 0.5, 0.0, 0.5,
  20876. 0.0, 0.0, 0.5, 0.5,
  20877. 0.0, 0.0, 0.0, 1.0 );
  20878. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20879. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20880. // update camera matrices and frustum
  20881. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20882. _frustum.setFromMatrix( _projScreenMatrix );
  20883. // render shadow map
  20884. _renderer.setRenderTarget( shadowMap );
  20885. _renderer.clear();
  20886. // set object matrices & frustum culling
  20887. renderList = scene.__webglObjects;
  20888. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20889. webglObject = renderList[ j ];
  20890. object = webglObject.object;
  20891. webglObject.render = false;
  20892. if ( object.visible && object.castShadow ) {
  20893. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20894. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20895. webglObject.render = true;
  20896. }
  20897. }
  20898. }
  20899. // render regular objects
  20900. var objectMaterial, useMorphing, useSkinning;
  20901. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20902. webglObject = renderList[ j ];
  20903. if ( webglObject.render ) {
  20904. object = webglObject.object;
  20905. buffer = webglObject.buffer;
  20906. // culling is overriden globally for all objects
  20907. // while rendering depth map
  20908. // need to deal with MeshFaceMaterial somehow
  20909. // in that case just use the first of material.materials for now
  20910. // (proper solution would require to break objects by materials
  20911. // similarly to regular rendering and then set corresponding
  20912. // depth materials per each chunk instead of just once per object)
  20913. objectMaterial = getObjectMaterial( object );
  20914. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20915. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20916. if ( object.customDepthMaterial ) {
  20917. material = object.customDepthMaterial;
  20918. } else if ( useSkinning ) {
  20919. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20920. } else if ( useMorphing ) {
  20921. material = _depthMaterialMorph;
  20922. } else {
  20923. material = _depthMaterial;
  20924. }
  20925. if ( buffer instanceof THREE.BufferGeometry ) {
  20926. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20927. } else {
  20928. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20929. }
  20930. }
  20931. }
  20932. // set matrices and render immediate objects
  20933. renderList = scene.__webglObjectsImmediate;
  20934. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20935. webglObject = renderList[ j ];
  20936. object = webglObject.object;
  20937. if ( object.visible && object.castShadow ) {
  20938. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20939. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20940. }
  20941. }
  20942. }
  20943. // restore GL state
  20944. var clearColor = _renderer.getClearColor(),
  20945. clearAlpha = _renderer.getClearAlpha();
  20946. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20947. _gl.enable( _gl.BLEND );
  20948. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20949. _gl.cullFace( _gl.BACK );
  20950. }
  20951. };
  20952. function createVirtualLight( light, cascade ) {
  20953. var virtualLight = new THREE.DirectionalLight();
  20954. virtualLight.isVirtual = true;
  20955. virtualLight.onlyShadow = true;
  20956. virtualLight.castShadow = true;
  20957. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20958. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20959. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20960. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20961. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20962. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20963. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20964. virtualLight.shadowDarkness = light.shadowDarkness;
  20965. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20966. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20967. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20968. virtualLight.pointsWorld = [];
  20969. virtualLight.pointsFrustum = [];
  20970. var pointsWorld = virtualLight.pointsWorld,
  20971. pointsFrustum = virtualLight.pointsFrustum;
  20972. for ( var i = 0; i < 8; i ++ ) {
  20973. pointsWorld[ i ] = new THREE.Vector3();
  20974. pointsFrustum[ i ] = new THREE.Vector3();
  20975. }
  20976. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20977. var farZ = light.shadowCascadeFarZ[ cascade ];
  20978. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20979. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20980. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20981. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20982. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20983. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20984. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20985. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20986. return virtualLight;
  20987. }
  20988. // Synchronize virtual light with the original light
  20989. function updateVirtualLight( light, cascade ) {
  20990. var virtualLight = light.shadowCascadeArray[ cascade ];
  20991. virtualLight.position.copy( light.position );
  20992. virtualLight.target.position.copy( light.target.position );
  20993. virtualLight.lookAt( virtualLight.target );
  20994. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20995. virtualLight.shadowDarkness = light.shadowDarkness;
  20996. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20997. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20998. var farZ = light.shadowCascadeFarZ[ cascade ];
  20999. var pointsFrustum = virtualLight.pointsFrustum;
  21000. pointsFrustum[ 0 ].z = nearZ;
  21001. pointsFrustum[ 1 ].z = nearZ;
  21002. pointsFrustum[ 2 ].z = nearZ;
  21003. pointsFrustum[ 3 ].z = nearZ;
  21004. pointsFrustum[ 4 ].z = farZ;
  21005. pointsFrustum[ 5 ].z = farZ;
  21006. pointsFrustum[ 6 ].z = farZ;
  21007. pointsFrustum[ 7 ].z = farZ;
  21008. }
  21009. // Fit shadow camera's ortho frustum to camera frustum
  21010. function updateShadowCamera( camera, light ) {
  21011. var shadowCamera = light.shadowCamera,
  21012. pointsFrustum = light.pointsFrustum,
  21013. pointsWorld = light.pointsWorld;
  21014. _min.set( Infinity, Infinity, Infinity );
  21015. _max.set( -Infinity, -Infinity, -Infinity );
  21016. for ( var i = 0; i < 8; i ++ ) {
  21017. var p = pointsWorld[ i ];
  21018. p.copy( pointsFrustum[ i ] );
  21019. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21020. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21021. if ( p.x < _min.x ) _min.x = p.x;
  21022. if ( p.x > _max.x ) _max.x = p.x;
  21023. if ( p.y < _min.y ) _min.y = p.y;
  21024. if ( p.y > _max.y ) _max.y = p.y;
  21025. if ( p.z < _min.z ) _min.z = p.z;
  21026. if ( p.z > _max.z ) _max.z = p.z;
  21027. }
  21028. shadowCamera.left = _min.x;
  21029. shadowCamera.right = _max.x;
  21030. shadowCamera.top = _max.y;
  21031. shadowCamera.bottom = _min.y;
  21032. // can't really fit near/far
  21033. //shadowCamera.near = _min.z;
  21034. //shadowCamera.far = _max.z;
  21035. shadowCamera.updateProjectionMatrix();
  21036. }
  21037. // For the moment just ignore objects that have multiple materials with different animation methods
  21038. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21039. function getObjectMaterial( object ) {
  21040. return object.material instanceof THREE.MeshFaceMaterial
  21041. ? object.material.materials[ 0 ]
  21042. : object.material;
  21043. };
  21044. };
  21045. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21046. /**
  21047. * @author mikael emtinger / http://gomo.se/
  21048. * @author alteredq / http://alteredqualia.com/
  21049. */
  21050. THREE.SpritePlugin = function ( ) {
  21051. var _gl, _renderer, _sprite = {};
  21052. this.init = function ( renderer ) {
  21053. _gl = renderer.context;
  21054. _renderer = renderer;
  21055. _sprite.vertices = new Float32Array( 8 + 8 );
  21056. _sprite.faces = new Uint16Array( 6 );
  21057. var i = 0;
  21058. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21059. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21060. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21061. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21062. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21063. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21064. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21065. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21066. i = 0;
  21067. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21068. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21069. _sprite.vertexBuffer = _gl.createBuffer();
  21070. _sprite.elementBuffer = _gl.createBuffer();
  21071. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21072. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21073. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21074. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21075. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21076. _sprite.attributes = {};
  21077. _sprite.uniforms = {};
  21078. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21079. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21080. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21081. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21082. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21083. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21084. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21085. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21086. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21087. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21088. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21089. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21090. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21091. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21092. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21093. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21094. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21095. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21096. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21097. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21098. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21099. };
  21100. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21101. var sprites = scene.__webglSprites,
  21102. nSprites = sprites.length;
  21103. if ( ! nSprites ) return;
  21104. var attributes = _sprite.attributes,
  21105. uniforms = _sprite.uniforms;
  21106. var invAspect = viewportHeight / viewportWidth;
  21107. var halfViewportWidth = viewportWidth * 0.5,
  21108. halfViewportHeight = viewportHeight * 0.5;
  21109. // setup gl
  21110. _gl.useProgram( _sprite.program );
  21111. _gl.enableVertexAttribArray( attributes.position );
  21112. _gl.enableVertexAttribArray( attributes.uv );
  21113. _gl.disable( _gl.CULL_FACE );
  21114. _gl.enable( _gl.BLEND );
  21115. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21116. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21117. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21118. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21119. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21120. _gl.activeTexture( _gl.TEXTURE0 );
  21121. _gl.uniform1i( uniforms.map, 0 );
  21122. var oldFogType = 0;
  21123. var sceneFogType = 0;
  21124. var fog = scene.fog;
  21125. if ( fog ) {
  21126. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21127. if ( fog instanceof THREE.Fog ) {
  21128. _gl.uniform1f( uniforms.fogNear, fog.near );
  21129. _gl.uniform1f( uniforms.fogFar, fog.far );
  21130. _gl.uniform1i( uniforms.fogType, 1 );
  21131. oldFogType = 1;
  21132. sceneFogType = 1;
  21133. } else if ( fog instanceof THREE.FogExp2 ) {
  21134. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21135. _gl.uniform1i( uniforms.fogType, 2 );
  21136. oldFogType = 2;
  21137. sceneFogType = 2;
  21138. }
  21139. } else {
  21140. _gl.uniform1i( uniforms.fogType, 0 );
  21141. oldFogType = 0;
  21142. sceneFogType = 0;
  21143. }
  21144. // update positions and sort
  21145. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21146. for( i = 0; i < nSprites; i ++ ) {
  21147. sprite = sprites[ i ];
  21148. material = sprite.material;
  21149. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21150. if ( ! material.useScreenCoordinates ) {
  21151. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21152. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21153. } else {
  21154. sprite.z = - sprite.position.z;
  21155. }
  21156. }
  21157. sprites.sort( painterSortStable );
  21158. // render all sprites
  21159. for( i = 0; i < nSprites; i ++ ) {
  21160. sprite = sprites[ i ];
  21161. material = sprite.material;
  21162. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21163. if ( material.map && material.map.image && material.map.image.width ) {
  21164. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21165. if ( material.useScreenCoordinates ) {
  21166. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21167. _gl.uniform3f(
  21168. uniforms.screenPosition,
  21169. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21170. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21171. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21172. );
  21173. } else {
  21174. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21175. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21176. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21177. }
  21178. if ( scene.fog && material.fog ) {
  21179. fogType = sceneFogType;
  21180. } else {
  21181. fogType = 0;
  21182. }
  21183. if ( oldFogType !== fogType ) {
  21184. _gl.uniform1i( uniforms.fogType, fogType );
  21185. oldFogType = fogType;
  21186. }
  21187. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21188. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21189. scale[ 1 ] = size * sprite.scale.y;
  21190. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21191. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21192. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21193. _gl.uniform1f( uniforms.opacity, material.opacity );
  21194. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21195. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21196. _gl.uniform2fv( uniforms.scale, scale );
  21197. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21198. _renderer.setDepthTest( material.depthTest );
  21199. _renderer.setDepthWrite( material.depthWrite );
  21200. _renderer.setTexture( material.map, 0 );
  21201. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21202. }
  21203. }
  21204. // restore gl
  21205. _gl.enable( _gl.CULL_FACE );
  21206. };
  21207. function createProgram ( shader ) {
  21208. var program = _gl.createProgram();
  21209. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21210. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21211. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21212. _gl.shaderSource( vertexShader, shader.vertexShader );
  21213. _gl.compileShader( fragmentShader );
  21214. _gl.compileShader( vertexShader );
  21215. _gl.attachShader( program, fragmentShader );
  21216. _gl.attachShader( program, vertexShader );
  21217. _gl.linkProgram( program );
  21218. return program;
  21219. };
  21220. function painterSortStable ( a, b ) {
  21221. if ( a.z !== b.z ) {
  21222. return b.z - a.z;
  21223. } else {
  21224. return b.id - a.id;
  21225. }
  21226. };
  21227. };/**
  21228. * @author alteredq / http://alteredqualia.com/
  21229. */
  21230. THREE.DepthPassPlugin = function ( ) {
  21231. this.enabled = false;
  21232. this.renderTarget = null;
  21233. var _gl,
  21234. _renderer,
  21235. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21236. _frustum = new THREE.Frustum(),
  21237. _projScreenMatrix = new THREE.Matrix4();
  21238. this.init = function ( renderer ) {
  21239. _gl = renderer.context;
  21240. _renderer = renderer;
  21241. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21242. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21243. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21244. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21245. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21246. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21247. _depthMaterial._shadowPass = true;
  21248. _depthMaterialMorph._shadowPass = true;
  21249. _depthMaterialSkin._shadowPass = true;
  21250. _depthMaterialMorphSkin._shadowPass = true;
  21251. };
  21252. this.render = function ( scene, camera ) {
  21253. if ( ! this.enabled ) return;
  21254. this.update( scene, camera );
  21255. };
  21256. this.update = function ( scene, camera ) {
  21257. var i, il, j, jl, n,
  21258. program, buffer, material,
  21259. webglObject, object, light,
  21260. renderList,
  21261. fog = null;
  21262. // set GL state for depth map
  21263. _gl.clearColor( 1, 1, 1, 1 );
  21264. _gl.disable( _gl.BLEND );
  21265. _renderer.setDepthTest( true );
  21266. // update scene
  21267. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21268. // update camera matrices and frustum
  21269. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21270. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21271. _frustum.setFromMatrix( _projScreenMatrix );
  21272. // render depth map
  21273. _renderer.setRenderTarget( this.renderTarget );
  21274. _renderer.clear();
  21275. // set object matrices & frustum culling
  21276. renderList = scene.__webglObjects;
  21277. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21278. webglObject = renderList[ j ];
  21279. object = webglObject.object;
  21280. webglObject.render = false;
  21281. if ( object.visible ) {
  21282. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21283. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21284. webglObject.render = true;
  21285. }
  21286. }
  21287. }
  21288. // render regular objects
  21289. var objectMaterial, useMorphing, useSkinning;
  21290. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21291. webglObject = renderList[ j ];
  21292. if ( webglObject.render ) {
  21293. object = webglObject.object;
  21294. buffer = webglObject.buffer;
  21295. // todo: create proper depth material for particles
  21296. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21297. objectMaterial = getObjectMaterial( object );
  21298. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21299. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21300. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21301. if ( object.customDepthMaterial ) {
  21302. material = object.customDepthMaterial;
  21303. } else if ( useSkinning ) {
  21304. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21305. } else if ( useMorphing ) {
  21306. material = _depthMaterialMorph;
  21307. } else {
  21308. material = _depthMaterial;
  21309. }
  21310. if ( buffer instanceof THREE.BufferGeometry ) {
  21311. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21312. } else {
  21313. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21314. }
  21315. }
  21316. }
  21317. // set matrices and render immediate objects
  21318. renderList = scene.__webglObjectsImmediate;
  21319. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21320. webglObject = renderList[ j ];
  21321. object = webglObject.object;
  21322. if ( object.visible ) {
  21323. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21324. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21325. }
  21326. }
  21327. // restore GL state
  21328. var clearColor = _renderer.getClearColor(),
  21329. clearAlpha = _renderer.getClearAlpha();
  21330. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21331. _gl.enable( _gl.BLEND );
  21332. };
  21333. // For the moment just ignore objects that have multiple materials with different animation methods
  21334. // Only the first material will be taken into account for deciding which depth material to use
  21335. function getObjectMaterial( object ) {
  21336. return object.material instanceof THREE.MeshFaceMaterial
  21337. ? object.material.materials[ 0 ]
  21338. : object.material;
  21339. };
  21340. };
  21341. /**
  21342. * @author mikael emtinger / http://gomo.se/
  21343. *
  21344. */
  21345. THREE.ShaderFlares = {
  21346. 'lensFlareVertexTexture': {
  21347. vertexShader: [
  21348. "uniform vec3 screenPosition;",
  21349. "uniform vec2 scale;",
  21350. "uniform float rotation;",
  21351. "uniform int renderType;",
  21352. "uniform sampler2D occlusionMap;",
  21353. "attribute vec2 position;",
  21354. "attribute vec2 uv;",
  21355. "varying vec2 vUV;",
  21356. "varying float vVisibility;",
  21357. "void main() {",
  21358. "vUV = uv;",
  21359. "vec2 pos = position;",
  21360. "if( renderType == 2 ) {",
  21361. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21362. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21363. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21364. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21365. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21366. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21367. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21368. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21369. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21370. "vVisibility = ( visibility.r / 9.0 ) *",
  21371. "( 1.0 - visibility.g / 9.0 ) *",
  21372. "( visibility.b / 9.0 ) *",
  21373. "( 1.0 - visibility.a / 9.0 );",
  21374. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21375. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21376. "}",
  21377. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21378. "}"
  21379. ].join( "\n" ),
  21380. fragmentShader: [
  21381. "precision mediump float;",
  21382. "uniform sampler2D map;",
  21383. "uniform float opacity;",
  21384. "uniform int renderType;",
  21385. "uniform vec3 color;",
  21386. "varying vec2 vUV;",
  21387. "varying float vVisibility;",
  21388. "void main() {",
  21389. // pink square
  21390. "if( renderType == 0 ) {",
  21391. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21392. // restore
  21393. "} else if( renderType == 1 ) {",
  21394. "gl_FragColor = texture2D( map, vUV );",
  21395. // flare
  21396. "} else {",
  21397. "vec4 texture = texture2D( map, vUV );",
  21398. "texture.a *= opacity * vVisibility;",
  21399. "gl_FragColor = texture;",
  21400. "gl_FragColor.rgb *= color;",
  21401. "}",
  21402. "}"
  21403. ].join( "\n" )
  21404. },
  21405. 'lensFlare': {
  21406. vertexShader: [
  21407. "uniform vec3 screenPosition;",
  21408. "uniform vec2 scale;",
  21409. "uniform float rotation;",
  21410. "uniform int renderType;",
  21411. "attribute vec2 position;",
  21412. "attribute vec2 uv;",
  21413. "varying vec2 vUV;",
  21414. "void main() {",
  21415. "vUV = uv;",
  21416. "vec2 pos = position;",
  21417. "if( renderType == 2 ) {",
  21418. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21419. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21420. "}",
  21421. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21422. "}"
  21423. ].join( "\n" ),
  21424. fragmentShader: [
  21425. "precision mediump float;",
  21426. "uniform sampler2D map;",
  21427. "uniform sampler2D occlusionMap;",
  21428. "uniform float opacity;",
  21429. "uniform int renderType;",
  21430. "uniform vec3 color;",
  21431. "varying vec2 vUV;",
  21432. "void main() {",
  21433. // pink square
  21434. "if( renderType == 0 ) {",
  21435. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21436. // restore
  21437. "} else if( renderType == 1 ) {",
  21438. "gl_FragColor = texture2D( map, vUV );",
  21439. // flare
  21440. "} else {",
  21441. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21442. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21443. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21444. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21445. "visibility = ( 1.0 - visibility / 4.0 );",
  21446. "vec4 texture = texture2D( map, vUV );",
  21447. "texture.a *= opacity * visibility;",
  21448. "gl_FragColor = texture;",
  21449. "gl_FragColor.rgb *= color;",
  21450. "}",
  21451. "}"
  21452. ].join( "\n" )
  21453. }
  21454. };
  21455. /**
  21456. * @author mikael emtinger / http://gomo.se/
  21457. * @author alteredq / http://alteredqualia.com/
  21458. *
  21459. */
  21460. THREE.ShaderSprite = {
  21461. 'sprite': {
  21462. vertexShader: [
  21463. "uniform int useScreenCoordinates;",
  21464. "uniform int sizeAttenuation;",
  21465. "uniform vec3 screenPosition;",
  21466. "uniform mat4 modelViewMatrix;",
  21467. "uniform mat4 projectionMatrix;",
  21468. "uniform float rotation;",
  21469. "uniform vec2 scale;",
  21470. "uniform vec2 alignment;",
  21471. "uniform vec2 uvOffset;",
  21472. "uniform vec2 uvScale;",
  21473. "attribute vec2 position;",
  21474. "attribute vec2 uv;",
  21475. "varying vec2 vUV;",
  21476. "void main() {",
  21477. "vUV = uvOffset + uv * uvScale;",
  21478. "vec2 alignedPosition = position + alignment;",
  21479. "vec2 rotatedPosition;",
  21480. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21481. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21482. "vec4 finalPosition;",
  21483. "if( useScreenCoordinates != 0 ) {",
  21484. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21485. "} else {",
  21486. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21487. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21488. "}",
  21489. "gl_Position = finalPosition;",
  21490. "}"
  21491. ].join( "\n" ),
  21492. fragmentShader: [
  21493. "precision mediump float;",
  21494. "uniform vec3 color;",
  21495. "uniform sampler2D map;",
  21496. "uniform float opacity;",
  21497. "uniform int fogType;",
  21498. "uniform vec3 fogColor;",
  21499. "uniform float fogDensity;",
  21500. "uniform float fogNear;",
  21501. "uniform float fogFar;",
  21502. "uniform float alphaTest;",
  21503. "varying vec2 vUV;",
  21504. "void main() {",
  21505. "vec4 texture = texture2D( map, vUV );",
  21506. "if ( texture.a < alphaTest ) discard;",
  21507. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21508. "if ( fogType > 0 ) {",
  21509. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21510. "float fogFactor = 0.0;",
  21511. "if ( fogType == 1 ) {",
  21512. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21513. "} else {",
  21514. "const float LOG2 = 1.442695;",
  21515. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21516. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21517. "}",
  21518. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21519. "}",
  21520. "}"
  21521. ].join( "\n" )
  21522. }
  21523. };
粤ICP备19079148号