three.js 788 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '53' };
  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. // MATERIAL CONSTANTS
  53. // side
  54. THREE.FrontSide = 0;
  55. THREE.BackSide = 1;
  56. THREE.DoubleSide = 2;
  57. // shading
  58. THREE.NoShading = 0;
  59. THREE.FlatShading = 1;
  60. THREE.SmoothShading = 2;
  61. // colors
  62. THREE.NoColors = 0;
  63. THREE.FaceColors = 1;
  64. THREE.VertexColors = 2;
  65. // blending modes
  66. THREE.NoBlending = 0;
  67. THREE.NormalBlending = 1;
  68. THREE.AdditiveBlending = 2;
  69. THREE.SubtractiveBlending = 3;
  70. THREE.MultiplyBlending = 4;
  71. THREE.CustomBlending = 5;
  72. // custom blending equations
  73. // (numbers start from 100 not to clash with other
  74. // mappings to OpenGL constants defined in Texture.js)
  75. THREE.AddEquation = 100;
  76. THREE.SubtractEquation = 101;
  77. THREE.ReverseSubtractEquation = 102;
  78. // custom blending destination factors
  79. THREE.ZeroFactor = 200;
  80. THREE.OneFactor = 201;
  81. THREE.SrcColorFactor = 202;
  82. THREE.OneMinusSrcColorFactor = 203;
  83. THREE.SrcAlphaFactor = 204;
  84. THREE.OneMinusSrcAlphaFactor = 205;
  85. THREE.DstAlphaFactor = 206;
  86. THREE.OneMinusDstAlphaFactor = 207;
  87. // custom blending source factors
  88. //THREE.ZeroFactor = 200;
  89. //THREE.OneFactor = 201;
  90. //THREE.SrcAlphaFactor = 204;
  91. //THREE.OneMinusSrcAlphaFactor = 205;
  92. //THREE.DstAlphaFactor = 206;
  93. //THREE.OneMinusDstAlphaFactor = 207;
  94. THREE.DstColorFactor = 208;
  95. THREE.OneMinusDstColorFactor = 209;
  96. THREE.SrcAlphaSaturateFactor = 210;
  97. // TEXTURE CONSTANTS
  98. THREE.MultiplyOperation = 0;
  99. THREE.MixOperation = 1;
  100. THREE.AddOperation = 2;
  101. // Mapping modes
  102. THREE.UVMapping = function () {};
  103. THREE.CubeReflectionMapping = function () {};
  104. THREE.CubeRefractionMapping = function () {};
  105. THREE.SphericalReflectionMapping = function () {};
  106. THREE.SphericalRefractionMapping = function () {};
  107. // Wrapping modes
  108. THREE.RepeatWrapping = 1000;
  109. THREE.ClampToEdgeWrapping = 1001;
  110. THREE.MirroredRepeatWrapping = 1002;
  111. // Filters
  112. THREE.NearestFilter = 1003;
  113. THREE.NearestMipMapNearestFilter = 1004;
  114. THREE.NearestMipMapLinearFilter = 1005;
  115. THREE.LinearFilter = 1006;
  116. THREE.LinearMipMapNearestFilter = 1007;
  117. THREE.LinearMipMapLinearFilter = 1008;
  118. // Data types
  119. THREE.UnsignedByteType = 1009;
  120. THREE.ByteType = 1010;
  121. THREE.ShortType = 1011;
  122. THREE.UnsignedShortType = 1012;
  123. THREE.IntType = 1013;
  124. THREE.UnsignedIntType = 1014;
  125. THREE.FloatType = 1015;
  126. // Pixel types
  127. //THREE.UnsignedByteType = 1009;
  128. THREE.UnsignedShort4444Type = 1016;
  129. THREE.UnsignedShort5551Type = 1017;
  130. THREE.UnsignedShort565Type = 1018;
  131. // Pixel formats
  132. THREE.AlphaFormat = 1019;
  133. THREE.RGBFormat = 1020;
  134. THREE.RGBAFormat = 1021;
  135. THREE.LuminanceFormat = 1022;
  136. THREE.LuminanceAlphaFormat = 1023;
  137. // Compressed texture formats
  138. THREE.RGB_S3TC_DXT1_Format = 2001;
  139. THREE.RGBA_S3TC_DXT1_Format = 2002;
  140. THREE.RGBA_S3TC_DXT3_Format = 2003;
  141. THREE.RGBA_S3TC_DXT5_Format = 2004;
  142. /*
  143. // Potential future PVRTC compressed texture formats
  144. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  145. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  146. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  147. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  148. */
  149. /**
  150. * @author alteredq / http://alteredqualia.com/
  151. */
  152. THREE.Clock = function ( autoStart ) {
  153. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  154. this.startTime = 0;
  155. this.oldTime = 0;
  156. this.elapsedTime = 0;
  157. this.running = false;
  158. };
  159. THREE.Clock.prototype.start = function () {
  160. this.startTime = Date.now();
  161. this.oldTime = this.startTime;
  162. this.running = true;
  163. };
  164. THREE.Clock.prototype.stop = function () {
  165. this.getElapsedTime();
  166. this.running = false;
  167. };
  168. THREE.Clock.prototype.getElapsedTime = function () {
  169. this.elapsedTime += this.getDelta();
  170. return this.elapsedTime;
  171. };
  172. THREE.Clock.prototype.getDelta = function () {
  173. var diff = 0;
  174. if ( this.autoStart && ! this.running ) {
  175. this.start();
  176. }
  177. if ( this.running ) {
  178. var newTime = Date.now();
  179. diff = 0.001 * ( newTime - this.oldTime );
  180. this.oldTime = newTime;
  181. this.elapsedTime += diff;
  182. }
  183. return diff;
  184. };/**
  185. * @author mrdoob / http://mrdoob.com/
  186. */
  187. THREE.Color = function ( hex ) {
  188. if ( hex !== undefined ) this.setHex( hex );
  189. return this;
  190. };
  191. THREE.Color.prototype = {
  192. constructor: THREE.Color,
  193. r: 1, g: 1, b: 1,
  194. copy: function ( color ) {
  195. this.r = color.r;
  196. this.g = color.g;
  197. this.b = color.b;
  198. return this;
  199. },
  200. copyGammaToLinear: function ( color ) {
  201. this.r = color.r * color.r;
  202. this.g = color.g * color.g;
  203. this.b = color.b * color.b;
  204. return this;
  205. },
  206. copyLinearToGamma: function ( color ) {
  207. this.r = Math.sqrt( color.r );
  208. this.g = Math.sqrt( color.g );
  209. this.b = Math.sqrt( color.b );
  210. return this;
  211. },
  212. convertGammaToLinear: function () {
  213. var r = this.r, g = this.g, b = this.b;
  214. this.r = r * r;
  215. this.g = g * g;
  216. this.b = b * b;
  217. return this;
  218. },
  219. convertLinearToGamma: function () {
  220. this.r = Math.sqrt( this.r );
  221. this.g = Math.sqrt( this.g );
  222. this.b = Math.sqrt( this.b );
  223. return this;
  224. },
  225. setRGB: function ( r, g, b ) {
  226. this.r = r;
  227. this.g = g;
  228. this.b = b;
  229. return this;
  230. },
  231. setHSV: function ( h, s, v ) {
  232. // based on MochiKit implementation by Bob Ippolito
  233. // h,s,v ranges are < 0.0 - 1.0 >
  234. var i, f, p, q, t;
  235. if ( v === 0 ) {
  236. this.r = this.g = this.b = 0;
  237. } else {
  238. i = Math.floor( h * 6 );
  239. f = ( h * 6 ) - i;
  240. p = v * ( 1 - s );
  241. q = v * ( 1 - ( s * f ) );
  242. t = v * ( 1 - ( s * ( 1 - f ) ) );
  243. if ( i === 0 ) {
  244. this.r = v;
  245. this.g = t;
  246. this.b = p;
  247. } else if ( i === 1 ) {
  248. this.r = q;
  249. this.g = v;
  250. this.b = p;
  251. } else if ( i === 2 ) {
  252. this.r = p;
  253. this.g = v;
  254. this.b = t;
  255. } else if ( i === 3 ) {
  256. this.r = p;
  257. this.g = q;
  258. this.b = v;
  259. } else if ( i === 4 ) {
  260. this.r = t;
  261. this.g = p;
  262. this.b = v;
  263. } else if ( i === 5 ) {
  264. this.r = v;
  265. this.g = p;
  266. this.b = q;
  267. }
  268. }
  269. return this;
  270. },
  271. getHex: function () {
  272. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  273. },
  274. setHex: function ( hex ) {
  275. hex = Math.floor( hex );
  276. this.r = ( hex >> 16 & 255 ) / 255;
  277. this.g = ( hex >> 8 & 255 ) / 255;
  278. this.b = ( hex & 255 ) / 255;
  279. return this;
  280. },
  281. getHexString: function () {
  282. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  283. },
  284. getContextStyle: function () {
  285. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  286. },
  287. setContextStyle: function ( style ) {
  288. var color = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/i.exec( style );
  289. this.r = parseInt( color[ 1 ], 10 ) / 255;
  290. this.g = parseInt( color[ 2 ], 10 ) / 255;
  291. this.b = parseInt( color[ 3 ], 10 ) / 255;
  292. return this;
  293. },
  294. getHSV: function ( hsv ) {
  295. // based on MochiKit implementation by Bob Ippolito
  296. // h,s,v ranges are < 0.0 - 1.0 >
  297. var r = this.r;
  298. var g = this.g;
  299. var b = this.b;
  300. var max = Math.max( Math.max( r, g ), b );
  301. var min = Math.min( Math.min( r, g ), b );
  302. var hue;
  303. var saturation;
  304. var value = max;
  305. if ( min === max ) {
  306. hue = 0;
  307. saturation = 0;
  308. } else {
  309. var delta = ( max - min );
  310. saturation = delta / max;
  311. if ( r === max ) {
  312. hue = ( g - b ) / delta;
  313. } else if ( g === max ) {
  314. hue = 2 + ( ( b - r ) / delta );
  315. } else {
  316. hue = 4 + ( ( r - g ) / delta );
  317. }
  318. hue /= 6;
  319. if ( hue < 0 ) {
  320. hue += 1;
  321. }
  322. if ( hue > 1 ) {
  323. hue -= 1;
  324. }
  325. }
  326. if ( hsv === undefined ) {
  327. hsv = { h: 0, s: 0, v: 0 };
  328. }
  329. hsv.h = hue;
  330. hsv.s = saturation;
  331. hsv.v = value;
  332. return hsv;
  333. },
  334. lerpSelf: function ( color, alpha ) {
  335. this.r += ( color.r - this.r ) * alpha;
  336. this.g += ( color.g - this.g ) * alpha;
  337. this.b += ( color.b - this.b ) * alpha;
  338. return this;
  339. },
  340. clone: function () {
  341. return new THREE.Color().setRGB( this.r, this.g, this.b );
  342. }
  343. };
  344. /**
  345. * @author mrdoob / http://mrdoob.com/
  346. * @author philogb / http://blog.thejit.org/
  347. * @author egraether / http://egraether.com/
  348. * @author zz85 / http://www.lab4games.net/zz85/blog
  349. */
  350. THREE.Vector2 = function ( x, y ) {
  351. this.x = x || 0;
  352. this.y = y || 0;
  353. };
  354. THREE.Vector2.prototype = {
  355. constructor: THREE.Vector2,
  356. set: function ( x, y ) {
  357. this.x = x;
  358. this.y = y;
  359. return this;
  360. },
  361. copy: function ( v ) {
  362. this.x = v.x;
  363. this.y = v.y;
  364. return this;
  365. },
  366. add: function ( a, b ) {
  367. this.x = a.x + b.x;
  368. this.y = a.y + b.y;
  369. return this;
  370. },
  371. addSelf: function ( v ) {
  372. this.x += v.x;
  373. this.y += v.y;
  374. return this;
  375. },
  376. sub: function ( a, b ) {
  377. this.x = a.x - b.x;
  378. this.y = a.y - b.y;
  379. return this;
  380. },
  381. subSelf: function ( v ) {
  382. this.x -= v.x;
  383. this.y -= v.y;
  384. return this;
  385. },
  386. multiplyScalar: function ( s ) {
  387. this.x *= s;
  388. this.y *= s;
  389. return this;
  390. },
  391. divideScalar: function ( s ) {
  392. if ( s ) {
  393. this.x /= s;
  394. this.y /= s;
  395. } else {
  396. this.set( 0, 0 );
  397. }
  398. return this;
  399. },
  400. negate: function() {
  401. return this.multiplyScalar( - 1 );
  402. },
  403. dot: function ( v ) {
  404. return this.x * v.x + this.y * v.y;
  405. },
  406. lengthSq: function () {
  407. return this.x * this.x + this.y * this.y;
  408. },
  409. length: function () {
  410. return Math.sqrt( this.lengthSq() );
  411. },
  412. normalize: function () {
  413. return this.divideScalar( this.length() );
  414. },
  415. distanceTo: function ( v ) {
  416. return Math.sqrt( this.distanceToSquared( v ) );
  417. },
  418. distanceToSquared: function ( v ) {
  419. var dx = this.x - v.x, dy = this.y - v.y;
  420. return dx * dx + dy * dy;
  421. },
  422. setLength: function ( l ) {
  423. return this.normalize().multiplyScalar( l );
  424. },
  425. lerpSelf: function ( v, alpha ) {
  426. this.x += ( v.x - this.x ) * alpha;
  427. this.y += ( v.y - this.y ) * alpha;
  428. return this;
  429. },
  430. equals: function( v ) {
  431. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  432. },
  433. clone: function () {
  434. return new THREE.Vector2( this.x, this.y );
  435. }
  436. };
  437. /**
  438. * @author mrdoob / http://mrdoob.com/
  439. * @author kile / http://kile.stravaganza.org/
  440. * @author philogb / http://blog.thejit.org/
  441. * @author mikael emtinger / http://gomo.se/
  442. * @author egraether / http://egraether.com/
  443. * @author WestLangley / http://github.com/WestLangley
  444. */
  445. THREE.Vector3 = function ( x, y, z ) {
  446. this.x = x || 0;
  447. this.y = y || 0;
  448. this.z = z || 0;
  449. };
  450. THREE.Vector3.prototype = {
  451. constructor: THREE.Vector3,
  452. set: function ( x, y, z ) {
  453. this.x = x;
  454. this.y = y;
  455. this.z = z;
  456. return this;
  457. },
  458. setX: function ( x ) {
  459. this.x = x;
  460. return this;
  461. },
  462. setY: function ( y ) {
  463. this.y = y;
  464. return this;
  465. },
  466. setZ: function ( z ) {
  467. this.z = z;
  468. return this;
  469. },
  470. copy: function ( v ) {
  471. this.x = v.x;
  472. this.y = v.y;
  473. this.z = v.z;
  474. return this;
  475. },
  476. add: function ( a, b ) {
  477. this.x = a.x + b.x;
  478. this.y = a.y + b.y;
  479. this.z = a.z + b.z;
  480. return this;
  481. },
  482. addSelf: function ( v ) {
  483. this.x += v.x;
  484. this.y += v.y;
  485. this.z += v.z;
  486. return this;
  487. },
  488. addScalar: function ( s ) {
  489. this.x += s;
  490. this.y += s;
  491. this.z += s;
  492. return this;
  493. },
  494. sub: function ( a, b ) {
  495. this.x = a.x - b.x;
  496. this.y = a.y - b.y;
  497. this.z = a.z - b.z;
  498. return this;
  499. },
  500. subSelf: function ( v ) {
  501. this.x -= v.x;
  502. this.y -= v.y;
  503. this.z -= v.z;
  504. return this;
  505. },
  506. multiply: function ( a, b ) {
  507. this.x = a.x * b.x;
  508. this.y = a.y * b.y;
  509. this.z = a.z * b.z;
  510. return this;
  511. },
  512. multiplySelf: function ( v ) {
  513. this.x *= v.x;
  514. this.y *= v.y;
  515. this.z *= v.z;
  516. return this;
  517. },
  518. multiplyScalar: function ( s ) {
  519. this.x *= s;
  520. this.y *= s;
  521. this.z *= s;
  522. return this;
  523. },
  524. divideSelf: function ( v ) {
  525. this.x /= v.x;
  526. this.y /= v.y;
  527. this.z /= v.z;
  528. return this;
  529. },
  530. divideScalar: function ( s ) {
  531. if ( s ) {
  532. this.x /= s;
  533. this.y /= s;
  534. this.z /= s;
  535. } else {
  536. this.x = 0;
  537. this.y = 0;
  538. this.z = 0;
  539. }
  540. return this;
  541. },
  542. negate: function() {
  543. return this.multiplyScalar( - 1 );
  544. },
  545. dot: function ( v ) {
  546. return this.x * v.x + this.y * v.y + this.z * v.z;
  547. },
  548. lengthSq: function () {
  549. return this.x * this.x + this.y * this.y + this.z * this.z;
  550. },
  551. length: function () {
  552. return Math.sqrt( this.lengthSq() );
  553. },
  554. lengthManhattan: function () {
  555. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  556. },
  557. normalize: function () {
  558. return this.divideScalar( this.length() );
  559. },
  560. setLength: function ( l ) {
  561. return this.normalize().multiplyScalar( l );
  562. },
  563. lerpSelf: function ( v, alpha ) {
  564. this.x += ( v.x - this.x ) * alpha;
  565. this.y += ( v.y - this.y ) * alpha;
  566. this.z += ( v.z - this.z ) * alpha;
  567. return this;
  568. },
  569. cross: function ( a, b ) {
  570. this.x = a.y * b.z - a.z * b.y;
  571. this.y = a.z * b.x - a.x * b.z;
  572. this.z = a.x * b.y - a.y * b.x;
  573. return this;
  574. },
  575. crossSelf: function ( v ) {
  576. var x = this.x, y = this.y, z = this.z;
  577. this.x = y * v.z - z * v.y;
  578. this.y = z * v.x - x * v.z;
  579. this.z = x * v.y - y * v.x;
  580. return this;
  581. },
  582. angleTo: function ( v ) {
  583. return Math.acos( this.dot( v ) / this.length() / v.length() );
  584. },
  585. distanceTo: function ( v ) {
  586. return Math.sqrt( this.distanceToSquared( v ) );
  587. },
  588. distanceToSquared: function ( v ) {
  589. return new THREE.Vector3().sub( this, v ).lengthSq();
  590. },
  591. getPositionFromMatrix: function ( m ) {
  592. this.x = m.elements[12];
  593. this.y = m.elements[13];
  594. this.z = m.elements[14];
  595. return this;
  596. },
  597. setEulerFromRotationMatrix: function ( m, order ) {
  598. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  599. // clamp, to handle numerical problems
  600. function clamp( x ) {
  601. return Math.min( Math.max( x, -1 ), 1 );
  602. }
  603. var te = m.elements;
  604. var m11 = te[0], m12 = te[4], m13 = te[8];
  605. var m21 = te[1], m22 = te[5], m23 = te[9];
  606. var m31 = te[2], m32 = te[6], m33 = te[10];
  607. if ( order === undefined || order === 'XYZ' ) {
  608. this.y = Math.asin( clamp( m13 ) );
  609. if ( Math.abs( m13 ) < 0.99999 ) {
  610. this.x = Math.atan2( - m23, m33 );
  611. this.z = Math.atan2( - m12, m11 );
  612. } else {
  613. this.x = Math.atan2( m32, m22 );
  614. this.z = 0;
  615. }
  616. } else if ( order === 'YXZ' ) {
  617. this.x = Math.asin( - clamp( m23 ) );
  618. if ( Math.abs( m23 ) < 0.99999 ) {
  619. this.y = Math.atan2( m13, m33 );
  620. this.z = Math.atan2( m21, m22 );
  621. } else {
  622. this.y = Math.atan2( - m31, m11 );
  623. this.z = 0;
  624. }
  625. } else if ( order === 'ZXY' ) {
  626. this.x = Math.asin( clamp( m32 ) );
  627. if ( Math.abs( m32 ) < 0.99999 ) {
  628. this.y = Math.atan2( - m31, m33 );
  629. this.z = Math.atan2( - m12, m22 );
  630. } else {
  631. this.y = 0;
  632. this.z = Math.atan2( m21, m11 );
  633. }
  634. } else if ( order === 'ZYX' ) {
  635. this.y = Math.asin( - clamp( m31 ) );
  636. if ( Math.abs( m31 ) < 0.99999 ) {
  637. this.x = Math.atan2( m32, m33 );
  638. this.z = Math.atan2( m21, m11 );
  639. } else {
  640. this.x = 0;
  641. this.z = Math.atan2( - m12, m22 );
  642. }
  643. } else if ( order === 'YZX' ) {
  644. this.z = Math.asin( clamp( m21 ) );
  645. if ( Math.abs( m21 ) < 0.99999 ) {
  646. this.x = Math.atan2( - m23, m22 );
  647. this.y = Math.atan2( - m31, m11 );
  648. } else {
  649. this.x = 0;
  650. this.y = Math.atan2( m13, m33 );
  651. }
  652. } else if ( order === 'XZY' ) {
  653. this.z = Math.asin( - clamp( m12 ) );
  654. if ( Math.abs( m12 ) < 0.99999 ) {
  655. this.x = Math.atan2( m32, m22 );
  656. this.y = Math.atan2( m13, m11 );
  657. } else {
  658. this.x = Math.atan2( - m23, m33 );
  659. this.y = 0;
  660. }
  661. }
  662. return this;
  663. },
  664. setEulerFromQuaternion: function ( q, order ) {
  665. // q is assumed to be normalized
  666. // clamp, to handle numerical problems
  667. function clamp( x ) {
  668. return Math.min( Math.max( x, -1 ), 1 );
  669. }
  670. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  671. var sqx = q.x * q.x;
  672. var sqy = q.y * q.y;
  673. var sqz = q.z * q.z;
  674. var sqw = q.w * q.w;
  675. if ( order === undefined || order === 'XYZ' ) {
  676. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  677. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  678. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  679. } else if ( order === 'YXZ' ) {
  680. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  681. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  682. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  683. } else if ( order === 'ZXY' ) {
  684. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  685. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  686. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  687. } else if ( order === 'ZYX' ) {
  688. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  689. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  690. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  691. } else if ( order === 'YZX' ) {
  692. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  693. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  694. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  695. } else if ( order === 'XZY' ) {
  696. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  697. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  698. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  699. }
  700. return this;
  701. },
  702. getScaleFromMatrix: function ( m ) {
  703. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  704. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  705. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  706. this.x = sx;
  707. this.y = sy;
  708. this.z = sz;
  709. return this;
  710. },
  711. equals: function ( v ) {
  712. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  713. },
  714. clone: function () {
  715. return new THREE.Vector3( this.x, this.y, this.z );
  716. }
  717. };
  718. /**
  719. * @author supereggbert / http://www.paulbrunt.co.uk/
  720. * @author philogb / http://blog.thejit.org/
  721. * @author mikael emtinger / http://gomo.se/
  722. * @author egraether / http://egraether.com/
  723. * @author WestLangley / http://github.com/WestLangley
  724. */
  725. THREE.Vector4 = function ( x, y, z, w ) {
  726. this.x = x || 0;
  727. this.y = y || 0;
  728. this.z = z || 0;
  729. this.w = ( w !== undefined ) ? w : 1;
  730. };
  731. THREE.Vector4.prototype = {
  732. constructor: THREE.Vector4,
  733. set: function ( x, y, z, w ) {
  734. this.x = x;
  735. this.y = y;
  736. this.z = z;
  737. this.w = w;
  738. return this;
  739. },
  740. copy: function ( v ) {
  741. this.x = v.x;
  742. this.y = v.y;
  743. this.z = v.z;
  744. this.w = ( v.w !== undefined ) ? v.w : 1;
  745. return this;
  746. },
  747. add: function ( a, b ) {
  748. this.x = a.x + b.x;
  749. this.y = a.y + b.y;
  750. this.z = a.z + b.z;
  751. this.w = a.w + b.w;
  752. return this;
  753. },
  754. addSelf: function ( v ) {
  755. this.x += v.x;
  756. this.y += v.y;
  757. this.z += v.z;
  758. this.w += v.w;
  759. return this;
  760. },
  761. sub: function ( a, b ) {
  762. this.x = a.x - b.x;
  763. this.y = a.y - b.y;
  764. this.z = a.z - b.z;
  765. this.w = a.w - b.w;
  766. return this;
  767. },
  768. subSelf: function ( v ) {
  769. this.x -= v.x;
  770. this.y -= v.y;
  771. this.z -= v.z;
  772. this.w -= v.w;
  773. return this;
  774. },
  775. multiplyScalar: function ( s ) {
  776. this.x *= s;
  777. this.y *= s;
  778. this.z *= s;
  779. this.w *= s;
  780. return this;
  781. },
  782. divideScalar: function ( s ) {
  783. if ( s ) {
  784. this.x /= s;
  785. this.y /= s;
  786. this.z /= s;
  787. this.w /= s;
  788. } else {
  789. this.x = 0;
  790. this.y = 0;
  791. this.z = 0;
  792. this.w = 1;
  793. }
  794. return this;
  795. },
  796. negate: function() {
  797. return this.multiplyScalar( -1 );
  798. },
  799. dot: function ( v ) {
  800. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  801. },
  802. lengthSq: function () {
  803. return this.dot( this );
  804. },
  805. length: function () {
  806. return Math.sqrt( this.lengthSq() );
  807. },
  808. lengthManhattan: function () {
  809. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  810. },
  811. normalize: function () {
  812. return this.divideScalar( this.length() );
  813. },
  814. setLength: function ( l ) {
  815. return this.normalize().multiplyScalar( l );
  816. },
  817. lerpSelf: function ( v, alpha ) {
  818. this.x += ( v.x - this.x ) * alpha;
  819. this.y += ( v.y - this.y ) * alpha;
  820. this.z += ( v.z - this.z ) * alpha;
  821. this.w += ( v.w - this.w ) * alpha;
  822. return this;
  823. },
  824. clone: function () {
  825. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  826. },
  827. setAxisAngleFromQuaternion: function ( q ) {
  828. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  829. // q is assumed to be normalized
  830. this.w = 2 * Math.acos( q.w );
  831. var s = Math.sqrt( 1 - q.w * q.w );
  832. if ( s < 0.0001 ) {
  833. this.x = 1;
  834. this.y = 0;
  835. this.z = 0;
  836. } else {
  837. this.x = q.x / s;
  838. this.y = q.y / s;
  839. this.z = q.z / s;
  840. }
  841. return this;
  842. },
  843. setAxisAngleFromRotationMatrix: function ( m ) {
  844. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  845. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  846. var angle, x, y, z, // variables for result
  847. epsilon = 0.01, // margin to allow for rounding errors
  848. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  849. te = m.elements,
  850. m11 = te[0], m12 = te[4], m13 = te[8],
  851. m21 = te[1], m22 = te[5], m23 = te[9],
  852. m31 = te[2], m32 = te[6], m33 = te[10];
  853. if ( ( Math.abs( m12 - m21 ) < epsilon )
  854. && ( Math.abs( m13 - m31 ) < epsilon )
  855. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  856. // singularity found
  857. // first check for identity matrix which must have +1 for all terms
  858. // in leading diagonal and zero in other terms
  859. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  860. && ( Math.abs( m13 + m31 ) < epsilon2 )
  861. && ( Math.abs( m23 + m32 ) < epsilon2 )
  862. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  863. // this singularity is identity matrix so angle = 0
  864. this.set( 1, 0, 0, 0 );
  865. return this; // zero angle, arbitrary axis
  866. }
  867. // otherwise this singularity is angle = 180
  868. angle = Math.PI;
  869. var xx = ( m11 + 1 ) / 2;
  870. var yy = ( m22 + 1 ) / 2;
  871. var zz = ( m33 + 1 ) / 2;
  872. var xy = ( m12 + m21 ) / 4;
  873. var xz = ( m13 + m31 ) / 4;
  874. var yz = ( m23 + m32 ) / 4;
  875. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  876. if ( xx < epsilon ) {
  877. x = 0;
  878. y = 0.707106781;
  879. z = 0.707106781;
  880. } else {
  881. x = Math.sqrt( xx );
  882. y = xy / x;
  883. z = xz / x;
  884. }
  885. } else if ( yy > zz ) { // m22 is the largest diagonal term
  886. if ( yy < epsilon ) {
  887. x = 0.707106781;
  888. y = 0;
  889. z = 0.707106781;
  890. } else {
  891. y = Math.sqrt( yy );
  892. x = xy / y;
  893. z = yz / y;
  894. }
  895. } else { // m33 is the largest diagonal term so base result on this
  896. if ( zz < epsilon ) {
  897. x = 0.707106781;
  898. y = 0.707106781;
  899. z = 0;
  900. } else {
  901. z = Math.sqrt( zz );
  902. x = xz / z;
  903. y = yz / z;
  904. }
  905. }
  906. this.set( x, y, z, angle );
  907. return this; // return 180 deg rotation
  908. }
  909. // as we have reached here there are no singularities so we can handle normally
  910. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  911. + ( m13 - m31 ) * ( m13 - m31 )
  912. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  913. if ( Math.abs( s ) < 0.001 ) s = 1;
  914. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  915. // caught by singularity test above, but I've left it in just in case
  916. this.x = ( m32 - m23 ) / s;
  917. this.y = ( m13 - m31 ) / s;
  918. this.z = ( m21 - m12 ) / s;
  919. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  920. return this;
  921. }
  922. };
  923. /**
  924. * @author alteredq / http://alteredqualia.com/
  925. * @author WestLangley / http://github.com/WestLangley
  926. */
  927. THREE.Matrix3 = function () {
  928. this.elements = new Float32Array(9);
  929. };
  930. THREE.Matrix3.prototype = {
  931. constructor: THREE.Matrix3,
  932. multiplyVector3: function ( v ) {
  933. var te = this.elements;
  934. var vx = v.x, vy = v.y, vz = v.z;
  935. v.x = te[0] * vx + te[3] * vy + te[6] * vz;
  936. v.y = te[1] * vx + te[4] * vy + te[7] * vz;
  937. v.z = te[2] * vx + te[5] * vy + te[8] * vz;
  938. return v;
  939. },
  940. multiplyVector3Array: function ( a ) {
  941. var tmp = THREE.Matrix3.__v1;
  942. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  943. tmp.x = a[ i ];
  944. tmp.y = a[ i + 1 ];
  945. tmp.z = a[ i + 2 ];
  946. this.multiplyVector3( tmp );
  947. a[ i ] = tmp.x;
  948. a[ i + 1 ] = tmp.y;
  949. a[ i + 2 ] = tmp.z;
  950. }
  951. return a;
  952. },
  953. getInverse: function ( matrix ) {
  954. // input: THREE.Matrix4
  955. // ( based on http://code.google.com/p/webgl-mjs/ )
  956. var me = matrix.elements;
  957. var a11 = me[10] * me[5] - me[6] * me[9];
  958. var a21 = - me[10] * me[1] + me[2] * me[9];
  959. var a31 = me[6] * me[1] - me[2] * me[5];
  960. var a12 = - me[10] * me[4] + me[6] * me[8];
  961. var a22 = me[10] * me[0] - me[2] * me[8];
  962. var a32 = - me[6] * me[0] + me[2] * me[4];
  963. var a13 = me[9] * me[4] - me[5] * me[8];
  964. var a23 = - me[9] * me[0] + me[1] * me[8];
  965. var a33 = me[5] * me[0] - me[1] * me[4];
  966. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  967. // no inverse
  968. if ( det === 0 ) {
  969. console.warn( "Matrix3.getInverse(): determinant == 0" );
  970. }
  971. var idet = 1.0 / det;
  972. var m = this.elements;
  973. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  974. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  975. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  976. return this;
  977. },
  978. transpose: function () {
  979. var tmp, m = this.elements;
  980. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  981. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  982. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  983. return this;
  984. },
  985. transposeIntoArray: function ( r ) {
  986. var m = this.m;
  987. r[ 0 ] = m[ 0 ];
  988. r[ 1 ] = m[ 3 ];
  989. r[ 2 ] = m[ 6 ];
  990. r[ 3 ] = m[ 1 ];
  991. r[ 4 ] = m[ 4 ];
  992. r[ 5 ] = m[ 7 ];
  993. r[ 6 ] = m[ 2 ];
  994. r[ 7 ] = m[ 5 ];
  995. r[ 8 ] = m[ 8 ];
  996. return this;
  997. }
  998. };
  999. THREE.Matrix3.__v1 = new THREE.Vector3();/**
  1000. * @author mrdoob / http://mrdoob.com/
  1001. * @author supereggbert / http://www.paulbrunt.co.uk/
  1002. * @author philogb / http://blog.thejit.org/
  1003. * @author jordi_ros / http://plattsoft.com
  1004. * @author D1plo1d / http://github.com/D1plo1d
  1005. * @author alteredq / http://alteredqualia.com/
  1006. * @author mikael emtinger / http://gomo.se/
  1007. * @author timknip / http://www.floorplanner.com/
  1008. */
  1009. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1010. this.elements = new Float32Array( 16 );
  1011. this.set(
  1012. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1013. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1014. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1015. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1016. );
  1017. };
  1018. THREE.Matrix4.prototype = {
  1019. constructor: THREE.Matrix4,
  1020. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1021. var te = this.elements;
  1022. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1023. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1024. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1025. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1026. return this;
  1027. },
  1028. identity: function () {
  1029. this.set(
  1030. 1, 0, 0, 0,
  1031. 0, 1, 0, 0,
  1032. 0, 0, 1, 0,
  1033. 0, 0, 0, 1
  1034. );
  1035. return this;
  1036. },
  1037. copy: function ( m ) {
  1038. var me = m.elements;
  1039. this.set(
  1040. me[0], me[4], me[8], me[12],
  1041. me[1], me[5], me[9], me[13],
  1042. me[2], me[6], me[10], me[14],
  1043. me[3], me[7], me[11], me[15]
  1044. );
  1045. return this;
  1046. },
  1047. lookAt: function ( eye, target, up ) {
  1048. var te = this.elements;
  1049. var x = THREE.Matrix4.__v1;
  1050. var y = THREE.Matrix4.__v2;
  1051. var z = THREE.Matrix4.__v3;
  1052. z.sub( eye, target ).normalize();
  1053. if ( z.length() === 0 ) {
  1054. z.z = 1;
  1055. }
  1056. x.cross( up, z ).normalize();
  1057. if ( x.length() === 0 ) {
  1058. z.x += 0.0001;
  1059. x.cross( up, z ).normalize();
  1060. }
  1061. y.cross( z, x );
  1062. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1063. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1064. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1065. return this;
  1066. },
  1067. multiply: function ( a, b ) {
  1068. var ae = a.elements;
  1069. var be = b.elements;
  1070. var te = this.elements;
  1071. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1072. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1073. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1074. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1075. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1076. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1077. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1078. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1079. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1080. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1081. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1082. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1083. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1084. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1085. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1086. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1087. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1088. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1089. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1090. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1091. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1092. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1093. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1094. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1095. return this;
  1096. },
  1097. multiplySelf: function ( m ) {
  1098. return this.multiply( this, m );
  1099. },
  1100. multiplyToArray: function ( a, b, r ) {
  1101. var te = this.elements;
  1102. this.multiply( a, b );
  1103. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1104. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1105. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1106. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1107. return this;
  1108. },
  1109. multiplyScalar: function ( s ) {
  1110. var te = this.elements;
  1111. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1112. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1113. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1114. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1115. return this;
  1116. },
  1117. multiplyVector3: function ( v ) {
  1118. var te = this.elements;
  1119. var vx = v.x, vy = v.y, vz = v.z;
  1120. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1121. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1122. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1123. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1124. return v;
  1125. },
  1126. multiplyVector4: function ( v ) {
  1127. var te = this.elements;
  1128. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1129. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1130. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1131. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1132. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1133. return v;
  1134. },
  1135. multiplyVector3Array: function ( a ) {
  1136. var tmp = THREE.Matrix4.__v1;
  1137. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1138. tmp.x = a[ i ];
  1139. tmp.y = a[ i + 1 ];
  1140. tmp.z = a[ i + 2 ];
  1141. this.multiplyVector3( tmp );
  1142. a[ i ] = tmp.x;
  1143. a[ i + 1 ] = tmp.y;
  1144. a[ i + 2 ] = tmp.z;
  1145. }
  1146. return a;
  1147. },
  1148. rotateAxis: function ( v ) {
  1149. var te = this.elements;
  1150. var vx = v.x, vy = v.y, vz = v.z;
  1151. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1152. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1153. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1154. v.normalize();
  1155. return v;
  1156. },
  1157. crossVector: function ( a ) {
  1158. var te = this.elements;
  1159. var v = new THREE.Vector4();
  1160. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1161. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1162. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1163. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1164. return v;
  1165. },
  1166. determinant: function () {
  1167. var te = this.elements;
  1168. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1169. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1170. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1171. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1172. //TODO: make this more efficient
  1173. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1174. return (
  1175. n14 * n23 * n32 * n41-
  1176. n13 * n24 * n32 * n41-
  1177. n14 * n22 * n33 * n41+
  1178. n12 * n24 * n33 * n41+
  1179. n13 * n22 * n34 * n41-
  1180. n12 * n23 * n34 * n41-
  1181. n14 * n23 * n31 * n42+
  1182. n13 * n24 * n31 * n42+
  1183. n14 * n21 * n33 * n42-
  1184. n11 * n24 * n33 * n42-
  1185. n13 * n21 * n34 * n42+
  1186. n11 * n23 * n34 * n42+
  1187. n14 * n22 * n31 * n43-
  1188. n12 * n24 * n31 * n43-
  1189. n14 * n21 * n32 * n43+
  1190. n11 * n24 * n32 * n43+
  1191. n12 * n21 * n34 * n43-
  1192. n11 * n22 * n34 * n43-
  1193. n13 * n22 * n31 * n44+
  1194. n12 * n23 * n31 * n44+
  1195. n13 * n21 * n32 * n44-
  1196. n11 * n23 * n32 * n44-
  1197. n12 * n21 * n33 * n44+
  1198. n11 * n22 * n33 * n44
  1199. );
  1200. },
  1201. transpose: function () {
  1202. var te = this.elements;
  1203. var tmp;
  1204. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1205. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1206. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1207. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1208. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1209. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1210. return this;
  1211. },
  1212. flattenToArray: function ( flat ) {
  1213. var te = this.elements;
  1214. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1215. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1216. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1217. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1218. return flat;
  1219. },
  1220. flattenToArrayOffset: function( flat, offset ) {
  1221. var te = this.elements;
  1222. flat[ offset ] = te[0];
  1223. flat[ offset + 1 ] = te[1];
  1224. flat[ offset + 2 ] = te[2];
  1225. flat[ offset + 3 ] = te[3];
  1226. flat[ offset + 4 ] = te[4];
  1227. flat[ offset + 5 ] = te[5];
  1228. flat[ offset + 6 ] = te[6];
  1229. flat[ offset + 7 ] = te[7];
  1230. flat[ offset + 8 ] = te[8];
  1231. flat[ offset + 9 ] = te[9];
  1232. flat[ offset + 10 ] = te[10];
  1233. flat[ offset + 11 ] = te[11];
  1234. flat[ offset + 12 ] = te[12];
  1235. flat[ offset + 13 ] = te[13];
  1236. flat[ offset + 14 ] = te[14];
  1237. flat[ offset + 15 ] = te[15];
  1238. return flat;
  1239. },
  1240. getPosition: function () {
  1241. var te = this.elements;
  1242. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1243. },
  1244. setPosition: function ( v ) {
  1245. var te = this.elements;
  1246. te[12] = v.x;
  1247. te[13] = v.y;
  1248. te[14] = v.z;
  1249. return this;
  1250. },
  1251. getColumnX: function () {
  1252. var te = this.elements;
  1253. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1254. },
  1255. getColumnY: function () {
  1256. var te = this.elements;
  1257. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1258. },
  1259. getColumnZ: function() {
  1260. var te = this.elements;
  1261. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1262. },
  1263. getInverse: function ( m ) {
  1264. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1265. var te = this.elements;
  1266. var me = m.elements;
  1267. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1268. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1269. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1270. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1271. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1272. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1273. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1274. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1275. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1276. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1277. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1278. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1279. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1280. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1281. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1282. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1283. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1284. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1285. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1286. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1287. this.multiplyScalar( 1 / m.determinant() );
  1288. return this;
  1289. },
  1290. setRotationFromEuler: function ( v, order ) {
  1291. var te = this.elements;
  1292. var x = v.x, y = v.y, z = v.z;
  1293. var a = Math.cos( x ), b = Math.sin( x );
  1294. var c = Math.cos( y ), d = Math.sin( y );
  1295. var e = Math.cos( z ), f = Math.sin( z );
  1296. if ( order === undefined || order === 'XYZ' ) {
  1297. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1298. te[0] = c * e;
  1299. te[4] = - c * f;
  1300. te[8] = d;
  1301. te[1] = af + be * d;
  1302. te[5] = ae - bf * d;
  1303. te[9] = - b * c;
  1304. te[2] = bf - ae * d;
  1305. te[6] = be + af * d;
  1306. te[10] = a * c;
  1307. } else if ( order === 'YXZ' ) {
  1308. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1309. te[0] = ce + df * b;
  1310. te[4] = de * b - cf;
  1311. te[8] = a * d;
  1312. te[1] = a * f;
  1313. te[5] = a * e;
  1314. te[9] = - b;
  1315. te[2] = cf * b - de;
  1316. te[6] = df + ce * b;
  1317. te[10] = a * c;
  1318. } else if ( order === 'ZXY' ) {
  1319. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1320. te[0] = ce - df * b;
  1321. te[4] = - a * f;
  1322. te[8] = de + cf * b;
  1323. te[1] = cf + de * b;
  1324. te[5] = a * e;
  1325. te[9] = df - ce * b;
  1326. te[2] = - a * d;
  1327. te[6] = b;
  1328. te[10] = a * c;
  1329. } else if ( order === 'ZYX' ) {
  1330. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1331. te[0] = c * e;
  1332. te[4] = be * d - af;
  1333. te[8] = ae * d + bf;
  1334. te[1] = c * f;
  1335. te[5] = bf * d + ae;
  1336. te[9] = af * d - be;
  1337. te[2] = - d;
  1338. te[6] = b * c;
  1339. te[10] = a * c;
  1340. } else if ( order === 'YZX' ) {
  1341. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1342. te[0] = c * e;
  1343. te[4] = bd - ac * f;
  1344. te[8] = bc * f + ad;
  1345. te[1] = f;
  1346. te[5] = a * e;
  1347. te[9] = - b * e;
  1348. te[2] = - d * e;
  1349. te[6] = ad * f + bc;
  1350. te[10] = ac - bd * f;
  1351. } else if ( order === 'XZY' ) {
  1352. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1353. te[0] = c * e;
  1354. te[4] = - f;
  1355. te[8] = d * e;
  1356. te[1] = ac * f + bd;
  1357. te[5] = a * e;
  1358. te[9] = ad * f - bc;
  1359. te[2] = bc * f - ad;
  1360. te[6] = b * e;
  1361. te[10] = bd * f + ac;
  1362. }
  1363. return this;
  1364. },
  1365. setRotationFromQuaternion: function ( q ) {
  1366. var te = this.elements;
  1367. var x = q.x, y = q.y, z = q.z, w = q.w;
  1368. var x2 = x + x, y2 = y + y, z2 = z + z;
  1369. var xx = x * x2, xy = x * y2, xz = x * z2;
  1370. var yy = y * y2, yz = y * z2, zz = z * z2;
  1371. var wx = w * x2, wy = w * y2, wz = w * z2;
  1372. te[0] = 1 - ( yy + zz );
  1373. te[4] = xy - wz;
  1374. te[8] = xz + wy;
  1375. te[1] = xy + wz;
  1376. te[5] = 1 - ( xx + zz );
  1377. te[9] = yz - wx;
  1378. te[2] = xz - wy;
  1379. te[6] = yz + wx;
  1380. te[10] = 1 - ( xx + yy );
  1381. return this;
  1382. },
  1383. compose: function ( translation, rotation, scale ) {
  1384. var te = this.elements;
  1385. var mRotation = THREE.Matrix4.__m1;
  1386. var mScale = THREE.Matrix4.__m2;
  1387. mRotation.identity();
  1388. mRotation.setRotationFromQuaternion( rotation );
  1389. mScale.makeScale( scale.x, scale.y, scale.z );
  1390. this.multiply( mRotation, mScale );
  1391. te[12] = translation.x;
  1392. te[13] = translation.y;
  1393. te[14] = translation.z;
  1394. return this;
  1395. },
  1396. decompose: function ( translation, rotation, scale ) {
  1397. var te = this.elements;
  1398. // grab the axis vectors
  1399. var x = THREE.Matrix4.__v1;
  1400. var y = THREE.Matrix4.__v2;
  1401. var z = THREE.Matrix4.__v3;
  1402. x.set( te[0], te[1], te[2] );
  1403. y.set( te[4], te[5], te[6] );
  1404. z.set( te[8], te[9], te[10] );
  1405. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1406. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1407. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1408. scale.x = x.length();
  1409. scale.y = y.length();
  1410. scale.z = z.length();
  1411. translation.x = te[12];
  1412. translation.y = te[13];
  1413. translation.z = te[14];
  1414. // scale the rotation part
  1415. var matrix = THREE.Matrix4.__m1;
  1416. matrix.copy( this );
  1417. matrix.elements[0] /= scale.x;
  1418. matrix.elements[1] /= scale.x;
  1419. matrix.elements[2] /= scale.x;
  1420. matrix.elements[4] /= scale.y;
  1421. matrix.elements[5] /= scale.y;
  1422. matrix.elements[6] /= scale.y;
  1423. matrix.elements[8] /= scale.z;
  1424. matrix.elements[9] /= scale.z;
  1425. matrix.elements[10] /= scale.z;
  1426. rotation.setFromRotationMatrix( matrix );
  1427. return [ translation, rotation, scale ];
  1428. },
  1429. extractPosition: function ( m ) {
  1430. var te = this.elements;
  1431. var me = m.elements;
  1432. te[12] = me[12];
  1433. te[13] = me[13];
  1434. te[14] = me[14];
  1435. return this;
  1436. },
  1437. extractRotation: function ( m ) {
  1438. var te = this.elements;
  1439. var me = m.elements;
  1440. var vector = THREE.Matrix4.__v1;
  1441. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1442. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1443. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1444. te[0] = me[0] * scaleX;
  1445. te[1] = me[1] * scaleX;
  1446. te[2] = me[2] * scaleX;
  1447. te[4] = me[4] * scaleY;
  1448. te[5] = me[5] * scaleY;
  1449. te[6] = me[6] * scaleY;
  1450. te[8] = me[8] * scaleZ;
  1451. te[9] = me[9] * scaleZ;
  1452. te[10] = me[10] * scaleZ;
  1453. return this;
  1454. },
  1455. //
  1456. translate: function ( v ) {
  1457. var te = this.elements;
  1458. var x = v.x, y = v.y, z = v.z;
  1459. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1460. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1461. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1462. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1463. return this;
  1464. },
  1465. rotateX: function ( angle ) {
  1466. var te = this.elements;
  1467. var m12 = te[4];
  1468. var m22 = te[5];
  1469. var m32 = te[6];
  1470. var m42 = te[7];
  1471. var m13 = te[8];
  1472. var m23 = te[9];
  1473. var m33 = te[10];
  1474. var m43 = te[11];
  1475. var c = Math.cos( angle );
  1476. var s = Math.sin( angle );
  1477. te[4] = c * m12 + s * m13;
  1478. te[5] = c * m22 + s * m23;
  1479. te[6] = c * m32 + s * m33;
  1480. te[7] = c * m42 + s * m43;
  1481. te[8] = c * m13 - s * m12;
  1482. te[9] = c * m23 - s * m22;
  1483. te[10] = c * m33 - s * m32;
  1484. te[11] = c * m43 - s * m42;
  1485. return this;
  1486. },
  1487. rotateY: function ( angle ) {
  1488. var te = this.elements;
  1489. var m11 = te[0];
  1490. var m21 = te[1];
  1491. var m31 = te[2];
  1492. var m41 = te[3];
  1493. var m13 = te[8];
  1494. var m23 = te[9];
  1495. var m33 = te[10];
  1496. var m43 = te[11];
  1497. var c = Math.cos( angle );
  1498. var s = Math.sin( angle );
  1499. te[0] = c * m11 - s * m13;
  1500. te[1] = c * m21 - s * m23;
  1501. te[2] = c * m31 - s * m33;
  1502. te[3] = c * m41 - s * m43;
  1503. te[8] = c * m13 + s * m11;
  1504. te[9] = c * m23 + s * m21;
  1505. te[10] = c * m33 + s * m31;
  1506. te[11] = c * m43 + s * m41;
  1507. return this;
  1508. },
  1509. rotateZ: function ( angle ) {
  1510. var te = this.elements;
  1511. var m11 = te[0];
  1512. var m21 = te[1];
  1513. var m31 = te[2];
  1514. var m41 = te[3];
  1515. var m12 = te[4];
  1516. var m22 = te[5];
  1517. var m32 = te[6];
  1518. var m42 = te[7];
  1519. var c = Math.cos( angle );
  1520. var s = Math.sin( angle );
  1521. te[0] = c * m11 + s * m12;
  1522. te[1] = c * m21 + s * m22;
  1523. te[2] = c * m31 + s * m32;
  1524. te[3] = c * m41 + s * m42;
  1525. te[4] = c * m12 - s * m11;
  1526. te[5] = c * m22 - s * m21;
  1527. te[6] = c * m32 - s * m31;
  1528. te[7] = c * m42 - s * m41;
  1529. return this;
  1530. },
  1531. rotateByAxis: function ( axis, angle ) {
  1532. var te = this.elements;
  1533. // optimize by checking axis
  1534. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1535. return this.rotateX( angle );
  1536. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1537. return this.rotateY( angle );
  1538. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1539. return this.rotateZ( angle );
  1540. }
  1541. var x = axis.x, y = axis.y, z = axis.z;
  1542. var n = Math.sqrt(x * x + y * y + z * z);
  1543. x /= n;
  1544. y /= n;
  1545. z /= n;
  1546. var xx = x * x, yy = y * y, zz = z * z;
  1547. var c = Math.cos( angle );
  1548. var s = Math.sin( angle );
  1549. var oneMinusCosine = 1 - c;
  1550. var xy = x * y * oneMinusCosine;
  1551. var xz = x * z * oneMinusCosine;
  1552. var yz = y * z * oneMinusCosine;
  1553. var xs = x * s;
  1554. var ys = y * s;
  1555. var zs = z * s;
  1556. var r11 = xx + (1 - xx) * c;
  1557. var r21 = xy + zs;
  1558. var r31 = xz - ys;
  1559. var r12 = xy - zs;
  1560. var r22 = yy + (1 - yy) * c;
  1561. var r32 = yz + xs;
  1562. var r13 = xz + ys;
  1563. var r23 = yz - xs;
  1564. var r33 = zz + (1 - zz) * c;
  1565. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1566. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1567. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1568. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1569. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1570. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1571. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1572. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1573. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1574. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1575. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1576. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1577. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1578. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1579. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1580. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1581. return this;
  1582. },
  1583. scale: function ( v ) {
  1584. var te = this.elements;
  1585. var x = v.x, y = v.y, z = v.z;
  1586. te[0] *= x; te[4] *= y; te[8] *= z;
  1587. te[1] *= x; te[5] *= y; te[9] *= z;
  1588. te[2] *= x; te[6] *= y; te[10] *= z;
  1589. te[3] *= x; te[7] *= y; te[11] *= z;
  1590. return this;
  1591. },
  1592. getMaxScaleOnAxis: function () {
  1593. var te = this.elements;
  1594. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1595. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1596. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1597. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1598. },
  1599. //
  1600. makeTranslation: function ( x, y, z ) {
  1601. this.set(
  1602. 1, 0, 0, x,
  1603. 0, 1, 0, y,
  1604. 0, 0, 1, z,
  1605. 0, 0, 0, 1
  1606. );
  1607. return this;
  1608. },
  1609. makeRotationX: function ( theta ) {
  1610. var c = Math.cos( theta ), s = Math.sin( theta );
  1611. this.set(
  1612. 1, 0, 0, 0,
  1613. 0, c, -s, 0,
  1614. 0, s, c, 0,
  1615. 0, 0, 0, 1
  1616. );
  1617. return this;
  1618. },
  1619. makeRotationY: function ( theta ) {
  1620. var c = Math.cos( theta ), s = Math.sin( theta );
  1621. this.set(
  1622. c, 0, s, 0,
  1623. 0, 1, 0, 0,
  1624. -s, 0, c, 0,
  1625. 0, 0, 0, 1
  1626. );
  1627. return this;
  1628. },
  1629. makeRotationZ: function ( theta ) {
  1630. var c = Math.cos( theta ), s = Math.sin( theta );
  1631. this.set(
  1632. c, -s, 0, 0,
  1633. s, c, 0, 0,
  1634. 0, 0, 1, 0,
  1635. 0, 0, 0, 1
  1636. );
  1637. return this;
  1638. },
  1639. makeRotationAxis: function ( axis, angle ) {
  1640. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1641. var c = Math.cos( angle );
  1642. var s = Math.sin( angle );
  1643. var t = 1 - c;
  1644. var x = axis.x, y = axis.y, z = axis.z;
  1645. var tx = t * x, ty = t * y;
  1646. this.set(
  1647. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1648. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1649. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1650. 0, 0, 0, 1
  1651. );
  1652. return this;
  1653. },
  1654. makeScale: function ( x, y, z ) {
  1655. this.set(
  1656. x, 0, 0, 0,
  1657. 0, y, 0, 0,
  1658. 0, 0, z, 0,
  1659. 0, 0, 0, 1
  1660. );
  1661. return this;
  1662. },
  1663. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1664. var te = this.elements;
  1665. var x = 2 * near / ( right - left );
  1666. var y = 2 * near / ( top - bottom );
  1667. var a = ( right + left ) / ( right - left );
  1668. var b = ( top + bottom ) / ( top - bottom );
  1669. var c = - ( far + near ) / ( far - near );
  1670. var d = - 2 * far * near / ( far - near );
  1671. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1672. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1673. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1674. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1675. return this;
  1676. },
  1677. makePerspective: function ( fov, aspect, near, far ) {
  1678. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1679. var ymin = - ymax;
  1680. var xmin = ymin * aspect;
  1681. var xmax = ymax * aspect;
  1682. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1683. },
  1684. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1685. var te = this.elements;
  1686. var w = right - left;
  1687. var h = top - bottom;
  1688. var p = far - near;
  1689. var x = ( right + left ) / w;
  1690. var y = ( top + bottom ) / h;
  1691. var z = ( far + near ) / p;
  1692. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1693. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1694. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1695. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1696. return this;
  1697. },
  1698. clone: function () {
  1699. var te = this.elements;
  1700. return new THREE.Matrix4(
  1701. te[0], te[4], te[8], te[12],
  1702. te[1], te[5], te[9], te[13],
  1703. te[2], te[6], te[10], te[14],
  1704. te[3], te[7], te[11], te[15]
  1705. );
  1706. }
  1707. };
  1708. THREE.Matrix4.__v1 = new THREE.Vector3();
  1709. THREE.Matrix4.__v2 = new THREE.Vector3();
  1710. THREE.Matrix4.__v3 = new THREE.Vector3();
  1711. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1712. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1713. /**
  1714. * https://github.com/mrdoob/eventtarget.js/
  1715. */
  1716. THREE.EventTarget = function () {
  1717. var listeners = {};
  1718. this.addEventListener = function ( type, listener ) {
  1719. if ( listeners[ type ] === undefined ) {
  1720. listeners[ type ] = [];
  1721. }
  1722. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1723. listeners[ type ].push( listener );
  1724. }
  1725. };
  1726. this.dispatchEvent = function ( event ) {
  1727. for ( var listener in listeners[ event.type ] ) {
  1728. listeners[ event.type ][ listener ]( event );
  1729. }
  1730. };
  1731. this.removeEventListener = function ( type, listener ) {
  1732. var index = listeners[ type ].indexOf( listener );
  1733. if ( index !== - 1 ) {
  1734. listeners[ type ].splice( index, 1 );
  1735. }
  1736. };
  1737. };
  1738. /**
  1739. * @author mrdoob / http://mrdoob.com/
  1740. * @author alteredq / http://alteredqualia.com/
  1741. */
  1742. THREE.Frustum = function ( ) {
  1743. this.planes = [
  1744. new THREE.Vector4(),
  1745. new THREE.Vector4(),
  1746. new THREE.Vector4(),
  1747. new THREE.Vector4(),
  1748. new THREE.Vector4(),
  1749. new THREE.Vector4()
  1750. ];
  1751. };
  1752. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1753. var plane;
  1754. var planes = this.planes;
  1755. var me = m.elements;
  1756. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1757. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1758. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1759. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1760. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1761. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1762. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1763. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1764. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1765. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1766. for ( var i = 0; i < 6; i ++ ) {
  1767. plane = planes[ i ];
  1768. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1769. }
  1770. };
  1771. THREE.Frustum.prototype.contains = function ( object ) {
  1772. var distance = 0.0;
  1773. var planes = this.planes;
  1774. var matrix = object.matrixWorld;
  1775. var me = matrix.elements;
  1776. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1777. for ( var i = 0; i < 6; i ++ ) {
  1778. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1779. if ( distance <= radius ) return false;
  1780. }
  1781. return true;
  1782. };
  1783. THREE.Frustum.__v1 = new THREE.Vector3();
  1784. /**
  1785. * @author mrdoob / http://mrdoob.com/
  1786. */
  1787. ( function ( THREE ) {
  1788. THREE.Ray = function ( origin, direction, near, far ) {
  1789. this.origin = origin || new THREE.Vector3();
  1790. this.direction = direction || new THREE.Vector3();
  1791. this.near = near || 0;
  1792. this.far = far || Infinity;
  1793. };
  1794. var originCopy = new THREE.Vector3();
  1795. var localOriginCopy = new THREE.Vector3();
  1796. var localDirectionCopy = new THREE.Vector3();
  1797. var vector = new THREE.Vector3();
  1798. var normal = new THREE.Vector3();
  1799. var intersectPoint = new THREE.Vector3();
  1800. var inverseMatrix = new THREE.Matrix4();
  1801. var descSort = function ( a, b ) {
  1802. return a.distance - b.distance;
  1803. };
  1804. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1805. var distanceFromIntersection = function ( origin, direction, position ) {
  1806. v0.sub( position, origin );
  1807. var dot = v0.dot( direction );
  1808. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1809. var distance = position.distanceTo( intersect );
  1810. return distance;
  1811. };
  1812. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1813. var pointInFace3 = function ( p, a, b, c ) {
  1814. v0.sub( c, a );
  1815. v1.sub( b, a );
  1816. v2.sub( p, a );
  1817. var dot00 = v0.dot( v0 );
  1818. var dot01 = v0.dot( v1 );
  1819. var dot02 = v0.dot( v2 );
  1820. var dot11 = v1.dot( v1 );
  1821. var dot12 = v1.dot( v2 );
  1822. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1823. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1824. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1825. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1826. };
  1827. var intersectObject = function ( object, ray, intersects ) {
  1828. if ( object instanceof THREE.Particle ) {
  1829. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1830. if ( distance > object.scale.x ) {
  1831. return intersects;
  1832. }
  1833. intersects.push( {
  1834. distance: distance,
  1835. point: object.position,
  1836. face: null,
  1837. object: object
  1838. } );
  1839. } else if ( object instanceof THREE.Mesh ) {
  1840. // Checking boundingSphere
  1841. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1842. // Checking distance to ray
  1843. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1844. if ( distance > scaledRadius) {
  1845. return intersects;
  1846. }
  1847. // Checking faces
  1848. var geometry = object.geometry;
  1849. var vertices = geometry.vertices;
  1850. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1851. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  1852. var side = object.material.side;
  1853. var a, b, c, d;
  1854. var precision = ray.precision;
  1855. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1856. originCopy.copy( ray.origin );
  1857. inverseMatrix.getInverse( object.matrixWorld );
  1858. localOriginCopy.copy( originCopy );
  1859. inverseMatrix.multiplyVector3( localOriginCopy );
  1860. localDirectionCopy.copy( ray.direction );
  1861. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1862. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1863. var face = geometry.faces[ f ];
  1864. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  1865. if ( material === undefined ) continue;
  1866. side = material.side;
  1867. vector.sub( face.centroid, localOriginCopy );
  1868. var normal = face.normal;
  1869. var dot = localDirectionCopy.dot( normal );
  1870. // bail if ray and plane are parallel
  1871. if ( Math.abs( dot ) < precision ) continue;
  1872. // calc distance to plane
  1873. var scalar = normal.dot( vector ) / dot;
  1874. // if negative distance, then plane is behind ray
  1875. if ( scalar < 0 ) continue;
  1876. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1877. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1878. if ( face instanceof THREE.Face3 ) {
  1879. a = vertices[ face.a ];
  1880. b = vertices[ face.b ];
  1881. c = vertices[ face.c ];
  1882. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1883. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1884. distance = originCopy.distanceTo( point );
  1885. if ( distance < ray.near || distance > ray.far ) continue;
  1886. intersects.push( {
  1887. distance: distance,
  1888. point: point,
  1889. face: face,
  1890. faceIndex: f,
  1891. object: object
  1892. } );
  1893. }
  1894. } else if ( face instanceof THREE.Face4 ) {
  1895. a = vertices[ face.a ];
  1896. b = vertices[ face.b ];
  1897. c = vertices[ face.c ];
  1898. d = vertices[ face.d ];
  1899. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1900. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1901. distance = originCopy.distanceTo( point );
  1902. if ( distance < ray.near || distance > ray.far ) continue;
  1903. intersects.push( {
  1904. distance: distance,
  1905. point: point,
  1906. face: face,
  1907. faceIndex: f,
  1908. object: object
  1909. } );
  1910. }
  1911. }
  1912. }
  1913. }
  1914. }
  1915. };
  1916. var intersectDescendants = function ( object, ray, intersects ) {
  1917. var descendants = object.getDescendants();
  1918. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1919. intersectObject( descendants[ i ], ray, intersects );
  1920. }
  1921. };
  1922. //
  1923. THREE.Ray.prototype.precision = 0.0001;
  1924. THREE.Ray.prototype.set = function ( origin, direction ) {
  1925. this.origin = origin;
  1926. this.direction = direction;
  1927. };
  1928. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1929. var intersects = [];
  1930. if ( recursive === true ) {
  1931. intersectDescendants( object, this, intersects );
  1932. }
  1933. intersectObject( object, this, intersects );
  1934. intersects.sort( descSort );
  1935. return intersects;
  1936. };
  1937. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1938. var intersects = [];
  1939. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1940. intersectObject( objects[ i ], this, intersects );
  1941. if ( recursive === true ) {
  1942. intersectDescendants( objects[ i ], this, intersects );
  1943. }
  1944. }
  1945. intersects.sort( descSort );
  1946. return intersects;
  1947. };
  1948. }( THREE ) );
  1949. /**
  1950. * @author mrdoob / http://mrdoob.com/
  1951. */
  1952. THREE.Rectangle = function () {
  1953. var _left = 0;
  1954. var _top = 0;
  1955. var _right = 0;
  1956. var _bottom = 0;
  1957. var _width = 0;
  1958. var _height = 0;
  1959. var _isEmpty = true;
  1960. function resize() {
  1961. _width = _right - _left;
  1962. _height = _bottom - _top;
  1963. }
  1964. this.getX = function () {
  1965. return _left;
  1966. };
  1967. this.getY = function () {
  1968. return _top;
  1969. };
  1970. this.getWidth = function () {
  1971. return _width;
  1972. };
  1973. this.getHeight = function () {
  1974. return _height;
  1975. };
  1976. this.getLeft = function() {
  1977. return _left;
  1978. };
  1979. this.getTop = function() {
  1980. return _top;
  1981. };
  1982. this.getRight = function() {
  1983. return _right;
  1984. };
  1985. this.getBottom = function() {
  1986. return _bottom;
  1987. };
  1988. this.set = function ( left, top, right, bottom ) {
  1989. _isEmpty = false;
  1990. _left = left; _top = top;
  1991. _right = right; _bottom = bottom;
  1992. resize();
  1993. };
  1994. this.addPoint = function ( x, y ) {
  1995. if ( _isEmpty === true ) {
  1996. _isEmpty = false;
  1997. _left = x; _top = y;
  1998. _right = x; _bottom = y;
  1999. resize();
  2000. } else {
  2001. _left = _left < x ? _left : x; // Math.min( _left, x );
  2002. _top = _top < y ? _top : y; // Math.min( _top, y );
  2003. _right = _right > x ? _right : x; // Math.max( _right, x );
  2004. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  2005. resize();
  2006. }
  2007. };
  2008. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  2009. if ( _isEmpty === true ) {
  2010. _isEmpty = false;
  2011. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  2012. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  2013. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  2014. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  2015. resize();
  2016. } else {
  2017. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  2018. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  2019. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  2020. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  2021. resize();
  2022. };
  2023. };
  2024. this.addRectangle = function ( r ) {
  2025. if ( _isEmpty === true ) {
  2026. _isEmpty = false;
  2027. _left = r.getLeft(); _top = r.getTop();
  2028. _right = r.getRight(); _bottom = r.getBottom();
  2029. resize();
  2030. } else {
  2031. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  2032. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  2033. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  2034. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  2035. resize();
  2036. }
  2037. };
  2038. this.inflate = function ( v ) {
  2039. _left -= v; _top -= v;
  2040. _right += v; _bottom += v;
  2041. resize();
  2042. };
  2043. this.minSelf = function ( r ) {
  2044. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  2045. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  2046. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  2047. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  2048. resize();
  2049. };
  2050. this.intersects = function ( r ) {
  2051. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  2052. if ( _right < r.getLeft() ) return false;
  2053. if ( _left > r.getRight() ) return false;
  2054. if ( _bottom < r.getTop() ) return false;
  2055. if ( _top > r.getBottom() ) return false;
  2056. return true;
  2057. };
  2058. this.empty = function () {
  2059. _isEmpty = true;
  2060. _left = 0; _top = 0;
  2061. _right = 0; _bottom = 0;
  2062. resize();
  2063. };
  2064. this.isEmpty = function () {
  2065. return _isEmpty;
  2066. };
  2067. };
  2068. /**
  2069. * @author alteredq / http://alteredqualia.com/
  2070. */
  2071. THREE.Math = {
  2072. // Clamp value to range <a, b>
  2073. clamp: function ( x, a, b ) {
  2074. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2075. },
  2076. // Clamp value to range <a, inf)
  2077. clampBottom: function ( x, a ) {
  2078. return x < a ? a : x;
  2079. },
  2080. // Linear mapping from range <a1, a2> to range <b1, b2>
  2081. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2082. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2083. },
  2084. // Random float from <0, 1> with 16 bits of randomness
  2085. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2086. random16: function () {
  2087. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2088. },
  2089. // Random integer from <low, high> interval
  2090. randInt: function ( low, high ) {
  2091. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2092. },
  2093. // Random float from <low, high> interval
  2094. randFloat: function ( low, high ) {
  2095. return low + Math.random() * ( high - low );
  2096. },
  2097. // Random float from <-range/2, range/2> interval
  2098. randFloatSpread: function ( range ) {
  2099. return range * ( 0.5 - Math.random() );
  2100. },
  2101. sign: function ( x ) {
  2102. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2103. }
  2104. };
  2105. /**
  2106. * @author mrdoob / http://mrdoob.com/
  2107. * @author mikael emtinger / http://gomo.se/
  2108. * @author alteredq / http://alteredqualia.com/
  2109. */
  2110. THREE.Object3D = function () {
  2111. THREE.Object3DLibrary.push( this );
  2112. this.id = THREE.Object3DIdCount ++;
  2113. this.name = '';
  2114. this.properties = {};
  2115. this.parent = undefined;
  2116. this.children = [];
  2117. this.up = new THREE.Vector3( 0, 1, 0 );
  2118. this.position = new THREE.Vector3();
  2119. this.rotation = new THREE.Vector3();
  2120. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  2121. this.scale = new THREE.Vector3( 1, 1, 1 );
  2122. this.renderDepth = null;
  2123. this.rotationAutoUpdate = true;
  2124. this.matrix = new THREE.Matrix4();
  2125. this.matrixWorld = new THREE.Matrix4();
  2126. this.matrixRotationWorld = new THREE.Matrix4();
  2127. this.matrixAutoUpdate = true;
  2128. this.matrixWorldNeedsUpdate = true;
  2129. this.quaternion = new THREE.Quaternion();
  2130. this.useQuaternion = false;
  2131. this.boundRadius = 0.0;
  2132. this.boundRadiusScale = 1.0;
  2133. this.visible = true;
  2134. this.castShadow = false;
  2135. this.receiveShadow = false;
  2136. this.frustumCulled = true;
  2137. this._vector = new THREE.Vector3();
  2138. };
  2139. THREE.Object3D.prototype = {
  2140. constructor: THREE.Object3D,
  2141. applyMatrix: function ( matrix ) {
  2142. this.matrix.multiply( matrix, this.matrix );
  2143. this.scale.getScaleFromMatrix( this.matrix );
  2144. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2145. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2146. this.position.getPositionFromMatrix( this.matrix );
  2147. },
  2148. translate: function ( distance, axis ) {
  2149. this.matrix.rotateAxis( axis );
  2150. this.position.addSelf( axis.multiplyScalar( distance ) );
  2151. },
  2152. translateX: function ( distance ) {
  2153. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2154. },
  2155. translateY: function ( distance ) {
  2156. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2157. },
  2158. translateZ: function ( distance ) {
  2159. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2160. },
  2161. localToWorld: function ( vector ) {
  2162. return this.matrixWorld.multiplyVector3( vector );
  2163. },
  2164. worldToLocal: function ( vector ) {
  2165. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2166. },
  2167. lookAt: function ( vector ) {
  2168. // TODO: Add hierarchy support.
  2169. this.matrix.lookAt( vector, this.position, this.up );
  2170. if ( this.rotationAutoUpdate ) {
  2171. if ( this.useQuaternion === false ) {
  2172. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2173. } else {
  2174. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  2175. }
  2176. }
  2177. },
  2178. add: function ( object ) {
  2179. if ( object === this ) {
  2180. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2181. return;
  2182. }
  2183. if ( object instanceof THREE.Object3D ) {
  2184. if ( object.parent !== undefined ) {
  2185. object.parent.remove( object );
  2186. }
  2187. object.parent = this;
  2188. this.children.push( object );
  2189. // add to scene
  2190. var scene = this;
  2191. while ( scene.parent !== undefined ) {
  2192. scene = scene.parent;
  2193. }
  2194. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2195. scene.__addObject( object );
  2196. }
  2197. }
  2198. },
  2199. remove: function ( object ) {
  2200. var index = this.children.indexOf( object );
  2201. if ( index !== - 1 ) {
  2202. object.parent = undefined;
  2203. this.children.splice( index, 1 );
  2204. // remove from scene
  2205. var scene = this;
  2206. while ( scene.parent !== undefined ) {
  2207. scene = scene.parent;
  2208. }
  2209. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2210. scene.__removeObject( object );
  2211. }
  2212. }
  2213. },
  2214. traverse: function ( callback ) {
  2215. callback( this );
  2216. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2217. this.children[ i ].traverse( callback );
  2218. }
  2219. },
  2220. getChildByName: function ( name, recursive ) {
  2221. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2222. var child = this.children[ i ];
  2223. if ( child.name === name ) {
  2224. return child;
  2225. }
  2226. if ( recursive === true ) {
  2227. child = child.getChildByName( name, recursive );
  2228. if ( child !== undefined ) {
  2229. return child;
  2230. }
  2231. }
  2232. }
  2233. return undefined;
  2234. },
  2235. getDescendants: function ( array ) {
  2236. if ( array === undefined ) array = [];
  2237. Array.prototype.push.apply( array, this.children );
  2238. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2239. this.children[ i ].getDescendants( array );
  2240. }
  2241. return array;
  2242. },
  2243. updateMatrix: function () {
  2244. this.matrix.setPosition( this.position );
  2245. if ( this.useQuaternion === false ) {
  2246. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2247. } else {
  2248. this.matrix.setRotationFromQuaternion( this.quaternion );
  2249. }
  2250. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2251. this.matrix.scale( this.scale );
  2252. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2253. }
  2254. this.matrixWorldNeedsUpdate = true;
  2255. },
  2256. updateMatrixWorld: function ( force ) {
  2257. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2258. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2259. if ( this.parent === undefined ) {
  2260. this.matrixWorld.copy( this.matrix );
  2261. } else {
  2262. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2263. }
  2264. this.matrixWorldNeedsUpdate = false;
  2265. force = true;
  2266. }
  2267. // update children
  2268. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2269. this.children[ i ].updateMatrixWorld( force );
  2270. }
  2271. },
  2272. clone: function ( object ) {
  2273. if ( object === undefined ) object = new THREE.Object3D();
  2274. object.name = this.name;
  2275. object.up.copy( this.up );
  2276. object.position.copy( this.position );
  2277. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  2278. object.eulerOrder = this.eulerOrder;
  2279. object.scale.copy( this.scale );
  2280. object.renderDepth = this.renderDepth;
  2281. object.rotationAutoUpdate = this.rotationAutoUpdate;
  2282. object.matrix.copy( this.matrix );
  2283. object.matrixWorld.copy( this.matrixWorld );
  2284. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  2285. object.matrixAutoUpdate = this.matrixAutoUpdate;
  2286. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  2287. object.quaternion.copy( this.quaternion );
  2288. object.useQuaternion = this.useQuaternion;
  2289. object.boundRadius = this.boundRadius;
  2290. object.boundRadiusScale = this.boundRadiusScale;
  2291. object.visible = this.visible;
  2292. object.castShadow = this.castShadow;
  2293. object.receiveShadow = this.receiveShadow;
  2294. object.frustumCulled = this.frustumCulled;
  2295. for ( var i = 0; i < this.children.length; i ++ ) {
  2296. var child = this.children[ i ];
  2297. object.add( child.clone() );
  2298. }
  2299. return object;
  2300. },
  2301. deallocate: function () {
  2302. var index = THREE.Object3DLibrary.indexOf( this );
  2303. if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
  2304. }
  2305. };
  2306. THREE.Object3D.__m1 = new THREE.Matrix4();
  2307. THREE.Object3D.defaultEulerOrder = 'XYZ',
  2308. THREE.Object3DIdCount = 0;
  2309. THREE.Object3DLibrary = [];
  2310. /**
  2311. * @author mrdoob / http://mrdoob.com/
  2312. * @author supereggbert / http://www.paulbrunt.co.uk/
  2313. * @author julianwa / https://github.com/julianwa
  2314. */
  2315. THREE.Projector = function() {
  2316. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2317. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2318. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2319. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2320. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2321. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2322. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2323. _vector3 = new THREE.Vector3(),
  2324. _vector4 = new THREE.Vector4(),
  2325. _viewProjectionMatrix = new THREE.Matrix4(),
  2326. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2327. _normalMatrix = new THREE.Matrix3(),
  2328. _frustum = new THREE.Frustum(),
  2329. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2330. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2331. _face3VertexNormals;
  2332. this.projectVector = function ( vector, camera ) {
  2333. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2334. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2335. _viewProjectionMatrix.multiplyVector3( vector );
  2336. return vector;
  2337. };
  2338. this.unprojectVector = function ( vector, camera ) {
  2339. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2340. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2341. _viewProjectionMatrix.multiplyVector3( vector );
  2342. return vector;
  2343. };
  2344. this.pickingRay = function ( vector, camera ) {
  2345. var end, ray, t;
  2346. // set two vectors with opposing z values
  2347. vector.z = -1.0;
  2348. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2349. this.unprojectVector( vector, camera );
  2350. this.unprojectVector( end, camera );
  2351. // find direction from vector to end
  2352. end.subSelf( vector ).normalize();
  2353. return new THREE.Ray( vector, end );
  2354. };
  2355. var projectGraph = function ( root, sortObjects ) {
  2356. _objectCount = 0;
  2357. _renderData.objects.length = 0;
  2358. _renderData.sprites.length = 0;
  2359. _renderData.lights.length = 0;
  2360. var projectObject = function ( parent ) {
  2361. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  2362. var object = parent.children[ c ];
  2363. if ( object.visible === false ) continue;
  2364. if ( object instanceof THREE.Light ) {
  2365. _renderData.lights.push( object );
  2366. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  2367. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  2368. _object = getNextObjectInPool();
  2369. _object.object = object;
  2370. if ( object.renderDepth !== null ) {
  2371. _object.z = object.renderDepth;
  2372. } else {
  2373. _vector3.copy( object.matrixWorld.getPosition() );
  2374. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2375. _object.z = _vector3.z;
  2376. }
  2377. _renderData.objects.push( _object );
  2378. }
  2379. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2380. _object = getNextObjectInPool();
  2381. _object.object = object;
  2382. // TODO: Find an elegant and performant solution and remove this dupe code.
  2383. if ( object.renderDepth !== null ) {
  2384. _object.z = object.renderDepth;
  2385. } else {
  2386. _vector3.copy( object.matrixWorld.getPosition() );
  2387. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2388. _object.z = _vector3.z;
  2389. }
  2390. _renderData.sprites.push( _object );
  2391. } else {
  2392. _object = getNextObjectInPool();
  2393. _object.object = object;
  2394. if ( object.renderDepth !== null ) {
  2395. _object.z = object.renderDepth;
  2396. } else {
  2397. _vector3.copy( object.matrixWorld.getPosition() );
  2398. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2399. _object.z = _vector3.z;
  2400. }
  2401. _renderData.objects.push( _object );
  2402. }
  2403. projectObject( object );
  2404. }
  2405. };
  2406. projectObject( root );
  2407. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  2408. return _renderData;
  2409. };
  2410. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  2411. var near = camera.near, far = camera.far, visible = false,
  2412. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object, modelMatrix,
  2413. geometry, vertices, vertex, vertexPositionScreen,
  2414. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2415. v1, v2, v3, v4, isFaceMaterial, objectMaterials, material, side;
  2416. _face3Count = 0;
  2417. _face4Count = 0;
  2418. _lineCount = 0;
  2419. _particleCount = 0;
  2420. _renderData.elements.length = 0;
  2421. scene.updateMatrixWorld();
  2422. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2423. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2424. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2425. _frustum.setFromMatrix( _viewProjectionMatrix );
  2426. _renderData = projectGraph( scene, sortObjects );
  2427. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  2428. object = _renderData.objects[ o ].object;
  2429. modelMatrix = object.matrixWorld;
  2430. _vertexCount = 0;
  2431. if ( object instanceof THREE.Mesh ) {
  2432. geometry = object.geometry;
  2433. vertices = geometry.vertices;
  2434. faces = geometry.faces;
  2435. faceVertexUvs = geometry.faceVertexUvs;
  2436. _normalMatrix.getInverse( modelMatrix );
  2437. _normalMatrix.transpose();
  2438. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2439. objectMaterials = isFaceMaterial === true ? object.material : null;
  2440. side = object.material.side;
  2441. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2442. _vertex = getNextVertexInPool();
  2443. _vertex.positionWorld.copy( vertices[ v ] );
  2444. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2445. _vertex.positionScreen.copy( _vertex.positionWorld );
  2446. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2447. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2448. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2449. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2450. }
  2451. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2452. face = faces[ f ];
  2453. material = isFaceMaterial === true ? objectMaterials.materials[ face.materialIndex ] : object.material;
  2454. if ( material === undefined ) continue;
  2455. side = material.side;
  2456. if ( face instanceof THREE.Face3 ) {
  2457. v1 = _vertexPool[ face.a ];
  2458. v2 = _vertexPool[ face.b ];
  2459. v3 = _vertexPool[ face.c ];
  2460. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2461. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2462. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2463. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2464. _face = getNextFace3InPool();
  2465. _face.v1.copy( v1 );
  2466. _face.v2.copy( v2 );
  2467. _face.v3.copy( v3 );
  2468. } else {
  2469. continue;
  2470. }
  2471. } else {
  2472. continue;
  2473. }
  2474. } else if ( face instanceof THREE.Face4 ) {
  2475. v1 = _vertexPool[ face.a ];
  2476. v2 = _vertexPool[ face.b ];
  2477. v3 = _vertexPool[ face.c ];
  2478. v4 = _vertexPool[ face.d ];
  2479. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2480. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2481. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2482. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2483. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2484. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2485. _face = getNextFace4InPool();
  2486. _face.v1.copy( v1 );
  2487. _face.v2.copy( v2 );
  2488. _face.v3.copy( v3 );
  2489. _face.v4.copy( v4 );
  2490. } else {
  2491. continue;
  2492. }
  2493. } else {
  2494. continue;
  2495. }
  2496. }
  2497. _face.normalWorld.copy( face.normal );
  2498. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2499. _normalMatrix.multiplyVector3( _face.normalWorld ).normalize();
  2500. _face.centroidWorld.copy( face.centroid );
  2501. modelMatrix.multiplyVector3( _face.centroidWorld );
  2502. _face.centroidScreen.copy( _face.centroidWorld );
  2503. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2504. faceVertexNormals = face.vertexNormals;
  2505. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2506. normal = _face.vertexNormalsWorld[ n ];
  2507. normal.copy( faceVertexNormals[ n ] );
  2508. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2509. _normalMatrix.multiplyVector3( normal ).normalize();
  2510. }
  2511. _face.vertexNormalsLength = faceVertexNormals.length;
  2512. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2513. uvs = faceVertexUvs[ c ][ f ];
  2514. if ( uvs === undefined ) continue;
  2515. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2516. _face.uvs[ c ][ u ] = uvs[ u ];
  2517. }
  2518. }
  2519. _face.color = face.color;
  2520. _face.material = material;
  2521. _face.z = _face.centroidScreen.z;
  2522. _renderData.elements.push( _face );
  2523. }
  2524. } else if ( object instanceof THREE.Line ) {
  2525. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2526. vertices = object.geometry.vertices;
  2527. v1 = getNextVertexInPool();
  2528. v1.positionScreen.copy( vertices[ 0 ] );
  2529. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2530. // Handle LineStrip and LinePieces
  2531. var step = object.type === THREE.LinePieces ? 2 : 1;
  2532. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2533. v1 = getNextVertexInPool();
  2534. v1.positionScreen.copy( vertices[ v ] );
  2535. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2536. if ( ( v + 1 ) % step > 0 ) continue;
  2537. v2 = _vertexPool[ _vertexCount - 2 ];
  2538. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2539. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2540. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2541. // Perform the perspective divide
  2542. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2543. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2544. _line = getNextLineInPool();
  2545. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2546. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2547. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2548. _line.material = object.material;
  2549. _renderData.elements.push( _line );
  2550. }
  2551. }
  2552. }
  2553. }
  2554. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2555. object = _renderData.sprites[ o ].object;
  2556. modelMatrix = object.matrixWorld;
  2557. if ( object instanceof THREE.Particle ) {
  2558. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2559. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2560. _vector4.z /= _vector4.w;
  2561. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2562. _particle = getNextParticleInPool();
  2563. _particle.object = object;
  2564. _particle.x = _vector4.x / _vector4.w;
  2565. _particle.y = _vector4.y / _vector4.w;
  2566. _particle.z = _vector4.z;
  2567. _particle.rotation = object.rotation.z;
  2568. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2569. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2570. _particle.material = object.material;
  2571. _renderData.elements.push( _particle );
  2572. }
  2573. }
  2574. }
  2575. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  2576. return _renderData;
  2577. };
  2578. // Pools
  2579. function getNextObjectInPool() {
  2580. if ( _objectCount === _objectPoolLength ) {
  2581. var object = new THREE.RenderableObject();
  2582. _objectPool.push( object );
  2583. _objectPoolLength ++;
  2584. _objectCount ++;
  2585. return object;
  2586. }
  2587. return _objectPool[ _objectCount ++ ];
  2588. }
  2589. function getNextVertexInPool() {
  2590. if ( _vertexCount === _vertexPoolLength ) {
  2591. var vertex = new THREE.RenderableVertex();
  2592. _vertexPool.push( vertex );
  2593. _vertexPoolLength ++;
  2594. _vertexCount ++;
  2595. return vertex;
  2596. }
  2597. return _vertexPool[ _vertexCount ++ ];
  2598. }
  2599. function getNextFace3InPool() {
  2600. if ( _face3Count === _face3PoolLength ) {
  2601. var face = new THREE.RenderableFace3();
  2602. _face3Pool.push( face );
  2603. _face3PoolLength ++;
  2604. _face3Count ++;
  2605. return face;
  2606. }
  2607. return _face3Pool[ _face3Count ++ ];
  2608. }
  2609. function getNextFace4InPool() {
  2610. if ( _face4Count === _face4PoolLength ) {
  2611. var face = new THREE.RenderableFace4();
  2612. _face4Pool.push( face );
  2613. _face4PoolLength ++;
  2614. _face4Count ++;
  2615. return face;
  2616. }
  2617. return _face4Pool[ _face4Count ++ ];
  2618. }
  2619. function getNextLineInPool() {
  2620. if ( _lineCount === _linePoolLength ) {
  2621. var line = new THREE.RenderableLine();
  2622. _linePool.push( line );
  2623. _linePoolLength ++;
  2624. _lineCount ++
  2625. return line;
  2626. }
  2627. return _linePool[ _lineCount ++ ];
  2628. }
  2629. function getNextParticleInPool() {
  2630. if ( _particleCount === _particlePoolLength ) {
  2631. var particle = new THREE.RenderableParticle();
  2632. _particlePool.push( particle );
  2633. _particlePoolLength ++;
  2634. _particleCount ++
  2635. return particle;
  2636. }
  2637. return _particlePool[ _particleCount ++ ];
  2638. }
  2639. //
  2640. function painterSort( a, b ) {
  2641. return b.z - a.z;
  2642. }
  2643. function clipLine( s1, s2 ) {
  2644. var alpha1 = 0, alpha2 = 1,
  2645. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2646. // Z = -1 and Z = +1, respectively.
  2647. bc1near = s1.z + s1.w,
  2648. bc2near = s2.z + s2.w,
  2649. bc1far = - s1.z + s1.w,
  2650. bc2far = - s2.z + s2.w;
  2651. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2652. // Both vertices lie entirely within all clip planes.
  2653. return true;
  2654. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2655. // Both vertices lie entirely outside one of the clip planes.
  2656. return false;
  2657. } else {
  2658. // The line segment spans at least one clip plane.
  2659. if ( bc1near < 0 ) {
  2660. // v1 lies outside the near plane, v2 inside
  2661. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2662. } else if ( bc2near < 0 ) {
  2663. // v2 lies outside the near plane, v1 inside
  2664. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2665. }
  2666. if ( bc1far < 0 ) {
  2667. // v1 lies outside the far plane, v2 inside
  2668. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2669. } else if ( bc2far < 0 ) {
  2670. // v2 lies outside the far plane, v2 inside
  2671. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2672. }
  2673. if ( alpha2 < alpha1 ) {
  2674. // The line segment spans two boundaries, but is outside both of them.
  2675. // (This can't happen when we're only clipping against just near/far but good
  2676. // to leave the check here for future usage if other clip planes are added.)
  2677. return false;
  2678. } else {
  2679. // Update the s1 and s2 vertices to match the clipped line segment.
  2680. s1.lerpSelf( s2, alpha1 );
  2681. s2.lerpSelf( s1, 1 - alpha2 );
  2682. return true;
  2683. }
  2684. }
  2685. }
  2686. };
  2687. /**
  2688. * @author mikael emtinger / http://gomo.se/
  2689. * @author alteredq / http://alteredqualia.com/
  2690. * @author WestLangley / http://github.com/WestLangley
  2691. */
  2692. THREE.Quaternion = function( x, y, z, w ) {
  2693. this.x = x || 0;
  2694. this.y = y || 0;
  2695. this.z = z || 0;
  2696. this.w = ( w !== undefined ) ? w : 1;
  2697. };
  2698. THREE.Quaternion.prototype = {
  2699. constructor: THREE.Quaternion,
  2700. set: function ( x, y, z, w ) {
  2701. this.x = x;
  2702. this.y = y;
  2703. this.z = z;
  2704. this.w = w;
  2705. return this;
  2706. },
  2707. copy: function ( q ) {
  2708. this.x = q.x;
  2709. this.y = q.y;
  2710. this.z = q.z;
  2711. this.w = q.w;
  2712. return this;
  2713. },
  2714. setFromEuler: function ( v, order ) {
  2715. // http://www.mathworks.com/matlabcentral/fileexchange/
  2716. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2717. // content/SpinCalc.m
  2718. var c1 = Math.cos( v.x / 2 );
  2719. var c2 = Math.cos( v.y / 2 );
  2720. var c3 = Math.cos( v.z / 2 );
  2721. var s1 = Math.sin( v.x / 2 );
  2722. var s2 = Math.sin( v.y / 2 );
  2723. var s3 = Math.sin( v.z / 2 );
  2724. if ( order === undefined || order === 'XYZ' ) {
  2725. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2726. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2727. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2728. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2729. } else if ( order === 'YXZ' ) {
  2730. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2731. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2732. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2733. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2734. } else if ( order === 'ZXY' ) {
  2735. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2736. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2737. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2738. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2739. } else if ( order === 'ZYX' ) {
  2740. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2741. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2742. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2743. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2744. } else if ( order === 'YZX' ) {
  2745. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2746. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2747. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2748. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2749. } else if ( order === 'XZY' ) {
  2750. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2751. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2752. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2753. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2754. }
  2755. return this;
  2756. },
  2757. setFromAxisAngle: function ( axis, angle ) {
  2758. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2759. // axis have to be normalized
  2760. var halfAngle = angle / 2,
  2761. s = Math.sin( halfAngle );
  2762. this.x = axis.x * s;
  2763. this.y = axis.y * s;
  2764. this.z = axis.z * s;
  2765. this.w = Math.cos( halfAngle );
  2766. return this;
  2767. },
  2768. setFromRotationMatrix: function ( m ) {
  2769. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2770. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2771. var te = m.elements,
  2772. m11 = te[0], m12 = te[4], m13 = te[8],
  2773. m21 = te[1], m22 = te[5], m23 = te[9],
  2774. m31 = te[2], m32 = te[6], m33 = te[10],
  2775. trace = m11 + m22 + m33,
  2776. s;
  2777. if( trace > 0 ) {
  2778. s = 0.5 / Math.sqrt( trace + 1.0 );
  2779. this.w = 0.25 / s;
  2780. this.x = ( m32 - m23 ) * s;
  2781. this.y = ( m13 - m31 ) * s;
  2782. this.z = ( m21 - m12 ) * s;
  2783. } else if ( m11 > m22 && m11 > m33 ) {
  2784. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2785. this.w = (m32 - m23 ) / s;
  2786. this.x = 0.25 * s;
  2787. this.y = (m12 + m21 ) / s;
  2788. this.z = (m13 + m31 ) / s;
  2789. } else if (m22 > m33) {
  2790. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2791. this.w = (m13 - m31 ) / s;
  2792. this.x = (m12 + m21 ) / s;
  2793. this.y = 0.25 * s;
  2794. this.z = (m23 + m32 ) / s;
  2795. } else {
  2796. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2797. this.w = ( m21 - m12 ) / s;
  2798. this.x = ( m13 + m31 ) / s;
  2799. this.y = ( m23 + m32 ) / s;
  2800. this.z = 0.25 * s;
  2801. }
  2802. return this;
  2803. },
  2804. inverse: function () {
  2805. this.conjugate().normalize();
  2806. return this;
  2807. },
  2808. conjugate: function () {
  2809. this.x *= -1;
  2810. this.y *= -1;
  2811. this.z *= -1;
  2812. return this;
  2813. },
  2814. length: function () {
  2815. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2816. },
  2817. normalize: function () {
  2818. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2819. if ( l === 0 ) {
  2820. this.x = 0;
  2821. this.y = 0;
  2822. this.z = 0;
  2823. this.w = 1;
  2824. } else {
  2825. l = 1 / l;
  2826. this.x = this.x * l;
  2827. this.y = this.y * l;
  2828. this.z = this.z * l;
  2829. this.w = this.w * l;
  2830. }
  2831. return this;
  2832. },
  2833. multiply: function ( a, b ) {
  2834. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2835. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2836. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2837. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2838. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2839. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2840. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2841. return this;
  2842. },
  2843. multiplySelf: function ( b ) {
  2844. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2845. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2846. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2847. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2848. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2849. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2850. return this;
  2851. },
  2852. multiplyVector3: function ( vector, dest ) {
  2853. if ( !dest ) { dest = vector; }
  2854. var x = vector.x, y = vector.y, z = vector.z,
  2855. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2856. // calculate quat * vector
  2857. var ix = qw * x + qy * z - qz * y,
  2858. iy = qw * y + qz * x - qx * z,
  2859. iz = qw * z + qx * y - qy * x,
  2860. iw = -qx * x - qy * y - qz * z;
  2861. // calculate result * inverse quat
  2862. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2863. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2864. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2865. return dest;
  2866. },
  2867. slerpSelf: function ( qb, t ) {
  2868. var x = this.x, y = this.y, z = this.z, w = this.w;
  2869. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2870. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2871. if ( cosHalfTheta < 0 ) {
  2872. this.w = -qb.w;
  2873. this.x = -qb.x;
  2874. this.y = -qb.y;
  2875. this.z = -qb.z;
  2876. cosHalfTheta = -cosHalfTheta;
  2877. } else {
  2878. this.copy( qb );
  2879. }
  2880. if ( cosHalfTheta >= 1.0 ) {
  2881. this.w = w;
  2882. this.x = x;
  2883. this.y = y;
  2884. this.z = z;
  2885. return this;
  2886. }
  2887. var halfTheta = Math.acos( cosHalfTheta );
  2888. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2889. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2890. this.w = 0.5 * ( w + this.w );
  2891. this.x = 0.5 * ( x + this.x );
  2892. this.y = 0.5 * ( y + this.y );
  2893. this.z = 0.5 * ( z + this.z );
  2894. return this;
  2895. }
  2896. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2897. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2898. this.w = ( w * ratioA + this.w * ratioB );
  2899. this.x = ( x * ratioA + this.x * ratioB );
  2900. this.y = ( y * ratioA + this.y * ratioB );
  2901. this.z = ( z * ratioA + this.z * ratioB );
  2902. return this;
  2903. },
  2904. clone: function () {
  2905. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2906. }
  2907. }
  2908. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2909. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2910. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2911. if ( cosHalfTheta < 0 ) {
  2912. qm.w = -qb.w;
  2913. qm.x = -qb.x;
  2914. qm.y = -qb.y;
  2915. qm.z = -qb.z;
  2916. cosHalfTheta = -cosHalfTheta;
  2917. } else {
  2918. qm.copy( qb );
  2919. }
  2920. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2921. qm.w = qa.w;
  2922. qm.x = qa.x;
  2923. qm.y = qa.y;
  2924. qm.z = qa.z;
  2925. return qm;
  2926. }
  2927. var halfTheta = Math.acos( cosHalfTheta );
  2928. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2929. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2930. qm.w = 0.5 * ( qa.w + qm.w );
  2931. qm.x = 0.5 * ( qa.x + qm.x );
  2932. qm.y = 0.5 * ( qa.y + qm.y );
  2933. qm.z = 0.5 * ( qa.z + qm.z );
  2934. return qm;
  2935. }
  2936. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2937. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2938. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2939. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2940. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2941. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2942. return qm;
  2943. }
  2944. /**
  2945. * @author mrdoob / http://mrdoob.com/
  2946. */
  2947. THREE.Vertex = function ( v ) {
  2948. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2949. return v;
  2950. };
  2951. /**
  2952. * @author mrdoob / http://mrdoob.com/
  2953. * @author alteredq / http://alteredqualia.com/
  2954. */
  2955. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2956. this.a = a;
  2957. this.b = b;
  2958. this.c = c;
  2959. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2960. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2961. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2962. this.vertexColors = color instanceof Array ? color : [];
  2963. this.vertexTangents = [];
  2964. this.materialIndex = materialIndex;
  2965. this.centroid = new THREE.Vector3();
  2966. };
  2967. THREE.Face3.prototype = {
  2968. constructor: THREE.Face3,
  2969. clone: function () {
  2970. var face = new THREE.Face3( this.a, this.b, this.c );
  2971. face.normal.copy( this.normal );
  2972. face.color.copy( this.color );
  2973. face.centroid.copy( this.centroid );
  2974. face.materialIndex = this.materialIndex;
  2975. var i, il;
  2976. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2977. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2978. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2979. return face;
  2980. }
  2981. };
  2982. /**
  2983. * @author mrdoob / http://mrdoob.com/
  2984. * @author alteredq / http://alteredqualia.com/
  2985. */
  2986. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2987. this.a = a;
  2988. this.b = b;
  2989. this.c = c;
  2990. this.d = d;
  2991. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2992. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2993. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2994. this.vertexColors = color instanceof Array ? color : [];
  2995. this.vertexTangents = [];
  2996. this.materialIndex = materialIndex;
  2997. this.centroid = new THREE.Vector3();
  2998. };
  2999. THREE.Face4.prototype = {
  3000. constructor: THREE.Face4,
  3001. clone: function () {
  3002. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  3003. face.normal.copy( this.normal );
  3004. face.color.copy( this.color );
  3005. face.centroid.copy( this.centroid );
  3006. face.materialIndex = this.materialIndex;
  3007. var i, il;
  3008. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3009. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3010. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3011. return face;
  3012. }
  3013. };
  3014. /**
  3015. * @author mrdoob / http://mrdoob.com/
  3016. */
  3017. THREE.UV = function ( u, v ) {
  3018. this.u = u || 0;
  3019. this.v = v || 0;
  3020. };
  3021. THREE.UV.prototype = {
  3022. constructor: THREE.UV,
  3023. set: function ( u, v ) {
  3024. this.u = u;
  3025. this.v = v;
  3026. return this;
  3027. },
  3028. copy: function ( uv ) {
  3029. this.u = uv.u;
  3030. this.v = uv.v;
  3031. return this;
  3032. },
  3033. lerpSelf: function ( uv, alpha ) {
  3034. this.u += ( uv.u - this.u ) * alpha;
  3035. this.v += ( uv.v - this.v ) * alpha;
  3036. return this;
  3037. },
  3038. clone: function () {
  3039. return new THREE.UV( this.u, this.v );
  3040. }
  3041. };
  3042. /**
  3043. * @author mrdoob / http://mrdoob.com/
  3044. * @author kile / http://kile.stravaganza.org/
  3045. * @author alteredq / http://alteredqualia.com/
  3046. * @author mikael emtinger / http://gomo.se/
  3047. * @author zz85 / http://www.lab4games.net/zz85/blog
  3048. */
  3049. THREE.Geometry = function () {
  3050. THREE.GeometryLibrary.push( this );
  3051. this.id = THREE.GeometryIdCount ++;
  3052. this.name = '';
  3053. this.vertices = [];
  3054. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  3055. this.normals = []; // one-to-one vertex normals, used in Ribbon
  3056. this.faces = [];
  3057. this.faceUvs = [[]];
  3058. this.faceVertexUvs = [[]];
  3059. this.morphTargets = [];
  3060. this.morphColors = [];
  3061. this.morphNormals = [];
  3062. this.skinWeights = [];
  3063. this.skinIndices = [];
  3064. this.lineDistances = [];
  3065. this.boundingBox = null;
  3066. this.boundingSphere = null;
  3067. this.hasTangents = false;
  3068. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  3069. // update flags
  3070. this.verticesNeedUpdate = false;
  3071. this.elementsNeedUpdate = false;
  3072. this.uvsNeedUpdate = false;
  3073. this.normalsNeedUpdate = false;
  3074. this.tangentsNeedUpdate = false;
  3075. this.colorsNeedUpdate = false;
  3076. this.lineDistancesNeedUpdate = false;
  3077. this.buffersNeedUpdate = false;
  3078. };
  3079. THREE.Geometry.prototype = {
  3080. constructor : THREE.Geometry,
  3081. applyMatrix: function ( matrix ) {
  3082. var normalMatrix = new THREE.Matrix3();
  3083. normalMatrix.getInverse( matrix ).transpose();
  3084. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3085. var vertex = this.vertices[ i ];
  3086. matrix.multiplyVector3( vertex );
  3087. }
  3088. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3089. var face = this.faces[ i ];
  3090. normalMatrix.multiplyVector3( face.normal ).normalize();
  3091. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3092. normalMatrix.multiplyVector3( face.vertexNormals[ j ] ).normalize();
  3093. }
  3094. matrix.multiplyVector3( face.centroid );
  3095. }
  3096. },
  3097. computeCentroids: function () {
  3098. var f, fl, face;
  3099. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3100. face = this.faces[ f ];
  3101. face.centroid.set( 0, 0, 0 );
  3102. if ( face instanceof THREE.Face3 ) {
  3103. face.centroid.addSelf( this.vertices[ face.a ] );
  3104. face.centroid.addSelf( this.vertices[ face.b ] );
  3105. face.centroid.addSelf( this.vertices[ face.c ] );
  3106. face.centroid.divideScalar( 3 );
  3107. } else if ( face instanceof THREE.Face4 ) {
  3108. face.centroid.addSelf( this.vertices[ face.a ] );
  3109. face.centroid.addSelf( this.vertices[ face.b ] );
  3110. face.centroid.addSelf( this.vertices[ face.c ] );
  3111. face.centroid.addSelf( this.vertices[ face.d ] );
  3112. face.centroid.divideScalar( 4 );
  3113. }
  3114. }
  3115. },
  3116. computeFaceNormals: function () {
  3117. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3118. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3119. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3120. face = this.faces[ f ];
  3121. vA = this.vertices[ face.a ];
  3122. vB = this.vertices[ face.b ];
  3123. vC = this.vertices[ face.c ];
  3124. cb.sub( vC, vB );
  3125. ab.sub( vA, vB );
  3126. cb.crossSelf( ab );
  3127. cb.normalize();
  3128. face.normal.copy( cb );
  3129. }
  3130. },
  3131. computeVertexNormals: function ( areaWeighted ) {
  3132. var v, vl, f, fl, face, vertices;
  3133. // create internal buffers for reuse when calling this method repeatedly
  3134. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3135. if ( this.__tmpVertices === undefined ) {
  3136. this.__tmpVertices = new Array( this.vertices.length );
  3137. vertices = this.__tmpVertices;
  3138. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3139. vertices[ v ] = new THREE.Vector3();
  3140. }
  3141. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3142. face = this.faces[ f ];
  3143. if ( face instanceof THREE.Face3 ) {
  3144. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3145. } else if ( face instanceof THREE.Face4 ) {
  3146. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3147. }
  3148. }
  3149. } else {
  3150. vertices = this.__tmpVertices;
  3151. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3152. vertices[ v ].set( 0, 0, 0 );
  3153. }
  3154. }
  3155. if ( areaWeighted ) {
  3156. // vertex normals weighted by triangle areas
  3157. // http://www.iquilezles.org/www/articles/normals/normals.htm
  3158. var vA, vB, vC, vD;
  3159. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  3160. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  3161. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3162. face = this.faces[ f ];
  3163. if ( face instanceof THREE.Face3 ) {
  3164. vA = this.vertices[ face.a ];
  3165. vB = this.vertices[ face.b ];
  3166. vC = this.vertices[ face.c ];
  3167. cb.sub( vC, vB );
  3168. ab.sub( vA, vB );
  3169. cb.crossSelf( ab );
  3170. vertices[ face.a ].addSelf( cb );
  3171. vertices[ face.b ].addSelf( cb );
  3172. vertices[ face.c ].addSelf( cb );
  3173. } else if ( face instanceof THREE.Face4 ) {
  3174. vA = this.vertices[ face.a ];
  3175. vB = this.vertices[ face.b ];
  3176. vC = this.vertices[ face.c ];
  3177. vD = this.vertices[ face.d ];
  3178. // abd
  3179. db.sub( vD, vB );
  3180. ab.sub( vA, vB );
  3181. db.crossSelf( ab );
  3182. vertices[ face.a ].addSelf( db );
  3183. vertices[ face.b ].addSelf( db );
  3184. vertices[ face.d ].addSelf( db );
  3185. // bcd
  3186. dc.sub( vD, vC );
  3187. bc.sub( vB, vC );
  3188. dc.crossSelf( bc );
  3189. vertices[ face.b ].addSelf( dc );
  3190. vertices[ face.c ].addSelf( dc );
  3191. vertices[ face.d ].addSelf( dc );
  3192. }
  3193. }
  3194. } else {
  3195. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3196. face = this.faces[ f ];
  3197. if ( face instanceof THREE.Face3 ) {
  3198. vertices[ face.a ].addSelf( face.normal );
  3199. vertices[ face.b ].addSelf( face.normal );
  3200. vertices[ face.c ].addSelf( face.normal );
  3201. } else if ( face instanceof THREE.Face4 ) {
  3202. vertices[ face.a ].addSelf( face.normal );
  3203. vertices[ face.b ].addSelf( face.normal );
  3204. vertices[ face.c ].addSelf( face.normal );
  3205. vertices[ face.d ].addSelf( face.normal );
  3206. }
  3207. }
  3208. }
  3209. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3210. vertices[ v ].normalize();
  3211. }
  3212. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3213. face = this.faces[ f ];
  3214. if ( face instanceof THREE.Face3 ) {
  3215. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3216. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3217. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3218. } else if ( face instanceof THREE.Face4 ) {
  3219. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3220. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3221. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3222. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3223. }
  3224. }
  3225. },
  3226. computeMorphNormals: function () {
  3227. var i, il, f, fl, face;
  3228. // save original normals
  3229. // - create temp variables on first access
  3230. // otherwise just copy (for faster repeated calls)
  3231. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3232. face = this.faces[ f ];
  3233. if ( ! face.__originalFaceNormal ) {
  3234. face.__originalFaceNormal = face.normal.clone();
  3235. } else {
  3236. face.__originalFaceNormal.copy( face.normal );
  3237. }
  3238. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3239. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3240. if ( ! face.__originalVertexNormals[ i ] ) {
  3241. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3242. } else {
  3243. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3244. }
  3245. }
  3246. }
  3247. // use temp geometry to compute face and vertex normals for each morph
  3248. var tmpGeo = new THREE.Geometry();
  3249. tmpGeo.faces = this.faces;
  3250. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3251. // create on first access
  3252. if ( ! this.morphNormals[ i ] ) {
  3253. this.morphNormals[ i ] = {};
  3254. this.morphNormals[ i ].faceNormals = [];
  3255. this.morphNormals[ i ].vertexNormals = [];
  3256. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3257. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3258. var faceNormal, vertexNormals;
  3259. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3260. face = this.faces[ f ];
  3261. faceNormal = new THREE.Vector3();
  3262. if ( face instanceof THREE.Face3 ) {
  3263. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3264. } else {
  3265. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3266. }
  3267. dstNormalsFace.push( faceNormal );
  3268. dstNormalsVertex.push( vertexNormals );
  3269. }
  3270. }
  3271. var morphNormals = this.morphNormals[ i ];
  3272. // set vertices to morph target
  3273. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3274. // compute morph normals
  3275. tmpGeo.computeFaceNormals();
  3276. tmpGeo.computeVertexNormals();
  3277. // store morph normals
  3278. var faceNormal, vertexNormals;
  3279. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3280. face = this.faces[ f ];
  3281. faceNormal = morphNormals.faceNormals[ f ];
  3282. vertexNormals = morphNormals.vertexNormals[ f ];
  3283. faceNormal.copy( face.normal );
  3284. if ( face instanceof THREE.Face3 ) {
  3285. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3286. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3287. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3288. } else {
  3289. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3290. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3291. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3292. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3293. }
  3294. }
  3295. }
  3296. // restore original normals
  3297. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3298. face = this.faces[ f ];
  3299. face.normal = face.__originalFaceNormal;
  3300. face.vertexNormals = face.__originalVertexNormals;
  3301. }
  3302. },
  3303. computeTangents: function () {
  3304. // based on http://www.terathon.com/code/tangent.html
  3305. // tangents go to vertices
  3306. var f, fl, v, vl, i, il, vertexIndex,
  3307. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3308. x1, x2, y1, y2, z1, z2,
  3309. s1, s2, t1, t2, r, t, test,
  3310. tan1 = [], tan2 = [],
  3311. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3312. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3313. n = new THREE.Vector3(), w;
  3314. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3315. tan1[ v ] = new THREE.Vector3();
  3316. tan2[ v ] = new THREE.Vector3();
  3317. }
  3318. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3319. vA = context.vertices[ a ];
  3320. vB = context.vertices[ b ];
  3321. vC = context.vertices[ c ];
  3322. uvA = uv[ ua ];
  3323. uvB = uv[ ub ];
  3324. uvC = uv[ uc ];
  3325. x1 = vB.x - vA.x;
  3326. x2 = vC.x - vA.x;
  3327. y1 = vB.y - vA.y;
  3328. y2 = vC.y - vA.y;
  3329. z1 = vB.z - vA.z;
  3330. z2 = vC.z - vA.z;
  3331. s1 = uvB.u - uvA.u;
  3332. s2 = uvC.u - uvA.u;
  3333. t1 = uvB.v - uvA.v;
  3334. t2 = uvC.v - uvA.v;
  3335. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3336. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3337. ( t2 * y1 - t1 * y2 ) * r,
  3338. ( t2 * z1 - t1 * z2 ) * r );
  3339. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3340. ( s1 * y2 - s2 * y1 ) * r,
  3341. ( s1 * z2 - s2 * z1 ) * r );
  3342. tan1[ a ].addSelf( sdir );
  3343. tan1[ b ].addSelf( sdir );
  3344. tan1[ c ].addSelf( sdir );
  3345. tan2[ a ].addSelf( tdir );
  3346. tan2[ b ].addSelf( tdir );
  3347. tan2[ c ].addSelf( tdir );
  3348. }
  3349. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3350. face = this.faces[ f ];
  3351. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3352. if ( face instanceof THREE.Face3 ) {
  3353. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3354. } else if ( face instanceof THREE.Face4 ) {
  3355. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3356. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3357. }
  3358. }
  3359. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3360. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3361. face = this.faces[ f ];
  3362. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3363. n.copy( face.vertexNormals[ i ] );
  3364. vertexIndex = face[ faceIndex[ i ] ];
  3365. t = tan1[ vertexIndex ];
  3366. // Gram-Schmidt orthogonalize
  3367. tmp.copy( t );
  3368. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3369. // Calculate handedness
  3370. tmp2.cross( face.vertexNormals[ i ], t );
  3371. test = tmp2.dot( tan2[ vertexIndex ] );
  3372. w = (test < 0.0) ? -1.0 : 1.0;
  3373. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3374. }
  3375. }
  3376. this.hasTangents = true;
  3377. },
  3378. computeLineDistances: function ( ) {
  3379. var d = 0;
  3380. var vertices = this.vertices;
  3381. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3382. if ( i > 0 ) {
  3383. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  3384. }
  3385. this.lineDistances[ i ] = d;
  3386. }
  3387. },
  3388. computeBoundingBox: function () {
  3389. if ( ! this.boundingBox ) {
  3390. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3391. }
  3392. if ( this.vertices.length > 0 ) {
  3393. var position, firstPosition = this.vertices[ 0 ];
  3394. this.boundingBox.min.copy( firstPosition );
  3395. this.boundingBox.max.copy( firstPosition );
  3396. var min = this.boundingBox.min,
  3397. max = this.boundingBox.max;
  3398. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3399. position = this.vertices[ v ];
  3400. if ( position.x < min.x ) {
  3401. min.x = position.x;
  3402. } else if ( position.x > max.x ) {
  3403. max.x = position.x;
  3404. }
  3405. if ( position.y < min.y ) {
  3406. min.y = position.y;
  3407. } else if ( position.y > max.y ) {
  3408. max.y = position.y;
  3409. }
  3410. if ( position.z < min.z ) {
  3411. min.z = position.z;
  3412. } else if ( position.z > max.z ) {
  3413. max.z = position.z;
  3414. }
  3415. }
  3416. } else {
  3417. this.boundingBox.min.set( 0, 0, 0 );
  3418. this.boundingBox.max.set( 0, 0, 0 );
  3419. }
  3420. },
  3421. computeBoundingSphere: function () {
  3422. var maxRadiusSq = 0;
  3423. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3424. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3425. var radiusSq = this.vertices[ i ].lengthSq();
  3426. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3427. }
  3428. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3429. },
  3430. /*
  3431. * Checks for duplicate vertices with hashmap.
  3432. * Duplicated vertices are removed
  3433. * and faces' vertices are updated.
  3434. */
  3435. mergeVertices: function () {
  3436. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3437. var unique = [], changes = [];
  3438. var v, key;
  3439. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3440. var precision = Math.pow( 10, precisionPoints );
  3441. var i,il, face;
  3442. var abcd = 'abcd', o, k, j, jl, u;
  3443. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3444. v = this.vertices[ i ];
  3445. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3446. if ( verticesMap[ key ] === undefined ) {
  3447. verticesMap[ key ] = i;
  3448. unique.push( this.vertices[ i ] );
  3449. changes[ i ] = unique.length - 1;
  3450. } else {
  3451. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3452. changes[ i ] = changes[ verticesMap[ key ] ];
  3453. }
  3454. };
  3455. // Start to patch face indices
  3456. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3457. face = this.faces[ i ];
  3458. if ( face instanceof THREE.Face3 ) {
  3459. face.a = changes[ face.a ];
  3460. face.b = changes[ face.b ];
  3461. face.c = changes[ face.c ];
  3462. } else if ( face instanceof THREE.Face4 ) {
  3463. face.a = changes[ face.a ];
  3464. face.b = changes[ face.b ];
  3465. face.c = changes[ face.c ];
  3466. face.d = changes[ face.d ];
  3467. // check dups in (a, b, c, d) and convert to -> face3
  3468. o = [ face.a, face.b, face.c, face.d ];
  3469. for ( k = 3; k > 0; k -- ) {
  3470. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3471. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3472. o.splice( k, 1 );
  3473. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3474. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3475. u = this.faceVertexUvs[ j ][ i ];
  3476. if ( u ) u.splice( k, 1 );
  3477. }
  3478. this.faces[ i ].vertexColors = face.vertexColors;
  3479. break;
  3480. }
  3481. }
  3482. }
  3483. }
  3484. // Use unique set of vertices
  3485. var diff = this.vertices.length - unique.length;
  3486. this.vertices = unique;
  3487. return diff;
  3488. },
  3489. clone: function () {
  3490. var geometry = new THREE.Geometry();
  3491. var vertices = this.vertices;
  3492. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3493. geometry.vertices.push( vertices[ i ].clone() );
  3494. }
  3495. var faces = this.faces;
  3496. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  3497. geometry.faces.push( faces[ i ].clone() );
  3498. }
  3499. var uvs = this.faceVertexUvs[ 0 ];
  3500. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  3501. var uv = uvs[ i ], uvCopy = [];
  3502. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  3503. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  3504. }
  3505. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  3506. }
  3507. return geometry;
  3508. },
  3509. deallocate: function () {
  3510. var index = THREE.GeometryLibrary.indexOf( this );
  3511. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3512. }
  3513. };
  3514. THREE.GeometryIdCount = 0;
  3515. THREE.GeometryLibrary = [];
  3516. /**
  3517. * @author alteredq / http://alteredqualia.com/
  3518. */
  3519. THREE.BufferGeometry = function () {
  3520. THREE.GeometryLibrary.push( this );
  3521. this.id = THREE.GeometryIdCount ++;
  3522. // attributes
  3523. this.attributes = {};
  3524. // attributes typed arrays are kept only if dynamic flag is set
  3525. this.dynamic = false;
  3526. // boundings
  3527. this.boundingBox = null;
  3528. this.boundingSphere = null;
  3529. this.hasTangents = false;
  3530. // for compatibility
  3531. this.morphTargets = [];
  3532. };
  3533. THREE.BufferGeometry.prototype = {
  3534. constructor : THREE.BufferGeometry,
  3535. applyMatrix: function ( matrix ) {
  3536. var positionArray;
  3537. var normalArray;
  3538. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3539. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3540. if ( positionArray !== undefined ) {
  3541. matrix.multiplyVector3Array( positionArray );
  3542. this.verticesNeedUpdate = true;
  3543. }
  3544. if ( normalArray !== undefined ) {
  3545. var normalMatrix = new THREE.Matrix3();
  3546. normalMatrix.getInverse( matrix ).transpose();
  3547. normalMatrix.multiplyVector3Array( normalArray );
  3548. this.normalizeNormals();
  3549. this.normalsNeedUpdate = true;
  3550. }
  3551. },
  3552. computeBoundingBox: function () {
  3553. if ( ! this.boundingBox ) {
  3554. this.boundingBox = {
  3555. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3556. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3557. };
  3558. }
  3559. var positions = this.attributes[ "position" ].array;
  3560. if ( positions ) {
  3561. var bb = this.boundingBox;
  3562. var x, y, z;
  3563. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3564. x = positions[ i ];
  3565. y = positions[ i + 1 ];
  3566. z = positions[ i + 2 ];
  3567. // bounding box
  3568. if ( x < bb.min.x ) {
  3569. bb.min.x = x;
  3570. } else if ( x > bb.max.x ) {
  3571. bb.max.x = x;
  3572. }
  3573. if ( y < bb.min.y ) {
  3574. bb.min.y = y;
  3575. } else if ( y > bb.max.y ) {
  3576. bb.max.y = y;
  3577. }
  3578. if ( z < bb.min.z ) {
  3579. bb.min.z = z;
  3580. } else if ( z > bb.max.z ) {
  3581. bb.max.z = z;
  3582. }
  3583. }
  3584. }
  3585. if ( positions === undefined || positions.length === 0 ) {
  3586. this.boundingBox.min.set( 0, 0, 0 );
  3587. this.boundingBox.max.set( 0, 0, 0 );
  3588. }
  3589. },
  3590. computeBoundingSphere: function () {
  3591. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3592. var positions = this.attributes[ "position" ].array;
  3593. if ( positions ) {
  3594. var radiusSq, maxRadiusSq = 0;
  3595. var x, y, z;
  3596. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3597. x = positions[ i ];
  3598. y = positions[ i + 1 ];
  3599. z = positions[ i + 2 ];
  3600. radiusSq = x * x + y * y + z * z;
  3601. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3602. }
  3603. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3604. }
  3605. },
  3606. computeVertexNormals: function () {
  3607. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  3608. var i, il;
  3609. var j, jl;
  3610. var nVertexElements = this.attributes[ "position" ].array.length;
  3611. if ( this.attributes[ "normal" ] === undefined ) {
  3612. this.attributes[ "normal" ] = {
  3613. itemSize: 3,
  3614. array: new Float32Array( nVertexElements ),
  3615. numItems: nVertexElements
  3616. };
  3617. } else {
  3618. // reset existing normals to zero
  3619. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3620. this.attributes[ "normal" ].array[ i ] = 0;
  3621. }
  3622. }
  3623. var offsets = this.offsets;
  3624. var indices = this.attributes[ "index" ].array;
  3625. var positions = this.attributes[ "position" ].array;
  3626. var normals = this.attributes[ "normal" ].array;
  3627. var vA, vB, vC, x, y, z,
  3628. pA = new THREE.Vector3(),
  3629. pB = new THREE.Vector3(),
  3630. pC = new THREE.Vector3(),
  3631. cb = new THREE.Vector3(),
  3632. ab = new THREE.Vector3();
  3633. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3634. var start = offsets[ j ].start;
  3635. var count = offsets[ j ].count;
  3636. var index = offsets[ j ].index;
  3637. for ( i = start, il = start + count; i < il; i += 3 ) {
  3638. vA = index + indices[ i ];
  3639. vB = index + indices[ i + 1 ];
  3640. vC = index + indices[ i + 2 ];
  3641. x = positions[ vA * 3 ];
  3642. y = positions[ vA * 3 + 1 ];
  3643. z = positions[ vA * 3 + 2 ];
  3644. pA.set( x, y, z );
  3645. x = positions[ vB * 3 ];
  3646. y = positions[ vB * 3 + 1 ];
  3647. z = positions[ vB * 3 + 2 ];
  3648. pB.set( x, y, z );
  3649. x = positions[ vC * 3 ];
  3650. y = positions[ vC * 3 + 1 ];
  3651. z = positions[ vC * 3 + 2 ];
  3652. pC.set( x, y, z );
  3653. cb.sub( pC, pB );
  3654. ab.sub( pA, pB );
  3655. cb.crossSelf( ab );
  3656. normals[ vA * 3 ] += cb.x;
  3657. normals[ vA * 3 + 1 ] += cb.y;
  3658. normals[ vA * 3 + 2 ] += cb.z;
  3659. normals[ vB * 3 ] += cb.x;
  3660. normals[ vB * 3 + 1 ] += cb.y;
  3661. normals[ vB * 3 + 2 ] += cb.z;
  3662. normals[ vC * 3 ] += cb.x;
  3663. normals[ vC * 3 + 1 ] += cb.y;
  3664. normals[ vC * 3 + 2 ] += cb.z;
  3665. }
  3666. }
  3667. this.normalizeNormals();
  3668. this.normalsNeedUpdate = true;
  3669. }
  3670. },
  3671. normalizeNormals: function () {
  3672. var normals = this.attributes[ "normal" ].array;
  3673. var x, y, z, n;
  3674. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  3675. x = normals[ i ];
  3676. y = normals[ i + 1 ];
  3677. z = normals[ i + 2 ];
  3678. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3679. normals[ i ] *= n;
  3680. normals[ i + 1 ] *= n;
  3681. normals[ i + 2 ] *= n;
  3682. }
  3683. },
  3684. computeTangents: function () {
  3685. // based on http://www.terathon.com/code/tangent.html
  3686. // (per vertex tangents)
  3687. if ( this.attributes[ "index" ] === undefined ||
  3688. this.attributes[ "position" ] === undefined ||
  3689. this.attributes[ "normal" ] === undefined ||
  3690. this.attributes[ "uv" ] === undefined ) {
  3691. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3692. return;
  3693. }
  3694. var indices = this.attributes[ "index" ].array;
  3695. var positions = this.attributes[ "position" ].array;
  3696. var normals = this.attributes[ "normal" ].array;
  3697. var uvs = this.attributes[ "uv" ].array;
  3698. var nVertices = positions.length / 3;
  3699. if ( this.attributes[ "tangent" ] === undefined ) {
  3700. var nTangentElements = 4 * nVertices;
  3701. this.attributes[ "tangent" ] = {
  3702. itemSize: 4,
  3703. array: new Float32Array( nTangentElements ),
  3704. numItems: nTangentElements
  3705. };
  3706. }
  3707. var tangents = this.attributes[ "tangent" ].array;
  3708. var tan1 = [], tan2 = [];
  3709. for ( var k = 0; k < nVertices; k ++ ) {
  3710. tan1[ k ] = new THREE.Vector3();
  3711. tan2[ k ] = new THREE.Vector3();
  3712. }
  3713. var xA, yA, zA,
  3714. xB, yB, zB,
  3715. xC, yC, zC,
  3716. uA, vA,
  3717. uB, vB,
  3718. uC, vC,
  3719. x1, x2, y1, y2, z1, z2,
  3720. s1, s2, t1, t2, r;
  3721. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3722. function handleTriangle( a, b, c ) {
  3723. xA = positions[ a * 3 ];
  3724. yA = positions[ a * 3 + 1 ];
  3725. zA = positions[ a * 3 + 2 ];
  3726. xB = positions[ b * 3 ];
  3727. yB = positions[ b * 3 + 1 ];
  3728. zB = positions[ b * 3 + 2 ];
  3729. xC = positions[ c * 3 ];
  3730. yC = positions[ c * 3 + 1 ];
  3731. zC = positions[ c * 3 + 2 ];
  3732. uA = uvs[ a * 2 ];
  3733. vA = uvs[ a * 2 + 1 ];
  3734. uB = uvs[ b * 2 ];
  3735. vB = uvs[ b * 2 + 1 ];
  3736. uC = uvs[ c * 2 ];
  3737. vC = uvs[ c * 2 + 1 ];
  3738. x1 = xB - xA;
  3739. x2 = xC - xA;
  3740. y1 = yB - yA;
  3741. y2 = yC - yA;
  3742. z1 = zB - zA;
  3743. z2 = zC - zA;
  3744. s1 = uB - uA;
  3745. s2 = uC - uA;
  3746. t1 = vB - vA;
  3747. t2 = vC - vA;
  3748. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3749. sdir.set(
  3750. ( t2 * x1 - t1 * x2 ) * r,
  3751. ( t2 * y1 - t1 * y2 ) * r,
  3752. ( t2 * z1 - t1 * z2 ) * r
  3753. );
  3754. tdir.set(
  3755. ( s1 * x2 - s2 * x1 ) * r,
  3756. ( s1 * y2 - s2 * y1 ) * r,
  3757. ( s1 * z2 - s2 * z1 ) * r
  3758. );
  3759. tan1[ a ].addSelf( sdir );
  3760. tan1[ b ].addSelf( sdir );
  3761. tan1[ c ].addSelf( sdir );
  3762. tan2[ a ].addSelf( tdir );
  3763. tan2[ b ].addSelf( tdir );
  3764. tan2[ c ].addSelf( tdir );
  3765. }
  3766. var i, il;
  3767. var j, jl;
  3768. var iA, iB, iC;
  3769. var offsets = this.offsets;
  3770. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3771. var start = offsets[ j ].start;
  3772. var count = offsets[ j ].count;
  3773. var index = offsets[ j ].index;
  3774. for ( i = start, il = start + count; i < il; i += 3 ) {
  3775. iA = index + indices[ i ];
  3776. iB = index + indices[ i + 1 ];
  3777. iC = index + indices[ i + 2 ];
  3778. handleTriangle( iA, iB, iC );
  3779. }
  3780. }
  3781. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3782. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3783. var w, t, test;
  3784. var nx, ny, nz;
  3785. function handleVertex( v ) {
  3786. n.x = normals[ v * 3 ];
  3787. n.y = normals[ v * 3 + 1 ];
  3788. n.z = normals[ v * 3 + 2 ];
  3789. n2.copy( n );
  3790. t = tan1[ v ];
  3791. // Gram-Schmidt orthogonalize
  3792. tmp.copy( t );
  3793. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3794. // Calculate handedness
  3795. tmp2.cross( n2, t );
  3796. test = tmp2.dot( tan2[ v ] );
  3797. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3798. tangents[ v * 4 ] = tmp.x;
  3799. tangents[ v * 4 + 1 ] = tmp.y;
  3800. tangents[ v * 4 + 2 ] = tmp.z;
  3801. tangents[ v * 4 + 3 ] = w;
  3802. }
  3803. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3804. var start = offsets[ j ].start;
  3805. var count = offsets[ j ].count;
  3806. var index = offsets[ j ].index;
  3807. for ( i = start, il = start + count; i < il; i += 3 ) {
  3808. iA = index + indices[ i ];
  3809. iB = index + indices[ i + 1 ];
  3810. iC = index + indices[ i + 2 ];
  3811. handleVertex( iA );
  3812. handleVertex( iB );
  3813. handleVertex( iC );
  3814. }
  3815. }
  3816. this.hasTangents = true;
  3817. this.tangentsNeedUpdate = true;
  3818. },
  3819. deallocate: function () {
  3820. var index = THREE.GeometryLibrary.indexOf( this );
  3821. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3822. }
  3823. };
  3824. /**
  3825. * Spline from Tween.js, slightly optimized (and trashed)
  3826. * http://sole.github.com/tween.js/examples/05_spline.html
  3827. *
  3828. * @author mrdoob / http://mrdoob.com/
  3829. * @author alteredq / http://alteredqualia.com/
  3830. */
  3831. THREE.Spline = function ( points ) {
  3832. this.points = points;
  3833. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3834. point, intPoint, weight, w2, w3,
  3835. pa, pb, pc, pd;
  3836. this.initFromArray = function( a ) {
  3837. this.points = [];
  3838. for ( var i = 0; i < a.length; i++ ) {
  3839. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3840. }
  3841. };
  3842. this.getPoint = function ( k ) {
  3843. point = ( this.points.length - 1 ) * k;
  3844. intPoint = Math.floor( point );
  3845. weight = point - intPoint;
  3846. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3847. c[ 1 ] = intPoint;
  3848. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3849. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3850. pa = this.points[ c[ 0 ] ];
  3851. pb = this.points[ c[ 1 ] ];
  3852. pc = this.points[ c[ 2 ] ];
  3853. pd = this.points[ c[ 3 ] ];
  3854. w2 = weight * weight;
  3855. w3 = weight * w2;
  3856. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3857. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3858. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3859. return v3;
  3860. };
  3861. this.getControlPointsArray = function () {
  3862. var i, p, l = this.points.length,
  3863. coords = [];
  3864. for ( i = 0; i < l; i ++ ) {
  3865. p = this.points[ i ];
  3866. coords[ i ] = [ p.x, p.y, p.z ];
  3867. }
  3868. return coords;
  3869. };
  3870. // approximate length by summing linear segments
  3871. this.getLength = function ( nSubDivisions ) {
  3872. var i, index, nSamples, position,
  3873. point = 0, intPoint = 0, oldIntPoint = 0,
  3874. oldPosition = new THREE.Vector3(),
  3875. tmpVec = new THREE.Vector3(),
  3876. chunkLengths = [],
  3877. totalLength = 0;
  3878. // first point has 0 length
  3879. chunkLengths[ 0 ] = 0;
  3880. if ( !nSubDivisions ) nSubDivisions = 100;
  3881. nSamples = this.points.length * nSubDivisions;
  3882. oldPosition.copy( this.points[ 0 ] );
  3883. for ( i = 1; i < nSamples; i ++ ) {
  3884. index = i / nSamples;
  3885. position = this.getPoint( index );
  3886. tmpVec.copy( position );
  3887. totalLength += tmpVec.distanceTo( oldPosition );
  3888. oldPosition.copy( position );
  3889. point = ( this.points.length - 1 ) * index;
  3890. intPoint = Math.floor( point );
  3891. if ( intPoint != oldIntPoint ) {
  3892. chunkLengths[ intPoint ] = totalLength;
  3893. oldIntPoint = intPoint;
  3894. }
  3895. }
  3896. // last point ends with total length
  3897. chunkLengths[ chunkLengths.length ] = totalLength;
  3898. return { chunks: chunkLengths, total: totalLength };
  3899. };
  3900. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3901. var i, j,
  3902. index, indexCurrent, indexNext,
  3903. linearDistance, realDistance,
  3904. sampling, position,
  3905. newpoints = [],
  3906. tmpVec = new THREE.Vector3(),
  3907. sl = this.getLength();
  3908. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3909. for ( i = 1; i < this.points.length; i++ ) {
  3910. //tmpVec.copy( this.points[ i - 1 ] );
  3911. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3912. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3913. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3914. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3915. indexNext = i / ( this.points.length - 1 );
  3916. for ( j = 1; j < sampling - 1; j++ ) {
  3917. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3918. position = this.getPoint( index );
  3919. newpoints.push( tmpVec.copy( position ).clone() );
  3920. }
  3921. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3922. }
  3923. this.points = newpoints;
  3924. };
  3925. // Catmull-Rom
  3926. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3927. var v0 = ( p2 - p0 ) * 0.5,
  3928. v1 = ( p3 - p1 ) * 0.5;
  3929. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3930. };
  3931. };
  3932. /**
  3933. * @author mrdoob / http://mrdoob.com/
  3934. * @author mikael emtinger / http://gomo.se/
  3935. */
  3936. THREE.Camera = function () {
  3937. THREE.Object3D.call( this );
  3938. this.matrixWorldInverse = new THREE.Matrix4();
  3939. this.projectionMatrix = new THREE.Matrix4();
  3940. this.projectionMatrixInverse = new THREE.Matrix4();
  3941. };
  3942. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3943. THREE.Camera.prototype.lookAt = function ( vector ) {
  3944. // TODO: Add hierarchy support.
  3945. this.matrix.lookAt( this.position, vector, this.up );
  3946. if ( this.rotationAutoUpdate === true ) {
  3947. if ( this.useQuaternion === false ) {
  3948. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3949. } else {
  3950. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3951. }
  3952. }
  3953. };
  3954. /**
  3955. * @author alteredq / http://alteredqualia.com/
  3956. */
  3957. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3958. THREE.Camera.call( this );
  3959. this.left = left;
  3960. this.right = right;
  3961. this.top = top;
  3962. this.bottom = bottom;
  3963. this.near = ( near !== undefined ) ? near : 0.1;
  3964. this.far = ( far !== undefined ) ? far : 2000;
  3965. this.updateProjectionMatrix();
  3966. };
  3967. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  3968. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  3969. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  3970. };
  3971. /**
  3972. * @author mrdoob / http://mrdoob.com/
  3973. * @author greggman / http://games.greggman.com/
  3974. * @author zz85 / http://www.lab4games.net/zz85/blog
  3975. */
  3976. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  3977. THREE.Camera.call( this );
  3978. this.fov = fov !== undefined ? fov : 50;
  3979. this.aspect = aspect !== undefined ? aspect : 1;
  3980. this.near = near !== undefined ? near : 0.1;
  3981. this.far = far !== undefined ? far : 2000;
  3982. this.updateProjectionMatrix();
  3983. };
  3984. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  3985. /**
  3986. * Uses Focal Length (in mm) to estimate and set FOV
  3987. * 35mm (fullframe) camera is used if frame size is not specified;
  3988. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3989. */
  3990. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3991. if ( frameHeight === undefined ) frameHeight = 24;
  3992. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3993. this.updateProjectionMatrix();
  3994. }
  3995. /**
  3996. * Sets an offset in a larger frustum. This is useful for multi-window or
  3997. * multi-monitor/multi-machine setups.
  3998. *
  3999. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  4000. * the monitors are in grid like this
  4001. *
  4002. * +---+---+---+
  4003. * | A | B | C |
  4004. * +---+---+---+
  4005. * | D | E | F |
  4006. * +---+---+---+
  4007. *
  4008. * then for each monitor you would call it like this
  4009. *
  4010. * var w = 1920;
  4011. * var h = 1080;
  4012. * var fullWidth = w * 3;
  4013. * var fullHeight = h * 2;
  4014. *
  4015. * --A--
  4016. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4017. * --B--
  4018. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4019. * --C--
  4020. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4021. * --D--
  4022. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4023. * --E--
  4024. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4025. * --F--
  4026. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4027. *
  4028. * Note there is no reason monitors have to be the same size or in a grid.
  4029. */
  4030. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4031. this.fullWidth = fullWidth;
  4032. this.fullHeight = fullHeight;
  4033. this.x = x;
  4034. this.y = y;
  4035. this.width = width;
  4036. this.height = height;
  4037. this.updateProjectionMatrix();
  4038. };
  4039. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4040. if ( this.fullWidth ) {
  4041. var aspect = this.fullWidth / this.fullHeight;
  4042. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  4043. var bottom = -top;
  4044. var left = aspect * bottom;
  4045. var right = aspect * top;
  4046. var width = Math.abs( right - left );
  4047. var height = Math.abs( top - bottom );
  4048. this.projectionMatrix.makeFrustum(
  4049. left + this.x * width / this.fullWidth,
  4050. left + ( this.x + this.width ) * width / this.fullWidth,
  4051. top - ( this.y + this.height ) * height / this.fullHeight,
  4052. top - this.y * height / this.fullHeight,
  4053. this.near,
  4054. this.far
  4055. );
  4056. } else {
  4057. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4058. }
  4059. };
  4060. /**
  4061. * @author mrdoob / http://mrdoob.com/
  4062. * @author alteredq / http://alteredqualia.com/
  4063. */
  4064. THREE.Light = function ( hex ) {
  4065. THREE.Object3D.call( this );
  4066. this.color = new THREE.Color( hex );
  4067. };
  4068. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4069. /**
  4070. * @author mrdoob / http://mrdoob.com/
  4071. */
  4072. THREE.AmbientLight = function ( hex ) {
  4073. THREE.Light.call( this, hex );
  4074. };
  4075. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4076. /**
  4077. * @author mrdoob / http://mrdoob.com/
  4078. * @author alteredq / http://alteredqualia.com/
  4079. */
  4080. THREE.DirectionalLight = function ( hex, intensity ) {
  4081. THREE.Light.call( this, hex );
  4082. this.position = new THREE.Vector3( 0, 1, 0 );
  4083. this.target = new THREE.Object3D();
  4084. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4085. this.castShadow = false;
  4086. this.onlyShadow = false;
  4087. //
  4088. this.shadowCameraNear = 50;
  4089. this.shadowCameraFar = 5000;
  4090. this.shadowCameraLeft = -500;
  4091. this.shadowCameraRight = 500;
  4092. this.shadowCameraTop = 500;
  4093. this.shadowCameraBottom = -500;
  4094. this.shadowCameraVisible = false;
  4095. this.shadowBias = 0;
  4096. this.shadowDarkness = 0.5;
  4097. this.shadowMapWidth = 512;
  4098. this.shadowMapHeight = 512;
  4099. //
  4100. this.shadowCascade = false;
  4101. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  4102. this.shadowCascadeCount = 2;
  4103. this.shadowCascadeBias = [ 0, 0, 0 ];
  4104. this.shadowCascadeWidth = [ 512, 512, 512 ];
  4105. this.shadowCascadeHeight = [ 512, 512, 512 ];
  4106. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  4107. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  4108. this.shadowCascadeArray = [];
  4109. //
  4110. this.shadowMap = null;
  4111. this.shadowMapSize = null;
  4112. this.shadowCamera = null;
  4113. this.shadowMatrix = null;
  4114. };
  4115. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  4116. /**
  4117. * @author alteredq / http://alteredqualia.com/
  4118. */
  4119. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  4120. THREE.Light.call( this, skyColorHex );
  4121. this.groundColor = new THREE.Color( groundColorHex );
  4122. this.position = new THREE.Vector3( 0, 100, 0 );
  4123. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4124. };
  4125. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  4126. /**
  4127. * @author mrdoob / http://mrdoob.com/
  4128. */
  4129. THREE.PointLight = function ( hex, intensity, distance ) {
  4130. THREE.Light.call( this, hex );
  4131. this.position = new THREE.Vector3( 0, 0, 0 );
  4132. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4133. this.distance = ( distance !== undefined ) ? distance : 0;
  4134. };
  4135. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  4136. /**
  4137. * @author alteredq / http://alteredqualia.com/
  4138. */
  4139. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  4140. THREE.Light.call( this, hex );
  4141. this.position = new THREE.Vector3( 0, 1, 0 );
  4142. this.target = new THREE.Object3D();
  4143. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4144. this.distance = ( distance !== undefined ) ? distance : 0;
  4145. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  4146. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  4147. this.castShadow = false;
  4148. this.onlyShadow = false;
  4149. //
  4150. this.shadowCameraNear = 50;
  4151. this.shadowCameraFar = 5000;
  4152. this.shadowCameraFov = 50;
  4153. this.shadowCameraVisible = false;
  4154. this.shadowBias = 0;
  4155. this.shadowDarkness = 0.5;
  4156. this.shadowMapWidth = 512;
  4157. this.shadowMapHeight = 512;
  4158. //
  4159. this.shadowMap = null;
  4160. this.shadowMapSize = null;
  4161. this.shadowCamera = null;
  4162. this.shadowMatrix = null;
  4163. };
  4164. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4165. /**
  4166. * @author alteredq / http://alteredqualia.com/
  4167. */
  4168. THREE.Loader = function ( showStatus ) {
  4169. this.showStatus = showStatus;
  4170. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4171. this.onLoadStart = function () {};
  4172. this.onLoadProgress = function () {};
  4173. this.onLoadComplete = function () {};
  4174. };
  4175. THREE.Loader.prototype = {
  4176. constructor: THREE.Loader,
  4177. crossOrigin: 'anonymous',
  4178. addStatusElement: function () {
  4179. var e = document.createElement( "div" );
  4180. e.style.position = "absolute";
  4181. e.style.right = "0px";
  4182. e.style.top = "0px";
  4183. e.style.fontSize = "0.8em";
  4184. e.style.textAlign = "left";
  4185. e.style.background = "rgba(0,0,0,0.25)";
  4186. e.style.color = "#fff";
  4187. e.style.width = "120px";
  4188. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4189. e.style.zIndex = 1000;
  4190. e.innerHTML = "Loading ...";
  4191. return e;
  4192. },
  4193. updateProgress: function ( progress ) {
  4194. var message = "Loaded ";
  4195. if ( progress.total ) {
  4196. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4197. } else {
  4198. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4199. }
  4200. this.statusDomElement.innerHTML = message;
  4201. },
  4202. extractUrlBase: function ( url ) {
  4203. var parts = url.split( '/' );
  4204. parts.pop();
  4205. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4206. },
  4207. initMaterials: function ( materials, texturePath ) {
  4208. var array = [];
  4209. for ( var i = 0; i < materials.length; ++ i ) {
  4210. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4211. }
  4212. return array;
  4213. },
  4214. needsTangents: function ( materials ) {
  4215. for( var i = 0, il = materials.length; i < il; i ++ ) {
  4216. var m = materials[ i ];
  4217. if ( m instanceof THREE.ShaderMaterial ) return true;
  4218. }
  4219. return false;
  4220. },
  4221. createMaterial: function ( m, texturePath ) {
  4222. var _this = this;
  4223. function is_pow2( n ) {
  4224. var l = Math.log( n ) / Math.LN2;
  4225. return Math.floor( l ) == l;
  4226. }
  4227. function nearest_pow2( n ) {
  4228. var l = Math.log( n ) / Math.LN2;
  4229. return Math.pow( 2, Math.round( l ) );
  4230. }
  4231. function load_image( where, url ) {
  4232. var image = new Image();
  4233. image.onload = function () {
  4234. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4235. var width = nearest_pow2( this.width );
  4236. var height = nearest_pow2( this.height );
  4237. where.image.width = width;
  4238. where.image.height = height;
  4239. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4240. } else {
  4241. where.image = this;
  4242. }
  4243. where.needsUpdate = true;
  4244. };
  4245. image.crossOrigin = _this.crossOrigin;
  4246. image.src = url;
  4247. }
  4248. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4249. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4250. var fullPath = texturePath + "/" + sourceFile;
  4251. if ( isCompressed ) {
  4252. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4253. where[ name ] = texture;
  4254. } else {
  4255. var texture = document.createElement( 'canvas' );
  4256. where[ name ] = new THREE.Texture( texture );
  4257. }
  4258. where[ name ].sourceFile = sourceFile;
  4259. if( repeat ) {
  4260. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4261. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4262. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4263. }
  4264. if ( offset ) {
  4265. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4266. }
  4267. if ( wrap ) {
  4268. var wrapMap = {
  4269. "repeat": THREE.RepeatWrapping,
  4270. "mirror": THREE.MirroredRepeatWrapping
  4271. }
  4272. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4273. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4274. }
  4275. if ( anisotropy ) {
  4276. where[ name ].anisotropy = anisotropy;
  4277. }
  4278. if ( ! isCompressed ) {
  4279. load_image( where[ name ], fullPath );
  4280. }
  4281. }
  4282. function rgb2hex( rgb ) {
  4283. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4284. }
  4285. // defaults
  4286. var mtype = "MeshLambertMaterial";
  4287. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4288. // parameters from model file
  4289. if ( m.shading ) {
  4290. var shading = m.shading.toLowerCase();
  4291. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4292. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4293. }
  4294. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4295. mpars.blending = THREE[ m.blending ];
  4296. }
  4297. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4298. mpars.transparent = m.transparent;
  4299. }
  4300. if ( m.depthTest !== undefined ) {
  4301. mpars.depthTest = m.depthTest;
  4302. }
  4303. if ( m.depthWrite !== undefined ) {
  4304. mpars.depthWrite = m.depthWrite;
  4305. }
  4306. if ( m.visible !== undefined ) {
  4307. mpars.visible = m.visible;
  4308. }
  4309. if ( m.flipSided !== undefined ) {
  4310. mpars.side = THREE.BackSide;
  4311. }
  4312. if ( m.doubleSided !== undefined ) {
  4313. mpars.side = THREE.DoubleSide;
  4314. }
  4315. if ( m.wireframe !== undefined ) {
  4316. mpars.wireframe = m.wireframe;
  4317. }
  4318. if ( m.vertexColors !== undefined ) {
  4319. if ( m.vertexColors === "face" ) {
  4320. mpars.vertexColors = THREE.FaceColors;
  4321. } else if ( m.vertexColors ) {
  4322. mpars.vertexColors = THREE.VertexColors;
  4323. }
  4324. }
  4325. // colors
  4326. if ( m.colorDiffuse ) {
  4327. mpars.color = rgb2hex( m.colorDiffuse );
  4328. } else if ( m.DbgColor ) {
  4329. mpars.color = m.DbgColor;
  4330. }
  4331. if ( m.colorSpecular ) {
  4332. mpars.specular = rgb2hex( m.colorSpecular );
  4333. }
  4334. if ( m.colorAmbient ) {
  4335. mpars.ambient = rgb2hex( m.colorAmbient );
  4336. }
  4337. // modifiers
  4338. if ( m.transparency ) {
  4339. mpars.opacity = m.transparency;
  4340. }
  4341. if ( m.specularCoef ) {
  4342. mpars.shininess = m.specularCoef;
  4343. }
  4344. // textures
  4345. if ( m.mapDiffuse && texturePath ) {
  4346. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  4347. }
  4348. if ( m.mapLight && texturePath ) {
  4349. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  4350. }
  4351. if ( m.mapBump && texturePath ) {
  4352. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  4353. }
  4354. if ( m.mapNormal && texturePath ) {
  4355. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  4356. }
  4357. if ( m.mapSpecular && texturePath ) {
  4358. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  4359. }
  4360. //
  4361. if ( m.mapBumpScale ) {
  4362. mpars.bumpScale = m.mapBumpScale;
  4363. }
  4364. // special case for normal mapped material
  4365. if ( m.mapNormal ) {
  4366. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4367. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4368. uniforms[ "tNormal" ].value = mpars.normalMap;
  4369. if ( m.mapNormalFactor ) {
  4370. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  4371. }
  4372. if ( mpars.map ) {
  4373. uniforms[ "tDiffuse" ].value = mpars.map;
  4374. uniforms[ "enableDiffuse" ].value = true;
  4375. }
  4376. if ( mpars.specularMap ) {
  4377. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4378. uniforms[ "enableSpecular" ].value = true;
  4379. }
  4380. if ( mpars.lightMap ) {
  4381. uniforms[ "tAO" ].value = mpars.lightMap;
  4382. uniforms[ "enableAO" ].value = true;
  4383. }
  4384. // for the moment don't handle displacement texture
  4385. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4386. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4387. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4388. uniforms[ "uShininess" ].value = mpars.shininess;
  4389. if ( mpars.opacity !== undefined ) {
  4390. uniforms[ "uOpacity" ].value = mpars.opacity;
  4391. }
  4392. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4393. var material = new THREE.ShaderMaterial( parameters );
  4394. } else {
  4395. var material = new THREE[ mtype ]( mpars );
  4396. }
  4397. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4398. return material;
  4399. }
  4400. };
  4401. /**
  4402. * @author alteredq / http://alteredqualia.com/
  4403. */
  4404. THREE.BinaryLoader = function ( showStatus ) {
  4405. THREE.Loader.call( this, showStatus );
  4406. };
  4407. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4408. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4409. // - binary models consist of two files: JS and BIN
  4410. // - parameters
  4411. // - url (required)
  4412. // - callback (required)
  4413. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4414. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4415. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4416. // todo: unify load API to for easier SceneLoader use
  4417. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4418. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  4419. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4420. this.onLoadStart();
  4421. // #1 load JS part via web worker
  4422. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4423. };
  4424. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4425. var xhr = new XMLHttpRequest();
  4426. xhr.onreadystatechange = function () {
  4427. if ( xhr.readyState == 4 ) {
  4428. if ( xhr.status == 200 || xhr.status == 0 ) {
  4429. var json = JSON.parse( xhr.responseText );
  4430. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4431. } else {
  4432. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4433. }
  4434. }
  4435. };
  4436. xhr.open( "GET", url, true );
  4437. xhr.send( null );
  4438. };
  4439. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4440. var xhr = new XMLHttpRequest(),
  4441. url = binaryPath + "/" + json.buffers;
  4442. var length = 0;
  4443. xhr.onreadystatechange = function () {
  4444. if ( xhr.readyState == 4 ) {
  4445. if ( xhr.status == 200 || xhr.status == 0 ) {
  4446. var buffer = xhr.response;
  4447. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4448. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4449. } else {
  4450. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4451. }
  4452. } else if ( xhr.readyState == 3 ) {
  4453. if ( callbackProgress ) {
  4454. if ( length == 0 ) {
  4455. length = xhr.getResponseHeader( "Content-Length" );
  4456. }
  4457. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4458. }
  4459. } else if ( xhr.readyState == 2 ) {
  4460. length = xhr.getResponseHeader( "Content-Length" );
  4461. }
  4462. };
  4463. xhr.open( "GET", url, true );
  4464. xhr.responseType = "arraybuffer";
  4465. xhr.send( null );
  4466. };
  4467. // Binary AJAX parser
  4468. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  4469. var Model = function ( texturePath ) {
  4470. var scope = this,
  4471. currentOffset = 0,
  4472. md,
  4473. normals = [],
  4474. uvs = [],
  4475. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4476. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4477. tri_size, quad_size,
  4478. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4479. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4480. THREE.Geometry.call( this );
  4481. md = parseMetaData( data, currentOffset );
  4482. currentOffset += md.header_bytes;
  4483. /*
  4484. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4485. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4486. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4487. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4488. */
  4489. // buffers sizes
  4490. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4491. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4492. len_tri_flat = md.ntri_flat * ( tri_size );
  4493. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4494. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4495. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4496. len_quad_flat = md.nquad_flat * ( quad_size );
  4497. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4498. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4499. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4500. // read buffers
  4501. currentOffset += init_vertices( currentOffset );
  4502. currentOffset += init_normals( currentOffset );
  4503. currentOffset += handlePadding( md.nnormals * 3 );
  4504. currentOffset += init_uvs( currentOffset );
  4505. start_tri_flat = currentOffset;
  4506. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4507. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4508. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4509. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4510. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4511. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4512. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4513. // have to first process faces with uvs
  4514. // so that face and uv indices match
  4515. init_triangles_flat_uv( start_tri_flat_uv );
  4516. init_triangles_smooth_uv( start_tri_smooth_uv );
  4517. init_quads_flat_uv( start_quad_flat_uv );
  4518. init_quads_smooth_uv( start_quad_smooth_uv );
  4519. // now we can process untextured faces
  4520. init_triangles_flat( start_tri_flat );
  4521. init_triangles_smooth( start_tri_smooth );
  4522. init_quads_flat( start_quad_flat );
  4523. init_quads_smooth( start_quad_smooth );
  4524. this.computeCentroids();
  4525. this.computeFaceNormals();
  4526. function handlePadding( n ) {
  4527. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4528. };
  4529. function parseMetaData( data, offset ) {
  4530. var metaData = {
  4531. 'signature' :parseString( data, offset, 12 ),
  4532. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4533. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4534. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4535. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4536. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4537. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4538. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4539. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4540. 'nvertices' :parseUInt32( data, offset + 20 ),
  4541. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4542. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4543. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4544. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4545. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4546. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4547. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4548. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4549. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4550. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4551. };
  4552. /*
  4553. console.log( "signature: " + metaData.signature );
  4554. console.log( "header_bytes: " + metaData.header_bytes );
  4555. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4556. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4557. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4558. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4559. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4560. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4561. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4562. console.log( "nvertices: " + metaData.nvertices );
  4563. console.log( "nnormals: " + metaData.nnormals );
  4564. console.log( "nuvs: " + metaData.nuvs );
  4565. console.log( "ntri_flat: " + metaData.ntri_flat );
  4566. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4567. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4568. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4569. console.log( "nquad_flat: " + metaData.nquad_flat );
  4570. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4571. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4572. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4573. var total = metaData.header_bytes
  4574. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4575. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4576. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4577. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4578. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4579. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4580. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4581. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4582. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4583. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4584. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4585. console.log( "total bytes: " + total );
  4586. */
  4587. return metaData;
  4588. };
  4589. function parseString( data, offset, length ) {
  4590. var charArray = new Uint8Array( data, offset, length );
  4591. var text = "";
  4592. for ( var i = 0; i < length; i ++ ) {
  4593. text += String.fromCharCode( charArray[ offset + i ] );
  4594. }
  4595. return text;
  4596. };
  4597. function parseUChar8( data, offset ) {
  4598. var charArray = new Uint8Array( data, offset, 1 );
  4599. return charArray[ 0 ];
  4600. };
  4601. function parseUInt32( data, offset ) {
  4602. var intArray = new Uint32Array( data, offset, 1 );
  4603. return intArray[ 0 ];
  4604. };
  4605. function init_vertices( start ) {
  4606. var nElements = md.nvertices;
  4607. var coordArray = new Float32Array( data, start, nElements * 3 );
  4608. var i, x, y, z;
  4609. for( i = 0; i < nElements; i ++ ) {
  4610. x = coordArray[ i * 3 ];
  4611. y = coordArray[ i * 3 + 1 ];
  4612. z = coordArray[ i * 3 + 2 ];
  4613. vertex( scope, x, y, z );
  4614. }
  4615. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4616. };
  4617. function init_normals( start ) {
  4618. var nElements = md.nnormals;
  4619. if ( nElements ) {
  4620. var normalArray = new Int8Array( data, start, nElements * 3 );
  4621. var i, x, y, z;
  4622. for( i = 0; i < nElements; i ++ ) {
  4623. x = normalArray[ i * 3 ];
  4624. y = normalArray[ i * 3 + 1 ];
  4625. z = normalArray[ i * 3 + 2 ];
  4626. normals.push( x/127, y/127, z/127 );
  4627. }
  4628. }
  4629. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4630. };
  4631. function init_uvs( start ) {
  4632. var nElements = md.nuvs;
  4633. if ( nElements ) {
  4634. var uvArray = new Float32Array( data, start, nElements * 2 );
  4635. var i, u, v;
  4636. for( i = 0; i < nElements; i ++ ) {
  4637. u = uvArray[ i * 2 ];
  4638. v = uvArray[ i * 2 + 1 ];
  4639. uvs.push( u, v );
  4640. }
  4641. }
  4642. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4643. };
  4644. function init_uvs3( nElements, offset ) {
  4645. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4646. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4647. for( i = 0; i < nElements; i ++ ) {
  4648. uva = uvIndexBuffer[ i * 3 ];
  4649. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4650. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4651. u1 = uvs[ uva*2 ];
  4652. v1 = uvs[ uva*2 + 1 ];
  4653. u2 = uvs[ uvb*2 ];
  4654. v2 = uvs[ uvb*2 + 1 ];
  4655. u3 = uvs[ uvc*2 ];
  4656. v3 = uvs[ uvc*2 + 1 ];
  4657. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4658. }
  4659. };
  4660. function init_uvs4( nElements, offset ) {
  4661. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4662. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4663. for( i = 0; i < nElements; i ++ ) {
  4664. uva = uvIndexBuffer[ i * 4 ];
  4665. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4666. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4667. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4668. u1 = uvs[ uva*2 ];
  4669. v1 = uvs[ uva*2 + 1 ];
  4670. u2 = uvs[ uvb*2 ];
  4671. v2 = uvs[ uvb*2 + 1 ];
  4672. u3 = uvs[ uvc*2 ];
  4673. v3 = uvs[ uvc*2 + 1 ];
  4674. u4 = uvs[ uvd*2 ];
  4675. v4 = uvs[ uvd*2 + 1 ];
  4676. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4677. }
  4678. };
  4679. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4680. var i, a, b, c, m;
  4681. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4682. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4683. for( i = 0; i < nElements; i ++ ) {
  4684. a = vertexIndexBuffer[ i * 3 ];
  4685. b = vertexIndexBuffer[ i * 3 + 1 ];
  4686. c = vertexIndexBuffer[ i * 3 + 2 ];
  4687. m = materialIndexBuffer[ i ];
  4688. f3( scope, a, b, c, m );
  4689. }
  4690. };
  4691. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4692. var i, a, b, c, d, m;
  4693. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4694. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4695. for( i = 0; i < nElements; i ++ ) {
  4696. a = vertexIndexBuffer[ i * 4 ];
  4697. b = vertexIndexBuffer[ i * 4 + 1 ];
  4698. c = vertexIndexBuffer[ i * 4 + 2 ];
  4699. d = vertexIndexBuffer[ i * 4 + 3 ];
  4700. m = materialIndexBuffer[ i ];
  4701. f4( scope, a, b, c, d, m );
  4702. }
  4703. };
  4704. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4705. var i, a, b, c, m;
  4706. var na, nb, nc;
  4707. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4708. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4709. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4710. for( i = 0; i < nElements; i ++ ) {
  4711. a = vertexIndexBuffer[ i * 3 ];
  4712. b = vertexIndexBuffer[ i * 3 + 1 ];
  4713. c = vertexIndexBuffer[ i * 3 + 2 ];
  4714. na = normalIndexBuffer[ i * 3 ];
  4715. nb = normalIndexBuffer[ i * 3 + 1 ];
  4716. nc = normalIndexBuffer[ i * 3 + 2 ];
  4717. m = materialIndexBuffer[ i ];
  4718. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4719. }
  4720. };
  4721. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4722. var i, a, b, c, d, m;
  4723. var na, nb, nc, nd;
  4724. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4725. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4726. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4727. for( i = 0; i < nElements; i ++ ) {
  4728. a = vertexIndexBuffer[ i * 4 ];
  4729. b = vertexIndexBuffer[ i * 4 + 1 ];
  4730. c = vertexIndexBuffer[ i * 4 + 2 ];
  4731. d = vertexIndexBuffer[ i * 4 + 3 ];
  4732. na = normalIndexBuffer[ i * 4 ];
  4733. nb = normalIndexBuffer[ i * 4 + 1 ];
  4734. nc = normalIndexBuffer[ i * 4 + 2 ];
  4735. nd = normalIndexBuffer[ i * 4 + 3 ];
  4736. m = materialIndexBuffer[ i ];
  4737. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4738. }
  4739. };
  4740. function init_triangles_flat( start ) {
  4741. var nElements = md.ntri_flat;
  4742. if ( nElements ) {
  4743. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4744. init_faces3_flat( nElements, start, offsetMaterials );
  4745. }
  4746. };
  4747. function init_triangles_flat_uv( start ) {
  4748. var nElements = md.ntri_flat_uv;
  4749. if ( nElements ) {
  4750. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4751. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4752. init_faces3_flat( nElements, start, offsetMaterials );
  4753. init_uvs3( nElements, offsetUvs );
  4754. }
  4755. };
  4756. function init_triangles_smooth( start ) {
  4757. var nElements = md.ntri_smooth;
  4758. if ( nElements ) {
  4759. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4760. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4761. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4762. }
  4763. };
  4764. function init_triangles_smooth_uv( start ) {
  4765. var nElements = md.ntri_smooth_uv;
  4766. if ( nElements ) {
  4767. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4768. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4769. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4770. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4771. init_uvs3( nElements, offsetUvs );
  4772. }
  4773. };
  4774. function init_quads_flat( start ) {
  4775. var nElements = md.nquad_flat;
  4776. if ( nElements ) {
  4777. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4778. init_faces4_flat( nElements, start, offsetMaterials );
  4779. }
  4780. };
  4781. function init_quads_flat_uv( start ) {
  4782. var nElements = md.nquad_flat_uv;
  4783. if ( nElements ) {
  4784. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4785. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4786. init_faces4_flat( nElements, start, offsetMaterials );
  4787. init_uvs4( nElements, offsetUvs );
  4788. }
  4789. };
  4790. function init_quads_smooth( start ) {
  4791. var nElements = md.nquad_smooth;
  4792. if ( nElements ) {
  4793. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4794. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4795. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4796. }
  4797. };
  4798. function init_quads_smooth_uv( start ) {
  4799. var nElements = md.nquad_smooth_uv;
  4800. if ( nElements ) {
  4801. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4802. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4803. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4804. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4805. init_uvs4( nElements, offsetUvs );
  4806. }
  4807. };
  4808. };
  4809. function vertex ( scope, x, y, z ) {
  4810. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4811. };
  4812. function f3 ( scope, a, b, c, mi ) {
  4813. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4814. };
  4815. function f4 ( scope, a, b, c, d, mi ) {
  4816. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4817. };
  4818. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4819. var nax = normals[ na*3 ],
  4820. nay = normals[ na*3 + 1 ],
  4821. naz = normals[ na*3 + 2 ],
  4822. nbx = normals[ nb*3 ],
  4823. nby = normals[ nb*3 + 1 ],
  4824. nbz = normals[ nb*3 + 2 ],
  4825. ncx = normals[ nc*3 ],
  4826. ncy = normals[ nc*3 + 1 ],
  4827. ncz = normals[ nc*3 + 2 ];
  4828. scope.faces.push( new THREE.Face3( a, b, c,
  4829. [new THREE.Vector3( nax, nay, naz ),
  4830. new THREE.Vector3( nbx, nby, nbz ),
  4831. new THREE.Vector3( ncx, ncy, ncz )],
  4832. null,
  4833. mi ) );
  4834. };
  4835. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4836. var nax = normals[ na*3 ],
  4837. nay = normals[ na*3 + 1 ],
  4838. naz = normals[ na*3 + 2 ],
  4839. nbx = normals[ nb*3 ],
  4840. nby = normals[ nb*3 + 1 ],
  4841. nbz = normals[ nb*3 + 2 ],
  4842. ncx = normals[ nc*3 ],
  4843. ncy = normals[ nc*3 + 1 ],
  4844. ncz = normals[ nc*3 + 2 ],
  4845. ndx = normals[ nd*3 ],
  4846. ndy = normals[ nd*3 + 1 ],
  4847. ndz = normals[ nd*3 + 2 ];
  4848. scope.faces.push( new THREE.Face4( a, b, c, d,
  4849. [new THREE.Vector3( nax, nay, naz ),
  4850. new THREE.Vector3( nbx, nby, nbz ),
  4851. new THREE.Vector3( ncx, ncy, ncz ),
  4852. new THREE.Vector3( ndx, ndy, ndz )],
  4853. null,
  4854. mi ) );
  4855. };
  4856. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4857. where.push( [
  4858. new THREE.UV( u1, v1 ),
  4859. new THREE.UV( u2, v2 ),
  4860. new THREE.UV( u3, v3 )
  4861. ] );
  4862. };
  4863. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4864. where.push( [
  4865. new THREE.UV( u1, v1 ),
  4866. new THREE.UV( u2, v2 ),
  4867. new THREE.UV( u3, v3 ),
  4868. new THREE.UV( u4, v4 )
  4869. ] );
  4870. };
  4871. Model.prototype = Object.create( THREE.Geometry.prototype );
  4872. var geometry = new Model( texturePath );
  4873. var materials = this.initMaterials( jsonMaterials, texturePath );
  4874. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  4875. callback( geometry, materials );
  4876. };
  4877. /**
  4878. * @author mrdoob / http://mrdoob.com/
  4879. */
  4880. THREE.ImageLoader = function () {
  4881. THREE.EventTarget.call( this );
  4882. this.crossOrigin = null;
  4883. };
  4884. THREE.ImageLoader.prototype = {
  4885. constructor: THREE.ImageLoader,
  4886. load: function ( url, image ) {
  4887. var scope = this;
  4888. if ( image === undefined ) image = new Image();
  4889. image.addEventListener( 'load', function () {
  4890. scope.dispatchEvent( { type: 'load', content: image } );
  4891. }, false );
  4892. image.addEventListener( 'error', function () {
  4893. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4894. }, false );
  4895. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4896. image.src = url;
  4897. }
  4898. }
  4899. /**
  4900. * @author mrdoob / http://mrdoob.com/
  4901. * @author alteredq / http://alteredqualia.com/
  4902. */
  4903. THREE.JSONLoader = function ( showStatus ) {
  4904. THREE.Loader.call( this, showStatus );
  4905. this.withCredentials = false;
  4906. };
  4907. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4908. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4909. var scope = this;
  4910. // todo: unify load API to for easier SceneLoader use
  4911. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4912. this.onLoadStart();
  4913. this.loadAjaxJSON( this, url, callback, texturePath );
  4914. };
  4915. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4916. var xhr = new XMLHttpRequest();
  4917. var length = 0;
  4918. xhr.withCredentials = this.withCredentials;
  4919. xhr.onreadystatechange = function () {
  4920. if ( xhr.readyState === xhr.DONE ) {
  4921. if ( xhr.status === 200 || xhr.status === 0 ) {
  4922. if ( xhr.responseText ) {
  4923. var json = JSON.parse( xhr.responseText );
  4924. context.createModel( json, callback, texturePath );
  4925. } else {
  4926. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4927. }
  4928. // in context of more complex asset initialization
  4929. // do not block on single failed file
  4930. // maybe should go even one more level up
  4931. context.onLoadComplete();
  4932. } else {
  4933. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4934. }
  4935. } else if ( xhr.readyState === xhr.LOADING ) {
  4936. if ( callbackProgress ) {
  4937. if ( length === 0 ) {
  4938. length = xhr.getResponseHeader( "Content-Length" );
  4939. }
  4940. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4941. }
  4942. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4943. length = xhr.getResponseHeader( "Content-Length" );
  4944. }
  4945. };
  4946. xhr.open( "GET", url, true );
  4947. xhr.send( null );
  4948. };
  4949. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4950. var scope = this,
  4951. geometry = new THREE.Geometry(),
  4952. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4953. parseModel( scale );
  4954. parseSkin();
  4955. parseMorphing( scale );
  4956. geometry.computeCentroids();
  4957. geometry.computeFaceNormals();
  4958. function parseModel( scale ) {
  4959. function isBitSet( value, position ) {
  4960. return value & ( 1 << position );
  4961. }
  4962. var i, j, fi,
  4963. offset, zLength, nVertices,
  4964. colorIndex, normalIndex, uvIndex, materialIndex,
  4965. type,
  4966. isQuad,
  4967. hasMaterial,
  4968. hasFaceUv, hasFaceVertexUv,
  4969. hasFaceNormal, hasFaceVertexNormal,
  4970. hasFaceColor, hasFaceVertexColor,
  4971. vertex, face, color, normal,
  4972. uvLayer, uvs, u, v,
  4973. faces = json.faces,
  4974. vertices = json.vertices,
  4975. normals = json.normals,
  4976. colors = json.colors,
  4977. nUvLayers = 0;
  4978. // disregard empty arrays
  4979. for ( i = 0; i < json.uvs.length; i++ ) {
  4980. if ( json.uvs[ i ].length ) nUvLayers ++;
  4981. }
  4982. for ( i = 0; i < nUvLayers; i++ ) {
  4983. geometry.faceUvs[ i ] = [];
  4984. geometry.faceVertexUvs[ i ] = [];
  4985. }
  4986. offset = 0;
  4987. zLength = vertices.length;
  4988. while ( offset < zLength ) {
  4989. vertex = new THREE.Vector3();
  4990. vertex.x = vertices[ offset ++ ] * scale;
  4991. vertex.y = vertices[ offset ++ ] * scale;
  4992. vertex.z = vertices[ offset ++ ] * scale;
  4993. geometry.vertices.push( vertex );
  4994. }
  4995. offset = 0;
  4996. zLength = faces.length;
  4997. while ( offset < zLength ) {
  4998. type = faces[ offset ++ ];
  4999. isQuad = isBitSet( type, 0 );
  5000. hasMaterial = isBitSet( type, 1 );
  5001. hasFaceUv = isBitSet( type, 2 );
  5002. hasFaceVertexUv = isBitSet( type, 3 );
  5003. hasFaceNormal = isBitSet( type, 4 );
  5004. hasFaceVertexNormal = isBitSet( type, 5 );
  5005. hasFaceColor = isBitSet( type, 6 );
  5006. hasFaceVertexColor = isBitSet( type, 7 );
  5007. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5008. if ( isQuad ) {
  5009. face = new THREE.Face4();
  5010. face.a = faces[ offset ++ ];
  5011. face.b = faces[ offset ++ ];
  5012. face.c = faces[ offset ++ ];
  5013. face.d = faces[ offset ++ ];
  5014. nVertices = 4;
  5015. } else {
  5016. face = new THREE.Face3();
  5017. face.a = faces[ offset ++ ];
  5018. face.b = faces[ offset ++ ];
  5019. face.c = faces[ offset ++ ];
  5020. nVertices = 3;
  5021. }
  5022. if ( hasMaterial ) {
  5023. materialIndex = faces[ offset ++ ];
  5024. face.materialIndex = materialIndex;
  5025. }
  5026. // to get face <=> uv index correspondence
  5027. fi = geometry.faces.length;
  5028. if ( hasFaceUv ) {
  5029. for ( i = 0; i < nUvLayers; i++ ) {
  5030. uvLayer = json.uvs[ i ];
  5031. uvIndex = faces[ offset ++ ];
  5032. u = uvLayer[ uvIndex * 2 ];
  5033. v = uvLayer[ uvIndex * 2 + 1 ];
  5034. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5035. }
  5036. }
  5037. if ( hasFaceVertexUv ) {
  5038. for ( i = 0; i < nUvLayers; i++ ) {
  5039. uvLayer = json.uvs[ i ];
  5040. uvs = [];
  5041. for ( j = 0; j < nVertices; j ++ ) {
  5042. uvIndex = faces[ offset ++ ];
  5043. u = uvLayer[ uvIndex * 2 ];
  5044. v = uvLayer[ uvIndex * 2 + 1 ];
  5045. uvs[ j ] = new THREE.UV( u, v );
  5046. }
  5047. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5048. }
  5049. }
  5050. if ( hasFaceNormal ) {
  5051. normalIndex = faces[ offset ++ ] * 3;
  5052. normal = new THREE.Vector3();
  5053. normal.x = normals[ normalIndex ++ ];
  5054. normal.y = normals[ normalIndex ++ ];
  5055. normal.z = normals[ normalIndex ];
  5056. face.normal = normal;
  5057. }
  5058. if ( hasFaceVertexNormal ) {
  5059. for ( i = 0; i < nVertices; i++ ) {
  5060. normalIndex = faces[ offset ++ ] * 3;
  5061. normal = new THREE.Vector3();
  5062. normal.x = normals[ normalIndex ++ ];
  5063. normal.y = normals[ normalIndex ++ ];
  5064. normal.z = normals[ normalIndex ];
  5065. face.vertexNormals.push( normal );
  5066. }
  5067. }
  5068. if ( hasFaceColor ) {
  5069. colorIndex = faces[ offset ++ ];
  5070. color = new THREE.Color( colors[ colorIndex ] );
  5071. face.color = color;
  5072. }
  5073. if ( hasFaceVertexColor ) {
  5074. for ( i = 0; i < nVertices; i++ ) {
  5075. colorIndex = faces[ offset ++ ];
  5076. color = new THREE.Color( colors[ colorIndex ] );
  5077. face.vertexColors.push( color );
  5078. }
  5079. }
  5080. geometry.faces.push( face );
  5081. }
  5082. };
  5083. function parseSkin() {
  5084. var i, l, x, y, z, w, a, b, c, d;
  5085. if ( json.skinWeights ) {
  5086. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5087. x = json.skinWeights[ i ];
  5088. y = json.skinWeights[ i + 1 ];
  5089. z = 0;
  5090. w = 0;
  5091. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5092. }
  5093. }
  5094. if ( json.skinIndices ) {
  5095. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5096. a = json.skinIndices[ i ];
  5097. b = json.skinIndices[ i + 1 ];
  5098. c = 0;
  5099. d = 0;
  5100. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5101. }
  5102. }
  5103. geometry.bones = json.bones;
  5104. geometry.animation = json.animation;
  5105. };
  5106. function parseMorphing( scale ) {
  5107. if ( json.morphTargets !== undefined ) {
  5108. var i, l, v, vl, dstVertices, srcVertices;
  5109. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5110. geometry.morphTargets[ i ] = {};
  5111. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5112. geometry.morphTargets[ i ].vertices = [];
  5113. dstVertices = geometry.morphTargets[ i ].vertices;
  5114. srcVertices = json.morphTargets [ i ].vertices;
  5115. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5116. var vertex = new THREE.Vector3();
  5117. vertex.x = srcVertices[ v ] * scale;
  5118. vertex.y = srcVertices[ v + 1 ] * scale;
  5119. vertex.z = srcVertices[ v + 2 ] * scale;
  5120. dstVertices.push( vertex );
  5121. }
  5122. }
  5123. }
  5124. if ( json.morphColors !== undefined ) {
  5125. var i, l, c, cl, dstColors, srcColors, color;
  5126. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5127. geometry.morphColors[ i ] = {};
  5128. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5129. geometry.morphColors[ i ].colors = [];
  5130. dstColors = geometry.morphColors[ i ].colors;
  5131. srcColors = json.morphColors [ i ].colors;
  5132. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5133. color = new THREE.Color( 0xffaa00 );
  5134. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5135. dstColors.push( color );
  5136. }
  5137. }
  5138. }
  5139. };
  5140. var materials = this.initMaterials( json.materials, texturePath );
  5141. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5142. callback( geometry, materials );
  5143. };
  5144. /**
  5145. * @author mrdoob / http://mrdoob.com/
  5146. */
  5147. THREE.LoadingMonitor = function () {
  5148. THREE.EventTarget.call( this );
  5149. var scope = this;
  5150. var loaded = 0;
  5151. var total = 0;
  5152. var onLoad = function ( event ) {
  5153. loaded ++;
  5154. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5155. if ( loaded === total ) {
  5156. scope.dispatchEvent( { type: 'load' } );
  5157. }
  5158. };
  5159. this.add = function ( loader ) {
  5160. total ++;
  5161. loader.addEventListener( 'load', onLoad, false );
  5162. };
  5163. };
  5164. /**
  5165. * @author alteredq / http://alteredqualia.com/
  5166. */
  5167. THREE.SceneLoader = function () {
  5168. this.onLoadStart = function () {};
  5169. this.onLoadProgress = function() {};
  5170. this.onLoadComplete = function () {};
  5171. this.callbackSync = function () {};
  5172. this.callbackProgress = function () {};
  5173. this.geometryHandlerMap = {};
  5174. this.hierarchyHandlerMap = {};
  5175. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5176. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5177. };
  5178. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5179. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5180. var scope = this;
  5181. var xhr = new XMLHttpRequest();
  5182. xhr.onreadystatechange = function () {
  5183. if ( xhr.readyState === 4 ) {
  5184. if ( xhr.status === 200 || xhr.status === 0 ) {
  5185. var json = JSON.parse( xhr.responseText );
  5186. scope.parse( json, callbackFinished, url );
  5187. } else {
  5188. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5189. }
  5190. }
  5191. };
  5192. xhr.open( "GET", url, true );
  5193. xhr.send( null );
  5194. };
  5195. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5196. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5197. };
  5198. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5199. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5200. };
  5201. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5202. var scope = this;
  5203. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5204. var dg, dm, dc, df, dt,
  5205. g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5206. geometry, material, camera, fog,
  5207. texture, images,
  5208. light, hex, intensity,
  5209. counter_models, counter_textures,
  5210. total_models, total_textures,
  5211. result;
  5212. var target_array = [];
  5213. var data = json;
  5214. // async geometry loaders
  5215. for ( var typeID in this.geometryHandlerMap ) {
  5216. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5217. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5218. }
  5219. // async hierachy loaders
  5220. for ( var typeID in this.hierarchyHandlerMap ) {
  5221. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5222. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5223. }
  5224. counter_models = 0;
  5225. counter_textures = 0;
  5226. result = {
  5227. scene: new THREE.Scene(),
  5228. geometries: {},
  5229. face_materials: {},
  5230. materials: {},
  5231. textures: {},
  5232. objects: {},
  5233. cameras: {},
  5234. lights: {},
  5235. fogs: {},
  5236. empties: {}
  5237. };
  5238. if ( data.transform ) {
  5239. var position = data.transform.position,
  5240. rotation = data.transform.rotation,
  5241. scale = data.transform.scale;
  5242. if ( position )
  5243. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5244. if ( rotation )
  5245. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5246. if ( scale )
  5247. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5248. if ( position || rotation || scale ) {
  5249. result.scene.updateMatrix();
  5250. result.scene.updateMatrixWorld();
  5251. }
  5252. }
  5253. function get_url( source_url, url_type ) {
  5254. if ( url_type == "relativeToHTML" ) {
  5255. return source_url;
  5256. } else {
  5257. return urlBase + "/" + source_url;
  5258. }
  5259. };
  5260. // toplevel loader function, delegates to handle_children
  5261. function handle_objects() {
  5262. handle_children( result.scene, data.objects );
  5263. }
  5264. // handle all the children from the loaded json and attach them to given parent
  5265. function handle_children( parent, children ) {
  5266. for ( var dd in children ) {
  5267. // check by id if child has already been handled,
  5268. // if not, create new object
  5269. if ( result.objects[ dd ] === undefined ) {
  5270. var o = children[ dd ];
  5271. var object = null;
  5272. // meshes
  5273. if ( o.type && ( o.type in scope.hierarchyHandlerMap ) && o.loading === undefined ) {
  5274. var loaderParameters = {};
  5275. for ( var parType in g ) {
  5276. if ( parType !== "type" && parType !== "url" ) {
  5277. loaderParameters[ parType ] = g[ parType ];
  5278. }
  5279. }
  5280. material = result.materials[ o.material ];
  5281. o.loading = true;
  5282. var loader = scope.hierarchyHandlerMap[ o.type ][ "loaderObject" ];
  5283. // OBJLoader
  5284. if ( loader.addEventListener ) {
  5285. loader.addEventListener( 'load', create_callback_hierachy( dd, parent, material, o ) );
  5286. loader.load( get_url( o.url, data.urlBaseType ) );
  5287. } else {
  5288. // ColladaLoader
  5289. if ( loader.options ) {
  5290. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ) );
  5291. // UTF8Loader
  5292. } else {
  5293. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ), loaderParameters );
  5294. }
  5295. }
  5296. } else if ( o.geometry !== undefined ) {
  5297. geometry = result.geometries[ o.geometry ];
  5298. // geometry already loaded
  5299. if ( geometry ) {
  5300. var needsTangents = false;
  5301. material = result.materials[ o.material ];
  5302. needsTangents = material instanceof THREE.ShaderMaterial;
  5303. p = o.position;
  5304. r = o.rotation;
  5305. q = o.quaternion;
  5306. s = o.scale;
  5307. m = o.matrix;
  5308. // turn off quaternions, for the moment
  5309. q = 0;
  5310. // use materials from the model file
  5311. // if there is no material specified in the object
  5312. if ( ! o.material ) {
  5313. material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
  5314. }
  5315. // use materials from the model file
  5316. // if there is just empty face material
  5317. // (must create new material as each model has its own face material)
  5318. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  5319. material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
  5320. }
  5321. if ( material instanceof THREE.MeshFaceMaterial ) {
  5322. for ( var i = 0; i < material.materials.length; i ++ ) {
  5323. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  5324. }
  5325. }
  5326. if ( needsTangents ) {
  5327. geometry.computeTangents();
  5328. }
  5329. if ( o.skin ) {
  5330. object = new THREE.SkinnedMesh( geometry, material );
  5331. } else if ( o.morph ) {
  5332. object = new THREE.MorphAnimMesh( geometry, material );
  5333. if ( o.duration !== undefined ) {
  5334. object.duration = o.duration;
  5335. }
  5336. if ( o.time !== undefined ) {
  5337. object.time = o.time;
  5338. }
  5339. if ( o.mirroredLoop !== undefined ) {
  5340. object.mirroredLoop = o.mirroredLoop;
  5341. }
  5342. if ( material.morphNormals ) {
  5343. geometry.computeMorphNormals();
  5344. }
  5345. } else {
  5346. object = new THREE.Mesh( geometry, material );
  5347. }
  5348. object.name = dd;
  5349. if ( m ) {
  5350. object.matrixAutoUpdate = false;
  5351. object.matrix.set(
  5352. m[0], m[1], m[2], m[3],
  5353. m[4], m[5], m[6], m[7],
  5354. m[8], m[9], m[10], m[11],
  5355. m[12], m[13], m[14], m[15]
  5356. );
  5357. } else {
  5358. object.position.set( p[0], p[1], p[2] );
  5359. if ( q ) {
  5360. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5361. object.useQuaternion = true;
  5362. } else {
  5363. object.rotation.set( r[0], r[1], r[2] );
  5364. }
  5365. object.scale.set( s[0], s[1], s[2] );
  5366. }
  5367. object.visible = o.visible;
  5368. object.castShadow = o.castShadow;
  5369. object.receiveShadow = o.receiveShadow;
  5370. parent.add( object );
  5371. result.objects[ dd ] = object;
  5372. }
  5373. // lights
  5374. } else if ( o.type === "DirectionalLight" || o.type === "PointLight" || o.type === "AmbientLight" ) {
  5375. hex = ( o.color !== undefined ) ? o.color : 0xffffff;
  5376. intensity = ( o.intensity !== undefined ) ? o.intensity : 1;
  5377. if ( o.type === "DirectionalLight" ) {
  5378. p = o.direction;
  5379. light = new THREE.DirectionalLight( hex, intensity );
  5380. light.position.set( p[0], p[1], p[2] );
  5381. if ( o.target ) {
  5382. target_array.push( { "object": light, "targetName" : o.target } );
  5383. // kill existing default target
  5384. // otherwise it gets added to scene when parent gets added
  5385. light.target = null;
  5386. }
  5387. } else if ( o.type === "PointLight" ) {
  5388. p = o.position;
  5389. d = o.distance;
  5390. light = new THREE.PointLight( hex, intensity, d );
  5391. light.position.set( p[0], p[1], p[2] );
  5392. } else if ( o.type === "AmbientLight" ) {
  5393. light = new THREE.AmbientLight( hex );
  5394. }
  5395. parent.add( light );
  5396. light.name = dd;
  5397. result.lights[ dd ] = light;
  5398. result.objects[ dd ] = light;
  5399. // cameras
  5400. } else if ( o.type === "PerspectiveCamera" || o.type === "OrthographicCamera" ) {
  5401. if ( o.type === "PerspectiveCamera" ) {
  5402. camera = new THREE.PerspectiveCamera( o.fov, o.aspect, o.near, o.far );
  5403. } else if ( o.type === "OrthographicCamera" ) {
  5404. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5405. }
  5406. p = o.position;
  5407. camera.position.set( p[0], p[1], p[2] );
  5408. parent.add( camera );
  5409. camera.name = dd;
  5410. result.cameras[ dd ] = camera;
  5411. result.objects[ dd ] = camera;
  5412. // pure Object3D
  5413. } else {
  5414. p = o.position;
  5415. r = o.rotation;
  5416. q = o.quaternion;
  5417. s = o.scale;
  5418. // turn off quaternions, for the moment
  5419. q = 0;
  5420. object = new THREE.Object3D();
  5421. object.name = dd;
  5422. object.position.set( p[0], p[1], p[2] );
  5423. if ( q ) {
  5424. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5425. object.useQuaternion = true;
  5426. } else {
  5427. object.rotation.set( r[0], r[1], r[2] );
  5428. }
  5429. object.scale.set( s[0], s[1], s[2] );
  5430. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5431. parent.add( object );
  5432. result.objects[ dd ] = object;
  5433. result.empties[ dd ] = object;
  5434. }
  5435. if ( object ) {
  5436. if ( o.properties !== undefined ) {
  5437. for ( var key in o.properties ) {
  5438. var value = o.properties[ key ];
  5439. object.properties[ key ] = value;
  5440. }
  5441. }
  5442. if ( o.children !== undefined ) {
  5443. handle_children( object, o.children );
  5444. }
  5445. }
  5446. }
  5447. }
  5448. };
  5449. function handle_mesh( geo, mat, id ) {
  5450. result.geometries[ id ] = geo;
  5451. result.face_materials[ id ] = mat;
  5452. handle_objects();
  5453. };
  5454. function handle_hierarchy( node, id, parent, material, o ) {
  5455. var p = o.position;
  5456. var r = o.rotation;
  5457. var q = o.quaternion;
  5458. var s = o.scale;
  5459. node.position.set( p[0], p[1], p[2] );
  5460. if ( q ) {
  5461. node.quaternion.set( q[0], q[1], q[2], q[3] );
  5462. node.useQuaternion = true;
  5463. } else {
  5464. node.rotation.set( r[0], r[1], r[2] );
  5465. }
  5466. node.scale.set( s[0], s[1], s[2] );
  5467. if ( material ) {
  5468. node.traverse( function ( child ) {
  5469. child.material = material;
  5470. } );
  5471. }
  5472. parent.add( node );
  5473. result.objects[ id ] = node;
  5474. handle_objects();
  5475. };
  5476. function create_callback_geometry( id ) {
  5477. return function( geo, mat ) {
  5478. handle_mesh( geo, mat, id );
  5479. counter_models -= 1;
  5480. scope.onLoadComplete();
  5481. async_callback_gate();
  5482. }
  5483. };
  5484. function create_callback_hierachy( id, parent, material, obj ) {
  5485. return function( event ) {
  5486. var result;
  5487. // loaders which use EventTarget
  5488. if ( event.content ) {
  5489. result = event.content;
  5490. // ColladaLoader
  5491. } else if ( event.dae ) {
  5492. result = event.scene;
  5493. // UTF8Loader
  5494. } else {
  5495. result = event;
  5496. }
  5497. handle_hierarchy( result, id, parent, material, obj );
  5498. counter_models -= 1;
  5499. scope.onLoadComplete();
  5500. async_callback_gate();
  5501. }
  5502. };
  5503. function create_callback_embed( id ) {
  5504. return function( geo, mat ) {
  5505. result.geometries[ id ] = geo;
  5506. result.face_materials[ id ] = mat;
  5507. }
  5508. };
  5509. function async_callback_gate() {
  5510. var progress = {
  5511. totalModels : total_models,
  5512. totalTextures : total_textures,
  5513. loadedModels : total_models - counter_models,
  5514. loadedTextures : total_textures - counter_textures
  5515. };
  5516. scope.callbackProgress( progress, result );
  5517. scope.onLoadProgress();
  5518. if ( counter_models === 0 && counter_textures === 0 ) {
  5519. finalize();
  5520. callbackFinished( result );
  5521. }
  5522. };
  5523. function finalize() {
  5524. // take care of targets which could be asynchronously loaded objects
  5525. for ( var i = 0; i < target_array.length; i ++ ) {
  5526. var ta = target_array[ i ];
  5527. var target = result.objects[ ta.targetName ];
  5528. if ( target ) {
  5529. ta.object.target = target;
  5530. } else {
  5531. // if there was error and target of specified name doesn't exist in the scene file
  5532. // create instead dummy target
  5533. // (target must be added to scene explicitly as parent is already added)
  5534. ta.object.target = new THREE.Object3D();
  5535. result.scene.add( ta.object.target );
  5536. }
  5537. ta.object.target.properties.targetInverse = ta.object;
  5538. }
  5539. };
  5540. var callbackTexture = function ( count ) {
  5541. counter_textures -= count;
  5542. async_callback_gate();
  5543. scope.onLoadComplete();
  5544. };
  5545. // must use this instead of just directly calling callbackTexture
  5546. // because of closure in the calling context loop
  5547. var generateTextureCallback = function ( count ) {
  5548. return function() {
  5549. callbackTexture( count );
  5550. };
  5551. };
  5552. // first go synchronous elements
  5553. // fogs
  5554. for ( df in data.fogs ) {
  5555. f = data.fogs[ df ];
  5556. if ( f.type === "linear" ) {
  5557. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5558. } else if ( f.type === "exp2" ) {
  5559. fog = new THREE.FogExp2( 0x000000, f.density );
  5560. }
  5561. c = f.color;
  5562. fog.color.setRGB( c[0], c[1], c[2] );
  5563. result.fogs[ df ] = fog;
  5564. }
  5565. // now come potentially asynchronous elements
  5566. // geometries
  5567. // count how many geometries will be loaded asynchronously
  5568. for ( dg in data.geometries ) {
  5569. g = data.geometries[ dg ];
  5570. if ( g.type in this.geometryHandlerMap ) {
  5571. counter_models += 1;
  5572. scope.onLoadStart();
  5573. }
  5574. }
  5575. // count how many hierarchies will be loaded asynchronously
  5576. for ( var dd in data.objects ) {
  5577. var o = data.objects[ dd ];
  5578. if ( o.type && ( o.type in this.hierarchyHandlerMap ) ) {
  5579. counter_models += 1;
  5580. scope.onLoadStart();
  5581. }
  5582. }
  5583. total_models = counter_models;
  5584. for ( dg in data.geometries ) {
  5585. g = data.geometries[ dg ];
  5586. if ( g.type === "cube" ) {
  5587. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.widthSegments, g.heightSegments, g.depthSegments );
  5588. result.geometries[ dg ] = geometry;
  5589. } else if ( g.type === "plane" ) {
  5590. geometry = new THREE.PlaneGeometry( g.width, g.height, g.widthSegments, g.heightSegments );
  5591. result.geometries[ dg ] = geometry;
  5592. } else if ( g.type === "sphere" ) {
  5593. geometry = new THREE.SphereGeometry( g.radius, g.widthSegments, g.heightSegments );
  5594. result.geometries[ dg ] = geometry;
  5595. } else if ( g.type === "cylinder" ) {
  5596. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5597. result.geometries[ dg ] = geometry;
  5598. } else if ( g.type === "torus" ) {
  5599. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5600. result.geometries[ dg ] = geometry;
  5601. } else if ( g.type === "icosahedron" ) {
  5602. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5603. result.geometries[ dg ] = geometry;
  5604. } else if ( g.type in this.geometryHandlerMap ) {
  5605. var loaderParameters = {};
  5606. for ( var parType in g ) {
  5607. if ( parType !== "type" && parType !== "url" ) {
  5608. loaderParameters[ parType ] = g[ parType ];
  5609. }
  5610. }
  5611. var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
  5612. loader.load( get_url( g.url, data.urlBaseType ), create_callback_geometry( dg ), loaderParameters );
  5613. } else if ( g.type === "embedded" ) {
  5614. var modelJson = data.embeds[ g.id ],
  5615. texture_path = "";
  5616. // pass metadata along to jsonLoader so it knows the format version
  5617. modelJson.metadata = data.metadata;
  5618. if ( modelJson ) {
  5619. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  5620. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5621. }
  5622. }
  5623. }
  5624. // textures
  5625. // count how many textures will be loaded asynchronously
  5626. for ( dt in data.textures ) {
  5627. tt = data.textures[ dt ];
  5628. if ( tt.url instanceof Array ) {
  5629. counter_textures += tt.url.length;
  5630. for( var n = 0; n < tt.url.length; n ++ ) {
  5631. scope.onLoadStart();
  5632. }
  5633. } else {
  5634. counter_textures += 1;
  5635. scope.onLoadStart();
  5636. }
  5637. }
  5638. total_textures = counter_textures;
  5639. for ( dt in data.textures ) {
  5640. tt = data.textures[ dt ];
  5641. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5642. tt.mapping = new THREE[ tt.mapping ]();
  5643. }
  5644. if ( tt.url instanceof Array ) {
  5645. var count = tt.url.length;
  5646. var url_array = [];
  5647. for( var i = 0; i < count; i ++ ) {
  5648. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5649. }
  5650. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  5651. if ( isCompressed ) {
  5652. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5653. } else {
  5654. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5655. }
  5656. } else {
  5657. var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
  5658. var fullUrl = get_url( tt.url, data.urlBaseType );
  5659. var textureCallback = generateTextureCallback( 1 );
  5660. if ( isCompressed ) {
  5661. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );
  5662. } else {
  5663. texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );
  5664. }
  5665. if ( THREE[ tt.minFilter ] !== undefined )
  5666. texture.minFilter = THREE[ tt.minFilter ];
  5667. if ( THREE[ tt.magFilter ] !== undefined )
  5668. texture.magFilter = THREE[ tt.magFilter ];
  5669. if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;
  5670. if ( tt.repeat ) {
  5671. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5672. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5673. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5674. }
  5675. if ( tt.offset ) {
  5676. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5677. }
  5678. // handle wrap after repeat so that default repeat can be overriden
  5679. if ( tt.wrap ) {
  5680. var wrapMap = {
  5681. "repeat" : THREE.RepeatWrapping,
  5682. "mirror" : THREE.MirroredRepeatWrapping
  5683. }
  5684. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5685. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5686. }
  5687. }
  5688. result.textures[ dt ] = texture;
  5689. }
  5690. // materials
  5691. for ( dm in data.materials ) {
  5692. m = data.materials[ dm ];
  5693. for ( pp in m.parameters ) {
  5694. if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {
  5695. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5696. } else if ( pp === "shading" ) {
  5697. m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5698. } else if ( pp === "side" ) {
  5699. if ( m.parameters[ pp ] == "double" ) {
  5700. m.parameters[ pp ] = THREE.DoubleSide;
  5701. } else if ( m.parameters[ pp ] == "back" ) {
  5702. m.parameters[ pp ] = THREE.BackSide;
  5703. } else {
  5704. m.parameters[ pp ] = THREE.FrontSide;
  5705. }
  5706. } else if ( pp === "blending" ) {
  5707. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5708. } else if ( pp === "combine" ) {
  5709. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5710. } else if ( pp === "vertexColors" ) {
  5711. if ( m.parameters[ pp ] == "face" ) {
  5712. m.parameters[ pp ] = THREE.FaceColors;
  5713. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5714. } else if ( m.parameters[ pp ] ) {
  5715. m.parameters[ pp ] = THREE.VertexColors;
  5716. }
  5717. } else if ( pp === "wrapRGB" ) {
  5718. var v3 = m.parameters[ pp ];
  5719. m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  5720. }
  5721. }
  5722. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5723. m.parameters.transparent = true;
  5724. }
  5725. if ( m.parameters.normalMap ) {
  5726. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5727. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5728. var diffuse = m.parameters.color;
  5729. var specular = m.parameters.specular;
  5730. var ambient = m.parameters.ambient;
  5731. var shininess = m.parameters.shininess;
  5732. uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
  5733. if ( m.parameters.normalScale ) {
  5734. uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );
  5735. }
  5736. if ( m.parameters.map ) {
  5737. uniforms[ "tDiffuse" ].value = m.parameters.map;
  5738. uniforms[ "enableDiffuse" ].value = true;
  5739. }
  5740. if ( m.parameters.envMap ) {
  5741. uniforms[ "tCube" ].value = m.parameters.envMap;
  5742. uniforms[ "enableReflection" ].value = true;
  5743. uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;
  5744. }
  5745. if ( m.parameters.lightMap ) {
  5746. uniforms[ "tAO" ].value = m.parameters.lightMap;
  5747. uniforms[ "enableAO" ].value = true;
  5748. }
  5749. if ( m.parameters.specularMap ) {
  5750. uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
  5751. uniforms[ "enableSpecular" ].value = true;
  5752. }
  5753. if ( m.parameters.displacementMap ) {
  5754. uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
  5755. uniforms[ "enableDisplacement" ].value = true;
  5756. uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
  5757. uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;
  5758. }
  5759. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5760. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5761. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5762. uniforms[ "uShininess" ].value = shininess;
  5763. if ( m.parameters.opacity ) {
  5764. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5765. }
  5766. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5767. material = new THREE.ShaderMaterial( parameters );
  5768. } else {
  5769. material = new THREE[ m.type ]( m.parameters );
  5770. }
  5771. result.materials[ dm ] = material;
  5772. }
  5773. // second pass through all materials to initialize MeshFaceMaterials
  5774. // that could be referring to other materials out of order
  5775. for ( dm in data.materials ) {
  5776. m = data.materials[ dm ];
  5777. if ( m.parameters.materials ) {
  5778. var materialArray = [];
  5779. for ( var i = 0; i < m.parameters.materials.length; i ++ ) {
  5780. var label = m.parameters.materials[ i ];
  5781. materialArray.push( result.materials[ label ] );
  5782. }
  5783. result.materials[ dm ].materials = materialArray;
  5784. }
  5785. }
  5786. // objects ( synchronous init of procedural primitives )
  5787. handle_objects();
  5788. // defaults
  5789. if ( result.cameras && data.defaults.camera ) {
  5790. result.currentCamera = result.cameras[ data.defaults.camera ];
  5791. }
  5792. if ( result.fogs && data.defaults.fog ) {
  5793. result.scene.fog = result.fogs[ data.defaults.fog ];
  5794. }
  5795. c = data.defaults.bgcolor;
  5796. result.bgColor = new THREE.Color();
  5797. result.bgColor.setRGB( c[0], c[1], c[2] );
  5798. result.bgColorAlpha = data.defaults.bgalpha;
  5799. // synchronous callback
  5800. scope.callbackSync( result );
  5801. // just in case there are no async elements
  5802. async_callback_gate();
  5803. };
  5804. /**
  5805. * @author mrdoob / http://mrdoob.com/
  5806. */
  5807. THREE.TextureLoader = function () {
  5808. THREE.EventTarget.call( this );
  5809. this.crossOrigin = null;
  5810. };
  5811. THREE.TextureLoader.prototype = {
  5812. constructor: THREE.TextureLoader,
  5813. load: function ( url ) {
  5814. var scope = this;
  5815. var image = new Image();
  5816. image.addEventListener( 'load', function () {
  5817. var texture = new THREE.Texture( image );
  5818. texture.needsUpdate = true;
  5819. scope.dispatchEvent( { type: 'load', content: texture } );
  5820. }, false );
  5821. image.addEventListener( 'error', function () {
  5822. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5823. }, false );
  5824. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5825. image.src = url;
  5826. }
  5827. }
  5828. /**
  5829. * @author mrdoob / http://mrdoob.com/
  5830. * @author alteredq / http://alteredqualia.com/
  5831. */
  5832. THREE.Material = function () {
  5833. THREE.MaterialLibrary.push( this );
  5834. this.id = THREE.MaterialIdCount ++;
  5835. this.name = '';
  5836. this.side = THREE.FrontSide;
  5837. this.opacity = 1;
  5838. this.transparent = false;
  5839. this.blending = THREE.NormalBlending;
  5840. this.blendSrc = THREE.SrcAlphaFactor;
  5841. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5842. this.blendEquation = THREE.AddEquation;
  5843. this.depthTest = true;
  5844. this.depthWrite = true;
  5845. this.polygonOffset = false;
  5846. this.polygonOffsetFactor = 0;
  5847. this.polygonOffsetUnits = 0;
  5848. this.alphaTest = 0;
  5849. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5850. this.visible = true;
  5851. this.needsUpdate = true;
  5852. };
  5853. THREE.Material.prototype.setValues = function ( values ) {
  5854. if ( values === undefined ) return;
  5855. for ( var key in values ) {
  5856. var newValue = values[ key ];
  5857. if ( newValue === undefined ) {
  5858. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5859. continue;
  5860. }
  5861. if ( key in this ) {
  5862. var currentValue = this[ key ];
  5863. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5864. currentValue.copy( newValue );
  5865. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  5866. currentValue.setHex( newValue );
  5867. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5868. currentValue.copy( newValue );
  5869. } else {
  5870. this[ key ] = newValue;
  5871. }
  5872. }
  5873. }
  5874. };
  5875. THREE.Material.prototype.clone = function ( material ) {
  5876. if ( material === undefined ) material = new THREE.Material();
  5877. material.name = this.name;
  5878. material.side = this.side;
  5879. material.opacity = this.opacity;
  5880. material.transparent = this.transparent;
  5881. material.blending = this.blending;
  5882. material.blendSrc = this.blendSrc;
  5883. material.blendDst = this.blendDst;
  5884. material.blendEquation = this.blendEquation;
  5885. material.depthTest = this.depthTest;
  5886. material.depthWrite = this.depthWrite;
  5887. material.polygonOffset = this.polygonOffset;
  5888. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5889. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5890. material.alphaTest = this.alphaTest;
  5891. material.overdraw = this.overdraw;
  5892. material.visible = this.visible;
  5893. return material;
  5894. };
  5895. THREE.Material.prototype.deallocate = function () {
  5896. var index = THREE.MaterialLibrary.indexOf( this );
  5897. if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
  5898. };
  5899. THREE.MaterialIdCount = 0;
  5900. THREE.MaterialLibrary = [];
  5901. /**
  5902. * @author mrdoob / http://mrdoob.com/
  5903. * @author alteredq / http://alteredqualia.com/
  5904. *
  5905. * parameters = {
  5906. * color: <hex>,
  5907. * opacity: <float>,
  5908. *
  5909. * blending: THREE.NormalBlending,
  5910. * depthTest: <bool>,
  5911. *
  5912. * linewidth: <float>,
  5913. * linecap: "round",
  5914. * linejoin: "round",
  5915. *
  5916. * vertexColors: <bool>
  5917. *
  5918. * fog: <bool>
  5919. * }
  5920. */
  5921. THREE.LineBasicMaterial = function ( parameters ) {
  5922. THREE.Material.call( this );
  5923. this.color = new THREE.Color( 0xffffff );
  5924. this.linewidth = 1;
  5925. this.linecap = 'round';
  5926. this.linejoin = 'round';
  5927. this.vertexColors = false;
  5928. this.fog = true;
  5929. this.setValues( parameters );
  5930. };
  5931. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5932. THREE.LineBasicMaterial.prototype.clone = function () {
  5933. var material = new THREE.LineBasicMaterial();
  5934. THREE.Material.prototype.clone.call( this, material );
  5935. material.color.copy( this.color );
  5936. material.linewidth = this.linewidth;
  5937. material.linecap = this.linecap;
  5938. material.linejoin = this.linejoin;
  5939. material.vertexColors = this.vertexColors;
  5940. material.fog = this.fog;
  5941. return material;
  5942. };
  5943. /**
  5944. * @author alteredq / http://alteredqualia.com/
  5945. *
  5946. * parameters = {
  5947. * color: <hex>,
  5948. * opacity: <float>,
  5949. *
  5950. * blending: THREE.NormalBlending,
  5951. * depthTest: <bool>,
  5952. *
  5953. * linewidth: <float>,
  5954. *
  5955. * scale: <float>,
  5956. * dashSize: <float>,
  5957. * gapSize: <float>,
  5958. *
  5959. * vertexColors: <bool>
  5960. *
  5961. * fog: <bool>
  5962. * }
  5963. */
  5964. THREE.LineDashedMaterial = function ( parameters ) {
  5965. THREE.Material.call( this );
  5966. this.color = new THREE.Color( 0xffffff );
  5967. this.linewidth = 1;
  5968. this.scale = 1;
  5969. this.dashSize = 3;
  5970. this.gapSize = 1;
  5971. this.vertexColors = false;
  5972. this.fog = true;
  5973. this.setValues( parameters );
  5974. };
  5975. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  5976. THREE.LineDashedMaterial.prototype.clone = function () {
  5977. var material = new THREE.LineDashedMaterial();
  5978. THREE.Material.prototype.clone.call( this, material );
  5979. material.color.copy( this.color );
  5980. material.linewidth = this.linewidth;
  5981. material.scale = this.scale;
  5982. material.dashSize = this.dashSize;
  5983. material.gapSize = this.gapSize;
  5984. material.vertexColors = this.vertexColors;
  5985. material.fog = this.fog;
  5986. return material;
  5987. };
  5988. /**
  5989. * @author mrdoob / http://mrdoob.com/
  5990. * @author alteredq / http://alteredqualia.com/
  5991. *
  5992. * parameters = {
  5993. * color: <hex>,
  5994. * opacity: <float>,
  5995. * map: new THREE.Texture( <Image> ),
  5996. *
  5997. * lightMap: new THREE.Texture( <Image> ),
  5998. *
  5999. * specularMap: new THREE.Texture( <Image> ),
  6000. *
  6001. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6002. * combine: THREE.Multiply,
  6003. * reflectivity: <float>,
  6004. * refractionRatio: <float>,
  6005. *
  6006. * shading: THREE.SmoothShading,
  6007. * blending: THREE.NormalBlending,
  6008. * depthTest: <bool>,
  6009. *
  6010. * wireframe: <boolean>,
  6011. * wireframeLinewidth: <float>,
  6012. *
  6013. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6014. *
  6015. * skinning: <bool>,
  6016. * morphTargets: <bool>,
  6017. *
  6018. * fog: <bool>
  6019. * }
  6020. */
  6021. THREE.MeshBasicMaterial = function ( parameters ) {
  6022. THREE.Material.call( this );
  6023. this.color = new THREE.Color( 0xffffff ); // emissive
  6024. this.map = null;
  6025. this.lightMap = null;
  6026. this.specularMap = null;
  6027. this.envMap = null;
  6028. this.combine = THREE.MultiplyOperation;
  6029. this.reflectivity = 1;
  6030. this.refractionRatio = 0.98;
  6031. this.fog = true;
  6032. this.shading = THREE.SmoothShading;
  6033. this.wireframe = false;
  6034. this.wireframeLinewidth = 1;
  6035. this.wireframeLinecap = 'round';
  6036. this.wireframeLinejoin = 'round';
  6037. this.vertexColors = THREE.NoColors;
  6038. this.skinning = false;
  6039. this.morphTargets = false;
  6040. this.setValues( parameters );
  6041. };
  6042. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6043. THREE.MeshBasicMaterial.prototype.clone = function () {
  6044. var material = new THREE.MeshBasicMaterial();
  6045. THREE.Material.prototype.clone.call( this, material );
  6046. material.color.copy( this.color );
  6047. material.map = this.map;
  6048. material.lightMap = this.lightMap;
  6049. material.specularMap = this.specularMap;
  6050. material.envMap = this.envMap;
  6051. material.combine = this.combine;
  6052. material.reflectivity = this.reflectivity;
  6053. material.refractionRatio = this.refractionRatio;
  6054. material.fog = this.fog;
  6055. material.shading = this.shading;
  6056. material.wireframe = this.wireframe;
  6057. material.wireframeLinewidth = this.wireframeLinewidth;
  6058. material.wireframeLinecap = this.wireframeLinecap;
  6059. material.wireframeLinejoin = this.wireframeLinejoin;
  6060. material.vertexColors = this.vertexColors;
  6061. material.skinning = this.skinning;
  6062. material.morphTargets = this.morphTargets;
  6063. return material;
  6064. };
  6065. /**
  6066. * @author mrdoob / http://mrdoob.com/
  6067. * @author alteredq / http://alteredqualia.com/
  6068. *
  6069. * parameters = {
  6070. * color: <hex>,
  6071. * ambient: <hex>,
  6072. * emissive: <hex>,
  6073. * opacity: <float>,
  6074. *
  6075. * map: new THREE.Texture( <Image> ),
  6076. *
  6077. * lightMap: new THREE.Texture( <Image> ),
  6078. *
  6079. * specularMap: new THREE.Texture( <Image> ),
  6080. *
  6081. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6082. * combine: THREE.Multiply,
  6083. * reflectivity: <float>,
  6084. * refractionRatio: <float>,
  6085. *
  6086. * shading: THREE.SmoothShading,
  6087. * blending: THREE.NormalBlending,
  6088. * depthTest: <bool>,
  6089. *
  6090. * wireframe: <boolean>,
  6091. * wireframeLinewidth: <float>,
  6092. *
  6093. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6094. *
  6095. * skinning: <bool>,
  6096. * morphTargets: <bool>,
  6097. * morphNormals: <bool>,
  6098. *
  6099. * fog: <bool>
  6100. * }
  6101. */
  6102. THREE.MeshLambertMaterial = function ( parameters ) {
  6103. THREE.Material.call( this );
  6104. this.color = new THREE.Color( 0xffffff ); // diffuse
  6105. this.ambient = new THREE.Color( 0xffffff );
  6106. this.emissive = new THREE.Color( 0x000000 );
  6107. this.wrapAround = false;
  6108. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6109. this.map = null;
  6110. this.lightMap = null;
  6111. this.specularMap = null;
  6112. this.envMap = null;
  6113. this.combine = THREE.MultiplyOperation;
  6114. this.reflectivity = 1;
  6115. this.refractionRatio = 0.98;
  6116. this.fog = true;
  6117. this.shading = THREE.SmoothShading;
  6118. this.wireframe = false;
  6119. this.wireframeLinewidth = 1;
  6120. this.wireframeLinecap = 'round';
  6121. this.wireframeLinejoin = 'round';
  6122. this.vertexColors = THREE.NoColors;
  6123. this.skinning = false;
  6124. this.morphTargets = false;
  6125. this.morphNormals = false;
  6126. this.setValues( parameters );
  6127. };
  6128. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6129. THREE.MeshLambertMaterial.prototype.clone = function () {
  6130. var material = new THREE.MeshLambertMaterial();
  6131. THREE.Material.prototype.clone.call( this, material );
  6132. material.color.copy( this.color );
  6133. material.ambient.copy( this.ambient );
  6134. material.emissive.copy( this.emissive );
  6135. material.wrapAround = this.wrapAround;
  6136. material.wrapRGB.copy( this.wrapRGB );
  6137. material.map = this.map;
  6138. material.lightMap = this.lightMap;
  6139. material.specularMap = this.specularMap;
  6140. material.envMap = this.envMap;
  6141. material.combine = this.combine;
  6142. material.reflectivity = this.reflectivity;
  6143. material.refractionRatio = this.refractionRatio;
  6144. material.fog = this.fog;
  6145. material.shading = this.shading;
  6146. material.wireframe = this.wireframe;
  6147. material.wireframeLinewidth = this.wireframeLinewidth;
  6148. material.wireframeLinecap = this.wireframeLinecap;
  6149. material.wireframeLinejoin = this.wireframeLinejoin;
  6150. material.vertexColors = this.vertexColors;
  6151. material.skinning = this.skinning;
  6152. material.morphTargets = this.morphTargets;
  6153. material.morphNormals = this.morphNormals;
  6154. return material;
  6155. };
  6156. /**
  6157. * @author mrdoob / http://mrdoob.com/
  6158. * @author alteredq / http://alteredqualia.com/
  6159. *
  6160. * parameters = {
  6161. * color: <hex>,
  6162. * ambient: <hex>,
  6163. * emissive: <hex>,
  6164. * specular: <hex>,
  6165. * shininess: <float>,
  6166. * opacity: <float>,
  6167. *
  6168. * map: new THREE.Texture( <Image> ),
  6169. *
  6170. * lightMap: new THREE.Texture( <Image> ),
  6171. *
  6172. * bumpMap: new THREE.Texture( <Image> ),
  6173. * bumpScale: <float>,
  6174. *
  6175. * normalMap: new THREE.Texture( <Image> ),
  6176. * normalScale: <Vector2>,
  6177. *
  6178. * specularMap: new THREE.Texture( <Image> ),
  6179. *
  6180. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6181. * combine: THREE.Multiply,
  6182. * reflectivity: <float>,
  6183. * refractionRatio: <float>,
  6184. *
  6185. * shading: THREE.SmoothShading,
  6186. * blending: THREE.NormalBlending,
  6187. * depthTest: <bool>,
  6188. *
  6189. * wireframe: <boolean>,
  6190. * wireframeLinewidth: <float>,
  6191. *
  6192. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6193. *
  6194. * skinning: <bool>,
  6195. * morphTargets: <bool>,
  6196. * morphNormals: <bool>,
  6197. *
  6198. * fog: <bool>
  6199. * }
  6200. */
  6201. THREE.MeshPhongMaterial = function ( parameters ) {
  6202. THREE.Material.call( this );
  6203. this.color = new THREE.Color( 0xffffff ); // diffuse
  6204. this.ambient = new THREE.Color( 0xffffff );
  6205. this.emissive = new THREE.Color( 0x000000 );
  6206. this.specular = new THREE.Color( 0x111111 );
  6207. this.shininess = 30;
  6208. this.metal = false;
  6209. this.perPixel = true;
  6210. this.wrapAround = false;
  6211. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6212. this.map = null;
  6213. this.lightMap = null;
  6214. this.bumpMap = null;
  6215. this.bumpScale = 1;
  6216. this.normalMap = null;
  6217. this.normalScale = new THREE.Vector2( 1, 1 );
  6218. this.specularMap = null;
  6219. this.envMap = null;
  6220. this.combine = THREE.MultiplyOperation;
  6221. this.reflectivity = 1;
  6222. this.refractionRatio = 0.98;
  6223. this.fog = true;
  6224. this.shading = THREE.SmoothShading;
  6225. this.wireframe = false;
  6226. this.wireframeLinewidth = 1;
  6227. this.wireframeLinecap = 'round';
  6228. this.wireframeLinejoin = 'round';
  6229. this.vertexColors = THREE.NoColors;
  6230. this.skinning = false;
  6231. this.morphTargets = false;
  6232. this.morphNormals = false;
  6233. this.setValues( parameters );
  6234. };
  6235. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6236. THREE.MeshPhongMaterial.prototype.clone = function () {
  6237. var material = new THREE.MeshPhongMaterial();
  6238. THREE.Material.prototype.clone.call( this, material );
  6239. material.color.copy( this.color );
  6240. material.ambient.copy( this.ambient );
  6241. material.emissive.copy( this.emissive );
  6242. material.specular.copy( this.specular );
  6243. material.shininess = this.shininess;
  6244. material.metal = this.metal;
  6245. material.perPixel = this.perPixel;
  6246. material.wrapAround = this.wrapAround;
  6247. material.wrapRGB.copy( this.wrapRGB );
  6248. material.map = this.map;
  6249. material.lightMap = this.lightMap;
  6250. material.bumpMap = this.bumpMap;
  6251. material.bumpScale = this.bumpScale;
  6252. material.normalMap = this.normalMap;
  6253. material.normalScale.copy( this.normalScale );
  6254. material.specularMap = this.specularMap;
  6255. material.envMap = this.envMap;
  6256. material.combine = this.combine;
  6257. material.reflectivity = this.reflectivity;
  6258. material.refractionRatio = this.refractionRatio;
  6259. material.fog = this.fog;
  6260. material.shading = this.shading;
  6261. material.wireframe = this.wireframe;
  6262. material.wireframeLinewidth = this.wireframeLinewidth;
  6263. material.wireframeLinecap = this.wireframeLinecap;
  6264. material.wireframeLinejoin = this.wireframeLinejoin;
  6265. material.vertexColors = this.vertexColors;
  6266. material.skinning = this.skinning;
  6267. material.morphTargets = this.morphTargets;
  6268. material.morphNormals = this.morphNormals;
  6269. return material;
  6270. };
  6271. /**
  6272. * @author mrdoob / http://mrdoob.com/
  6273. * @author alteredq / http://alteredqualia.com/
  6274. *
  6275. * parameters = {
  6276. * opacity: <float>,
  6277. * blending: THREE.NormalBlending,
  6278. * depthTest: <bool>,
  6279. * wireframe: <boolean>,
  6280. * wireframeLinewidth: <float>
  6281. * }
  6282. */
  6283. THREE.MeshDepthMaterial = function ( parameters ) {
  6284. THREE.Material.call( this );
  6285. this.wireframe = false;
  6286. this.wireframeLinewidth = 1;
  6287. this.setValues( parameters );
  6288. };
  6289. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6290. THREE.MeshDepthMaterial.prototype.clone = function () {
  6291. var material = new THREE.LineBasicMaterial();
  6292. THREE.Material.prototype.clone.call( this, material );
  6293. material.wireframe = this.wireframe;
  6294. material.wireframeLinewidth = this.wireframeLinewidth;
  6295. return material;
  6296. };
  6297. /**
  6298. * @author mrdoob / http://mrdoob.com/
  6299. *
  6300. * parameters = {
  6301. * opacity: <float>,
  6302. * shading: THREE.FlatShading,
  6303. * blending: THREE.NormalBlending,
  6304. * depthTest: <bool>,
  6305. * wireframe: <boolean>,
  6306. * wireframeLinewidth: <float>
  6307. * }
  6308. */
  6309. THREE.MeshNormalMaterial = function ( parameters ) {
  6310. THREE.Material.call( this, parameters );
  6311. this.shading = THREE.FlatShading;
  6312. this.wireframe = false;
  6313. this.wireframeLinewidth = 1;
  6314. this.setValues( parameters );
  6315. };
  6316. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6317. THREE.MeshNormalMaterial.prototype.clone = function () {
  6318. var material = new THREE.MeshNormalMaterial();
  6319. THREE.Material.prototype.clone.call( this, material );
  6320. material.shading = this.shading;
  6321. material.wireframe = this.wireframe;
  6322. material.wireframeLinewidth = this.wireframeLinewidth;
  6323. return material;
  6324. };
  6325. /**
  6326. * @author mrdoob / http://mrdoob.com/
  6327. */
  6328. THREE.MeshFaceMaterial = function ( materials ) {
  6329. this.materials = materials instanceof Array ? materials : [];
  6330. };
  6331. THREE.MeshFaceMaterial.prototype.clone = function () {
  6332. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  6333. };
  6334. /**
  6335. * @author mrdoob / http://mrdoob.com/
  6336. * @author alteredq / http://alteredqualia.com/
  6337. *
  6338. * parameters = {
  6339. * color: <hex>,
  6340. * opacity: <float>,
  6341. * map: new THREE.Texture( <Image> ),
  6342. *
  6343. * size: <float>,
  6344. *
  6345. * blending: THREE.NormalBlending,
  6346. * depthTest: <bool>,
  6347. *
  6348. * vertexColors: <bool>,
  6349. *
  6350. * fog: <bool>
  6351. * }
  6352. */
  6353. THREE.ParticleBasicMaterial = function ( parameters ) {
  6354. THREE.Material.call( this );
  6355. this.color = new THREE.Color( 0xffffff );
  6356. this.map = null;
  6357. this.size = 1;
  6358. this.sizeAttenuation = true;
  6359. this.vertexColors = false;
  6360. this.fog = true;
  6361. this.setValues( parameters );
  6362. };
  6363. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6364. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6365. var material = new THREE.ParticleBasicMaterial();
  6366. THREE.Material.prototype.clone.call( this, material );
  6367. material.color.copy( this.color );
  6368. material.map = this.map;
  6369. material.size = this.size;
  6370. material.sizeAttenuation = this.sizeAttenuation;
  6371. material.vertexColors = this.vertexColors;
  6372. material.fog = this.fog;
  6373. return material;
  6374. };
  6375. /**
  6376. * @author mrdoob / http://mrdoob.com/
  6377. *
  6378. * parameters = {
  6379. * color: <hex>,
  6380. * program: <function>,
  6381. * opacity: <float>,
  6382. * blending: THREE.NormalBlending
  6383. * }
  6384. */
  6385. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6386. THREE.Material.call( this );
  6387. this.color = new THREE.Color( 0xffffff );
  6388. this.program = function ( context, color ) {};
  6389. this.setValues( parameters );
  6390. };
  6391. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6392. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6393. var material = new THREE.ParticleCanvasMaterial();
  6394. THREE.Material.prototype.clone.call( this, material );
  6395. material.color.copy( this.color );
  6396. material.program = this.program;
  6397. return material;
  6398. };
  6399. /**
  6400. * @author mrdoob / http://mrdoob.com/
  6401. */
  6402. THREE.ParticleDOMMaterial = function ( element ) {
  6403. this.element = element;
  6404. };
  6405. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6406. return new THREE.ParticleDOMMaterial( this.element );
  6407. };
  6408. /**
  6409. * @author alteredq / http://alteredqualia.com/
  6410. *
  6411. * parameters = {
  6412. * fragmentShader: <string>,
  6413. * vertexShader: <string>,
  6414. *
  6415. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6416. *
  6417. * defines: { "label" : "value" },
  6418. *
  6419. * shading: THREE.SmoothShading,
  6420. * blending: THREE.NormalBlending,
  6421. * depthTest: <bool>,
  6422. *
  6423. * wireframe: <boolean>,
  6424. * wireframeLinewidth: <float>,
  6425. *
  6426. * lights: <bool>,
  6427. *
  6428. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6429. *
  6430. * skinning: <bool>,
  6431. * morphTargets: <bool>,
  6432. * morphNormals: <bool>,
  6433. *
  6434. * fog: <bool>
  6435. * }
  6436. */
  6437. THREE.ShaderMaterial = function ( parameters ) {
  6438. THREE.Material.call( this );
  6439. this.fragmentShader = "void main() {}";
  6440. this.vertexShader = "void main() {}";
  6441. this.uniforms = {};
  6442. this.defines = {};
  6443. this.attributes = null;
  6444. this.shading = THREE.SmoothShading;
  6445. this.wireframe = false;
  6446. this.wireframeLinewidth = 1;
  6447. this.fog = false; // set to use scene fog
  6448. this.lights = false; // set to use scene lights
  6449. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6450. this.skinning = false; // set to use skinning attribute streams
  6451. this.morphTargets = false; // set to use morph targets
  6452. this.morphNormals = false; // set to use morph normals
  6453. this.setValues( parameters );
  6454. };
  6455. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6456. THREE.ShaderMaterial.prototype.clone = function () {
  6457. var material = new THREE.ShaderMaterial();
  6458. THREE.Material.prototype.clone.call( this, material );
  6459. material.fragmentShader = this.fragmentShader;
  6460. material.vertexShader = this.vertexShader;
  6461. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  6462. material.attributes = this.attributes;
  6463. material.defines = this.defines;
  6464. material.shading = this.shading;
  6465. material.wireframe = this.wireframe;
  6466. material.wireframeLinewidth = this.wireframeLinewidth;
  6467. material.fog = this.fog;
  6468. material.lights = this.lights;
  6469. material.vertexColors = this.vertexColors;
  6470. material.skinning = this.skinning;
  6471. material.morphTargets = this.morphTargets;
  6472. material.morphNormals = this.morphNormals;
  6473. return material;
  6474. };
  6475. /**
  6476. * @author mrdoob / http://mrdoob.com/
  6477. * @author alteredq / http://alteredqualia.com/
  6478. * @author szimek / https://github.com/szimek/
  6479. */
  6480. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6481. THREE.TextureLibrary.push( this );
  6482. this.id = THREE.TextureIdCount ++;
  6483. this.name = '';
  6484. this.image = image;
  6485. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6486. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6487. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6488. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6489. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6490. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6491. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6492. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6493. this.offset = new THREE.Vector2( 0, 0 );
  6494. this.repeat = new THREE.Vector2( 1, 1 );
  6495. this.generateMipmaps = true;
  6496. this.premultiplyAlpha = false;
  6497. this.flipY = true;
  6498. this.needsUpdate = false;
  6499. this.onUpdate = null;
  6500. };
  6501. THREE.Texture.prototype = {
  6502. constructor: THREE.Texture,
  6503. clone: function () {
  6504. var texture = new THREE.Texture();
  6505. texture.image = this.image;
  6506. texture.mapping = this.mapping;
  6507. texture.wrapS = this.wrapS;
  6508. texture.wrapT = this.wrapT;
  6509. texture.magFilter = this.magFilter;
  6510. texture.minFilter = this.minFilter;
  6511. texture.anisotropy = this.anisotropy;
  6512. texture.format = this.format;
  6513. texture.type = this.type;
  6514. texture.offset.copy( this.offset );
  6515. texture.repeat.copy( this.repeat );
  6516. texture.generateMipmaps = this.generateMipmaps;
  6517. texture.premultiplyAlpha = this.premultiplyAlpha;
  6518. texture.flipY = this.flipY;
  6519. return texture;
  6520. },
  6521. deallocate: function () {
  6522. var index = THREE.TextureLibrary.indexOf( this );
  6523. if ( index !== -1 ) THREE.TextureLibrary.splice( index, 1 );
  6524. }
  6525. };
  6526. THREE.TextureIdCount = 0;
  6527. THREE.TextureLibrary = [];
  6528. /**
  6529. * @author alteredq / http://alteredqualia.com/
  6530. */
  6531. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6532. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6533. this.image = { width: width, height: height };
  6534. this.mipmaps = mipmaps;
  6535. };
  6536. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  6537. THREE.CompressedTexture.prototype.clone = function () {
  6538. var texture = new THREE.CompressedTexture();
  6539. texture.image = this.image;
  6540. texture.mipmaps = this.mipmaps;
  6541. texture.format = this.format;
  6542. texture.type = this.type;
  6543. texture.mapping = this.mapping;
  6544. texture.wrapS = this.wrapS;
  6545. texture.wrapT = this.wrapT;
  6546. texture.magFilter = this.magFilter;
  6547. texture.minFilter = this.minFilter;
  6548. texture.anisotropy = this.anisotropy;
  6549. texture.offset.copy( this.offset );
  6550. texture.repeat.copy( this.repeat );
  6551. return texture;
  6552. };
  6553. /**
  6554. * @author alteredq / http://alteredqualia.com/
  6555. */
  6556. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6557. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6558. this.image = { data: data, width: width, height: height };
  6559. };
  6560. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6561. THREE.DataTexture.prototype.clone = function () {
  6562. var clonedTexture = new THREE.DataTexture( this.image.data, this.image.width, this.image.height, this.format, this.type, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter );
  6563. clonedTexture.offset.copy( this.offset );
  6564. clonedTexture.repeat.copy( this.repeat );
  6565. return clonedTexture;
  6566. };
  6567. /**
  6568. * @author mrdoob / http://mrdoob.com/
  6569. */
  6570. THREE.Particle = function ( material ) {
  6571. THREE.Object3D.call( this );
  6572. this.material = material;
  6573. };
  6574. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6575. THREE.Particle.prototype.clone = function ( object ) {
  6576. if ( object === undefined ) object = new THREE.Particle( this.material );
  6577. THREE.Object3D.prototype.clone.call( this, object );
  6578. return object;
  6579. };
  6580. /**
  6581. * @author alteredq / http://alteredqualia.com/
  6582. */
  6583. THREE.ParticleSystem = function ( geometry, material ) {
  6584. THREE.Object3D.call( this );
  6585. this.geometry = geometry;
  6586. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6587. this.sortParticles = false;
  6588. if ( this.geometry ) {
  6589. // calc bound radius
  6590. if( this.geometry.boundingSphere === null ) {
  6591. this.geometry.computeBoundingSphere();
  6592. }
  6593. this.boundRadius = geometry.boundingSphere.radius;
  6594. }
  6595. this.frustumCulled = false;
  6596. };
  6597. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6598. THREE.ParticleSystem.prototype.clone = function ( object ) {
  6599. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  6600. object.sortParticles = this.sortParticles;
  6601. THREE.Object3D.prototype.clone.call( this, object );
  6602. return object;
  6603. };
  6604. /**
  6605. * @author mrdoob / http://mrdoob.com/
  6606. */
  6607. THREE.Line = function ( geometry, material, type ) {
  6608. THREE.Object3D.call( this );
  6609. this.geometry = geometry;
  6610. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6611. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6612. if ( this.geometry ) {
  6613. if ( ! this.geometry.boundingSphere ) {
  6614. this.geometry.computeBoundingSphere();
  6615. }
  6616. }
  6617. };
  6618. THREE.LineStrip = 0;
  6619. THREE.LinePieces = 1;
  6620. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6621. THREE.Line.prototype.clone = function ( object ) {
  6622. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  6623. THREE.Object3D.prototype.clone.call( this, object );
  6624. return object;
  6625. };
  6626. /**
  6627. * @author mrdoob / http://mrdoob.com/
  6628. * @author alteredq / http://alteredqualia.com/
  6629. * @author mikael emtinger / http://gomo.se/
  6630. */
  6631. THREE.Mesh = function ( geometry, material ) {
  6632. THREE.Object3D.call( this );
  6633. this.geometry = geometry;
  6634. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6635. if ( this.geometry ) {
  6636. // calc bound radius
  6637. if ( this.geometry.boundingSphere === null ) {
  6638. this.geometry.computeBoundingSphere();
  6639. }
  6640. this.boundRadius = geometry.boundingSphere.radius;
  6641. // setup morph targets
  6642. if ( this.geometry.morphTargets.length ) {
  6643. this.morphTargetBase = -1;
  6644. this.morphTargetForcedOrder = [];
  6645. this.morphTargetInfluences = [];
  6646. this.morphTargetDictionary = {};
  6647. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6648. this.morphTargetInfluences.push( 0 );
  6649. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6650. }
  6651. }
  6652. }
  6653. }
  6654. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6655. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  6656. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6657. return this.morphTargetDictionary[ name ];
  6658. }
  6659. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6660. return 0;
  6661. };
  6662. THREE.Mesh.prototype.clone = function ( object ) {
  6663. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  6664. THREE.Object3D.prototype.clone.call( this, object );
  6665. return object;
  6666. };
  6667. /**
  6668. * @author mikael emtinger / http://gomo.se/
  6669. * @author alteredq / http://alteredqualia.com/
  6670. */
  6671. THREE.Bone = function( belongsToSkin ) {
  6672. THREE.Object3D.call( this );
  6673. this.skin = belongsToSkin;
  6674. this.skinMatrix = new THREE.Matrix4();
  6675. };
  6676. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6677. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6678. // update local
  6679. if ( this.matrixAutoUpdate ) {
  6680. forceUpdate |= this.updateMatrix();
  6681. }
  6682. // update skin matrix
  6683. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6684. if( parentSkinMatrix ) {
  6685. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6686. } else {
  6687. this.skinMatrix.copy( this.matrix );
  6688. }
  6689. this.matrixWorldNeedsUpdate = false;
  6690. forceUpdate = true;
  6691. }
  6692. // update children
  6693. var child, i, l = this.children.length;
  6694. for ( i = 0; i < l; i ++ ) {
  6695. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6696. }
  6697. };
  6698. /**
  6699. * @author mikael emtinger / http://gomo.se/
  6700. * @author alteredq / http://alteredqualia.com/
  6701. */
  6702. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6703. THREE.Mesh.call( this, geometry, material );
  6704. //
  6705. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6706. // init bones
  6707. this.identityMatrix = new THREE.Matrix4();
  6708. this.bones = [];
  6709. this.boneMatrices = [];
  6710. var b, bone, gbone, p, q, s;
  6711. if ( this.geometry && this.geometry.bones !== undefined ) {
  6712. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6713. gbone = this.geometry.bones[ b ];
  6714. p = gbone.pos;
  6715. q = gbone.rotq;
  6716. s = gbone.scl;
  6717. bone = this.addBone();
  6718. bone.name = gbone.name;
  6719. bone.position.set( p[0], p[1], p[2] );
  6720. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6721. bone.useQuaternion = true;
  6722. if ( s !== undefined ) {
  6723. bone.scale.set( s[0], s[1], s[2] );
  6724. } else {
  6725. bone.scale.set( 1, 1, 1 );
  6726. }
  6727. }
  6728. for ( b = 0; b < this.bones.length; b ++ ) {
  6729. gbone = this.geometry.bones[ b ];
  6730. bone = this.bones[ b ];
  6731. if ( gbone.parent === -1 ) {
  6732. this.add( bone );
  6733. } else {
  6734. this.bones[ gbone.parent ].add( bone );
  6735. }
  6736. }
  6737. //
  6738. var nBones = this.bones.length;
  6739. if ( this.useVertexTexture ) {
  6740. // layout (1 matrix = 4 pixels)
  6741. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6742. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6743. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6744. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6745. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6746. var size;
  6747. if ( nBones > 256 )
  6748. size = 64;
  6749. else if ( nBones > 64 )
  6750. size = 32;
  6751. else if ( nBones > 16 )
  6752. size = 16;
  6753. else
  6754. size = 8;
  6755. this.boneTextureWidth = size;
  6756. this.boneTextureHeight = size;
  6757. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6758. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6759. this.boneTexture.minFilter = THREE.NearestFilter;
  6760. this.boneTexture.magFilter = THREE.NearestFilter;
  6761. this.boneTexture.generateMipmaps = false;
  6762. this.boneTexture.flipY = false;
  6763. } else {
  6764. this.boneMatrices = new Float32Array( 16 * nBones );
  6765. }
  6766. this.pose();
  6767. }
  6768. };
  6769. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6770. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6771. if ( bone === undefined ) {
  6772. bone = new THREE.Bone( this );
  6773. }
  6774. this.bones.push( bone );
  6775. return bone;
  6776. };
  6777. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6778. this.matrixAutoUpdate && this.updateMatrix();
  6779. // update matrixWorld
  6780. if ( this.matrixWorldNeedsUpdate || force ) {
  6781. if ( this.parent ) {
  6782. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6783. } else {
  6784. this.matrixWorld.copy( this.matrix );
  6785. }
  6786. this.matrixWorldNeedsUpdate = false;
  6787. force = true;
  6788. }
  6789. // update children
  6790. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6791. var child = this.children[ i ];
  6792. if ( child instanceof THREE.Bone ) {
  6793. child.update( this.identityMatrix, false );
  6794. } else {
  6795. child.updateMatrixWorld( true );
  6796. }
  6797. }
  6798. // make a snapshot of the bones' rest position
  6799. if ( this.boneInverses == undefined ) {
  6800. this.boneInverses = [];
  6801. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6802. var inverse = new THREE.Matrix4();
  6803. inverse.getInverse( this.bones[ b ].skinMatrix );
  6804. this.boneInverses.push( inverse );
  6805. }
  6806. }
  6807. // flatten bone matrices to array
  6808. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6809. // compute the offset between the current and the original transform;
  6810. //TODO: we could get rid of this multiplication step if the skinMatrix
  6811. // was already representing the offset; however, this requires some
  6812. // major changes to the animation system
  6813. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6814. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6815. }
  6816. if ( this.useVertexTexture ) {
  6817. this.boneTexture.needsUpdate = true;
  6818. }
  6819. };
  6820. THREE.SkinnedMesh.prototype.pose = function() {
  6821. this.updateMatrixWorld( true );
  6822. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6823. // normalize weights
  6824. var sw = this.geometry.skinWeights[ i ];
  6825. var scale = 1.0 / sw.lengthManhattan();
  6826. if ( scale !== Infinity ) {
  6827. sw.multiplyScalar( scale );
  6828. } else {
  6829. sw.set( 1 ); // this will be normalized by the shader anyway
  6830. }
  6831. }
  6832. };
  6833. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  6834. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  6835. THREE.Mesh.prototype.clone.call( this, object );
  6836. return object;
  6837. };
  6838. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  6839. /**
  6840. * @author alteredq / http://alteredqualia.com/
  6841. */
  6842. THREE.MorphAnimMesh = function ( geometry, material ) {
  6843. THREE.Mesh.call( this, geometry, material );
  6844. // API
  6845. this.duration = 1000; // milliseconds
  6846. this.mirroredLoop = false;
  6847. this.time = 0;
  6848. // internals
  6849. this.lastKeyframe = 0;
  6850. this.currentKeyframe = 0;
  6851. this.direction = 1;
  6852. this.directionBackwards = false;
  6853. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  6854. };
  6855. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  6856. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  6857. this.startKeyframe = start;
  6858. this.endKeyframe = end;
  6859. this.length = this.endKeyframe - this.startKeyframe + 1;
  6860. };
  6861. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  6862. this.direction = 1;
  6863. this.directionBackwards = false;
  6864. };
  6865. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  6866. this.direction = -1;
  6867. this.directionBackwards = true;
  6868. };
  6869. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  6870. var geometry = this.geometry;
  6871. if ( ! geometry.animations ) geometry.animations = {};
  6872. var firstAnimation, animations = geometry.animations;
  6873. var pattern = /([a-z]+)(\d+)/;
  6874. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  6875. var morph = geometry.morphTargets[ i ];
  6876. var parts = morph.name.match( pattern );
  6877. if ( parts && parts.length > 1 ) {
  6878. var label = parts[ 1 ];
  6879. var num = parts[ 2 ];
  6880. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  6881. var animation = animations[ label ];
  6882. if ( i < animation.start ) animation.start = i;
  6883. if ( i > animation.end ) animation.end = i;
  6884. if ( ! firstAnimation ) firstAnimation = label;
  6885. }
  6886. }
  6887. geometry.firstAnimation = firstAnimation;
  6888. };
  6889. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  6890. if ( ! this.geometry.animations ) this.geometry.animations = {};
  6891. this.geometry.animations[ label ] = { start: start, end: end };
  6892. };
  6893. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  6894. var animation = this.geometry.animations[ label ];
  6895. if ( animation ) {
  6896. this.setFrameRange( animation.start, animation.end );
  6897. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  6898. this.time = 0;
  6899. } else {
  6900. console.warn( "animation[" + label + "] undefined" );
  6901. }
  6902. };
  6903. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  6904. var frameTime = this.duration / this.length;
  6905. this.time += this.direction * delta;
  6906. if ( this.mirroredLoop ) {
  6907. if ( this.time > this.duration || this.time < 0 ) {
  6908. this.direction *= -1;
  6909. if ( this.time > this.duration ) {
  6910. this.time = this.duration;
  6911. this.directionBackwards = true;
  6912. }
  6913. if ( this.time < 0 ) {
  6914. this.time = 0;
  6915. this.directionBackwards = false;
  6916. }
  6917. }
  6918. } else {
  6919. this.time = this.time % this.duration;
  6920. if ( this.time < 0 ) this.time += this.duration;
  6921. }
  6922. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  6923. if ( keyframe !== this.currentKeyframe ) {
  6924. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  6925. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  6926. this.morphTargetInfluences[ keyframe ] = 0;
  6927. this.lastKeyframe = this.currentKeyframe;
  6928. this.currentKeyframe = keyframe;
  6929. }
  6930. var mix = ( this.time % frameTime ) / frameTime;
  6931. if ( this.directionBackwards ) {
  6932. mix = 1 - mix;
  6933. }
  6934. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  6935. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  6936. };
  6937. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  6938. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  6939. object.duration = this.duration;
  6940. object.mirroredLoop = this.mirroredLoop;
  6941. object.time = this.time;
  6942. object.lastKeyframe = this.lastKeyframe;
  6943. object.currentKeyframe = this.currentKeyframe;
  6944. object.direction = this.direction;
  6945. object.directionBackwards = this.directionBackwards;
  6946. THREE.Mesh.prototype.clone.call( this, object );
  6947. return object;
  6948. };
  6949. /**
  6950. * @author alteredq / http://alteredqualia.com/
  6951. */
  6952. THREE.Ribbon = function ( geometry, material ) {
  6953. THREE.Object3D.call( this );
  6954. this.geometry = geometry;
  6955. this.material = material;
  6956. };
  6957. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  6958. THREE.Ribbon.prototype.clone = function ( object ) {
  6959. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  6960. THREE.Object3D.prototype.clone.call( this, object );
  6961. return object;
  6962. };
  6963. /**
  6964. * @author mikael emtinger / http://gomo.se/
  6965. * @author alteredq / http://alteredqualia.com/
  6966. * @author mrdoob / http://mrdoob.com/
  6967. */
  6968. THREE.LOD = function () {
  6969. THREE.Object3D.call( this );
  6970. this.LODs = [];
  6971. };
  6972. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  6973. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  6974. if ( visibleAtDistance === undefined ) {
  6975. visibleAtDistance = 0;
  6976. }
  6977. visibleAtDistance = Math.abs( visibleAtDistance );
  6978. for ( var l = 0; l < this.LODs.length; l ++ ) {
  6979. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  6980. break;
  6981. }
  6982. }
  6983. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  6984. this.add( object3D );
  6985. };
  6986. THREE.LOD.prototype.update = function ( camera ) {
  6987. if ( this.LODs.length > 1 ) {
  6988. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  6989. var inverse = camera.matrixWorldInverse;
  6990. 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] );
  6991. this.LODs[ 0 ].object3D.visible = true;
  6992. for ( var l = 1; l < this.LODs.length; l ++ ) {
  6993. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  6994. this.LODs[ l - 1 ].object3D.visible = false;
  6995. this.LODs[ l ].object3D.visible = true;
  6996. } else {
  6997. break;
  6998. }
  6999. }
  7000. for( ; l < this.LODs.length; l ++ ) {
  7001. this.LODs[ l ].object3D.visible = false;
  7002. }
  7003. }
  7004. };
  7005. THREE.LOD.prototype.clone = function () {
  7006. // TODO
  7007. };
  7008. /**
  7009. * @author mikael emtinger / http://gomo.se/
  7010. * @author alteredq / http://alteredqualia.com/
  7011. */
  7012. THREE.Sprite = function ( parameters ) {
  7013. THREE.Object3D.call( this );
  7014. parameters = parameters || {};
  7015. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  7016. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  7017. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  7018. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  7019. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  7020. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  7021. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  7022. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  7023. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  7024. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  7025. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center.clone();
  7026. this.fog = ( parameters.fog !== undefined ) ? parameters.fog : false;
  7027. this.rotation3d = this.rotation;
  7028. this.rotation = 0;
  7029. this.opacity = 1;
  7030. this.uvOffset = new THREE.Vector2( 0, 0 );
  7031. this.uvScale = new THREE.Vector2( 1, 1 );
  7032. };
  7033. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7034. /*
  7035. * Custom update matrix
  7036. */
  7037. THREE.Sprite.prototype.updateMatrix = function () {
  7038. this.matrix.setPosition( this.position );
  7039. this.rotation3d.set( 0, 0, this.rotation );
  7040. this.matrix.setRotationFromEuler( this.rotation3d );
  7041. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7042. this.matrix.scale( this.scale );
  7043. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  7044. }
  7045. this.matrixWorldNeedsUpdate = true;
  7046. };
  7047. THREE.Sprite.prototype.clone = function ( object ) {
  7048. if ( object === undefined ) object = new THREE.Sprite( {} );
  7049. object.color.copy( this.color );
  7050. object.map = this.map;
  7051. object.blending = this.blending;
  7052. object.useScreenCoordinates = this.useScreenCoordinates;
  7053. object.mergeWith3D = this.mergeWith3D;
  7054. object.affectedByDistance = this.affectedByDistance;
  7055. object.scaleByViewport = this.scaleByViewport;
  7056. object.alignment = this.alignment;
  7057. object.fog = this.fog;
  7058. object.rotation3d.copy( this.rotation3d );
  7059. object.rotation = this.rotation;
  7060. object.opacity = this.opacity;
  7061. object.uvOffset.copy( this.uvOffset );
  7062. object.uvScale.copy( this.uvScale);
  7063. THREE.Object3D.prototype.clone.call( this, object );
  7064. return object;
  7065. };
  7066. /*
  7067. * Alignment
  7068. */
  7069. THREE.SpriteAlignment = {};
  7070. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7071. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7072. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7073. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7074. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7075. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7076. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7077. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7078. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7079. /**
  7080. * @author mrdoob / http://mrdoob.com/
  7081. */
  7082. THREE.Scene = function () {
  7083. THREE.Object3D.call( this );
  7084. this.fog = null;
  7085. this.overrideMaterial = null;
  7086. this.matrixAutoUpdate = false;
  7087. this.__objects = [];
  7088. this.__lights = [];
  7089. this.__objectsAdded = [];
  7090. this.__objectsRemoved = [];
  7091. };
  7092. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7093. THREE.Scene.prototype.__addObject = function ( object ) {
  7094. if ( object instanceof THREE.Light ) {
  7095. if ( this.__lights.indexOf( object ) === - 1 ) {
  7096. this.__lights.push( object );
  7097. }
  7098. if ( object.target && object.target.parent === undefined ) {
  7099. this.add( object.target );
  7100. }
  7101. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7102. if ( this.__objects.indexOf( object ) === - 1 ) {
  7103. this.__objects.push( object );
  7104. this.__objectsAdded.push( object );
  7105. // check if previously removed
  7106. var i = this.__objectsRemoved.indexOf( object );
  7107. if ( i !== -1 ) {
  7108. this.__objectsRemoved.splice( i, 1 );
  7109. }
  7110. }
  7111. }
  7112. for ( var c = 0; c < object.children.length; c ++ ) {
  7113. this.__addObject( object.children[ c ] );
  7114. }
  7115. };
  7116. THREE.Scene.prototype.__removeObject = function ( object ) {
  7117. if ( object instanceof THREE.Light ) {
  7118. var i = this.__lights.indexOf( object );
  7119. if ( i !== -1 ) {
  7120. this.__lights.splice( i, 1 );
  7121. }
  7122. } else if ( !( object instanceof THREE.Camera ) ) {
  7123. var i = this.__objects.indexOf( object );
  7124. if( i !== -1 ) {
  7125. this.__objects.splice( i, 1 );
  7126. this.__objectsRemoved.push( object );
  7127. // check if previously added
  7128. var ai = this.__objectsAdded.indexOf( object );
  7129. if ( ai !== -1 ) {
  7130. this.__objectsAdded.splice( ai, 1 );
  7131. }
  7132. }
  7133. }
  7134. for ( var c = 0; c < object.children.length; c ++ ) {
  7135. this.__removeObject( object.children[ c ] );
  7136. }
  7137. };
  7138. /**
  7139. * @author mrdoob / http://mrdoob.com/
  7140. * @author alteredq / http://alteredqualia.com/
  7141. */
  7142. THREE.Fog = function ( hex, near, far ) {
  7143. this.name = '';
  7144. this.color = new THREE.Color( hex );
  7145. this.near = ( near !== undefined ) ? near : 1;
  7146. this.far = ( far !== undefined ) ? far : 1000;
  7147. };
  7148. THREE.Fog.prototype.clone = function () {
  7149. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7150. };
  7151. /**
  7152. * @author mrdoob / http://mrdoob.com/
  7153. * @author alteredq / http://alteredqualia.com/
  7154. */
  7155. THREE.FogExp2 = function ( hex, density ) {
  7156. this.name = '';
  7157. this.color = new THREE.Color( hex );
  7158. this.density = ( density !== undefined ) ? density : 0.00025;
  7159. };
  7160. THREE.FogExp2.prototype.clone = function () {
  7161. return new THREE.FogExp2( this.color.getHex(), this.density );
  7162. };
  7163. /**
  7164. * @author mrdoob / http://mrdoob.com/
  7165. */
  7166. THREE.CanvasRenderer = function ( parameters ) {
  7167. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7168. parameters = parameters || {};
  7169. var _this = this,
  7170. _renderData, _elements, _lights,
  7171. _projector = new THREE.Projector(),
  7172. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7173. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7174. _context = _canvas.getContext( '2d' ),
  7175. _clearColor = new THREE.Color( 0x000000 ),
  7176. _clearOpacity = 0,
  7177. _contextGlobalAlpha = 1,
  7178. _contextGlobalCompositeOperation = 0,
  7179. _contextStrokeStyle = null,
  7180. _contextFillStyle = null,
  7181. _contextLineWidth = null,
  7182. _contextLineCap = null,
  7183. _contextLineJoin = null,
  7184. _v1, _v2, _v3, _v4,
  7185. _v5 = new THREE.RenderableVertex(),
  7186. _v6 = new THREE.RenderableVertex(),
  7187. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7188. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7189. _color = new THREE.Color(),
  7190. _color1 = new THREE.Color(),
  7191. _color2 = new THREE.Color(),
  7192. _color3 = new THREE.Color(),
  7193. _color4 = new THREE.Color(),
  7194. _diffuseColor = new THREE.Color(),
  7195. _emissiveColor = new THREE.Color(),
  7196. _patterns = {}, _imagedatas = {},
  7197. _near, _far,
  7198. _image, _uvs,
  7199. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7200. _clipRect = new THREE.Rectangle(),
  7201. _clearRect = new THREE.Rectangle(),
  7202. _bboxRect = new THREE.Rectangle(),
  7203. _enableLighting = false,
  7204. _ambientLight = new THREE.Color(),
  7205. _directionalLights = new THREE.Color(),
  7206. _pointLights = new THREE.Color(),
  7207. _pi2 = Math.PI * 2,
  7208. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7209. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7210. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7211. _pixelMap = document.createElement( 'canvas' );
  7212. _pixelMap.width = _pixelMap.height = 2;
  7213. _pixelMapContext = _pixelMap.getContext( '2d' );
  7214. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7215. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7216. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7217. _pixelMapData = _pixelMapImage.data;
  7218. _gradientMap = document.createElement( 'canvas' );
  7219. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7220. _gradientMapContext = _gradientMap.getContext( '2d' );
  7221. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7222. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7223. _gradientMapQuality --; // Fix UVs
  7224. this.domElement = _canvas;
  7225. this.autoClear = true;
  7226. this.sortObjects = true;
  7227. this.sortElements = true;
  7228. this.info = {
  7229. render: {
  7230. vertices: 0,
  7231. faces: 0
  7232. }
  7233. }
  7234. this.setSize = function ( width, height ) {
  7235. _canvasWidth = width;
  7236. _canvasHeight = height;
  7237. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7238. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7239. _canvas.width = _canvasWidth;
  7240. _canvas.height = _canvasHeight;
  7241. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7242. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7243. _contextGlobalAlpha = 1;
  7244. _contextGlobalCompositeOperation = 0;
  7245. _contextStrokeStyle = null;
  7246. _contextFillStyle = null;
  7247. _contextLineWidth = null;
  7248. _contextLineCap = null;
  7249. _contextLineJoin = null;
  7250. };
  7251. this.setClearColor = function ( color, opacity ) {
  7252. _clearColor.copy( color );
  7253. _clearOpacity = opacity !== undefined ? opacity : 1;
  7254. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7255. };
  7256. this.setClearColorHex = function ( hex, opacity ) {
  7257. _clearColor.setHex( hex );
  7258. _clearOpacity = opacity !== undefined ? opacity : 1;
  7259. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7260. };
  7261. this.getMaxAnisotropy = function () {
  7262. return 0;
  7263. };
  7264. this.clear = function () {
  7265. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7266. if ( _clearRect.isEmpty() === false ) {
  7267. _clearRect.minSelf( _clipRect );
  7268. _clearRect.inflate( 2 );
  7269. if ( _clearOpacity < 1 ) {
  7270. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7271. }
  7272. if ( _clearOpacity > 0 ) {
  7273. setBlending( THREE.NormalBlending );
  7274. setOpacity( 1 );
  7275. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7276. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7277. }
  7278. _clearRect.empty();
  7279. }
  7280. };
  7281. this.render = function ( scene, camera ) {
  7282. if ( camera instanceof THREE.Camera === false ) {
  7283. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7284. return;
  7285. }
  7286. var e, el, element, material;
  7287. this.autoClear === true
  7288. ? this.clear()
  7289. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7290. _this.info.render.vertices = 0;
  7291. _this.info.render.faces = 0;
  7292. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7293. _elements = _renderData.elements;
  7294. _lights = _renderData.lights;
  7295. /* DEBUG
  7296. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7297. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7298. */
  7299. _enableLighting = _lights.length > 0;
  7300. if ( _enableLighting === true ) {
  7301. calculateLights();
  7302. }
  7303. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7304. element = _elements[ e ];
  7305. material = element.material;
  7306. if ( material === undefined || material.visible === false ) continue;
  7307. _bboxRect.empty();
  7308. if ( element instanceof THREE.RenderableParticle ) {
  7309. _v1 = element;
  7310. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7311. renderParticle( _v1, element, material, scene );
  7312. } else if ( element instanceof THREE.RenderableLine ) {
  7313. _v1 = element.v1; _v2 = element.v2;
  7314. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7315. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7316. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7317. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7318. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7319. renderLine( _v1, _v2, element, material, scene );
  7320. }
  7321. } else if ( element instanceof THREE.RenderableFace3 ) {
  7322. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7323. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7324. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7325. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7326. if ( material.overdraw === true ) {
  7327. expand( _v1.positionScreen, _v2.positionScreen );
  7328. expand( _v2.positionScreen, _v3.positionScreen );
  7329. expand( _v3.positionScreen, _v1.positionScreen );
  7330. }
  7331. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7332. _v2.positionScreen.x, _v2.positionScreen.y,
  7333. _v3.positionScreen.x, _v3.positionScreen.y );
  7334. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7335. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7336. }
  7337. } else if ( element instanceof THREE.RenderableFace4 ) {
  7338. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7339. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7340. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7341. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7342. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7343. _v5.positionScreen.copy( _v2.positionScreen );
  7344. _v6.positionScreen.copy( _v4.positionScreen );
  7345. if ( material.overdraw === true ) {
  7346. expand( _v1.positionScreen, _v2.positionScreen );
  7347. expand( _v2.positionScreen, _v4.positionScreen );
  7348. expand( _v4.positionScreen, _v1.positionScreen );
  7349. expand( _v3.positionScreen, _v5.positionScreen );
  7350. expand( _v3.positionScreen, _v6.positionScreen );
  7351. }
  7352. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7353. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7354. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7355. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7356. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7357. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7358. }
  7359. }
  7360. /* DEBUG
  7361. _context.lineWidth = 1;
  7362. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7363. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7364. */
  7365. _clearRect.addRectangle( _bboxRect );
  7366. }
  7367. /* DEBUG
  7368. _context.lineWidth = 1;
  7369. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7370. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7371. */
  7372. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7373. //
  7374. function calculateLights() {
  7375. _ambientLight.setRGB( 0, 0, 0 );
  7376. _directionalLights.setRGB( 0, 0, 0 );
  7377. _pointLights.setRGB( 0, 0, 0 );
  7378. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7379. var light = _lights[ l ];
  7380. var lightColor = light.color;
  7381. if ( light instanceof THREE.AmbientLight ) {
  7382. _ambientLight.r += lightColor.r;
  7383. _ambientLight.g += lightColor.g;
  7384. _ambientLight.b += lightColor.b;
  7385. } else if ( light instanceof THREE.DirectionalLight ) {
  7386. // for particles
  7387. _directionalLights.r += lightColor.r;
  7388. _directionalLights.g += lightColor.g;
  7389. _directionalLights.b += lightColor.b;
  7390. } else if ( light instanceof THREE.PointLight ) {
  7391. // for particles
  7392. _pointLights.r += lightColor.r;
  7393. _pointLights.g += lightColor.g;
  7394. _pointLights.b += lightColor.b;
  7395. }
  7396. }
  7397. }
  7398. function calculateLight( position, normal, color ) {
  7399. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7400. var light = _lights[ l ];
  7401. var lightColor = light.color;
  7402. if ( light instanceof THREE.DirectionalLight ) {
  7403. var lightPosition = light.matrixWorld.getPosition().normalize();
  7404. var amount = normal.dot( lightPosition );
  7405. if ( amount <= 0 ) continue;
  7406. amount *= light.intensity;
  7407. color.r += lightColor.r * amount;
  7408. color.g += lightColor.g * amount;
  7409. color.b += lightColor.b * amount;
  7410. } else if ( light instanceof THREE.PointLight ) {
  7411. var lightPosition = light.matrixWorld.getPosition();
  7412. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7413. if ( amount <= 0 ) continue;
  7414. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7415. if ( amount == 0 ) continue;
  7416. amount *= light.intensity;
  7417. color.r += lightColor.r * amount;
  7418. color.g += lightColor.g * amount;
  7419. color.b += lightColor.b * amount;
  7420. }
  7421. }
  7422. }
  7423. function renderParticle( v1, element, material, scene ) {
  7424. setOpacity( material.opacity );
  7425. setBlending( material.blending );
  7426. var width, height, scaleX, scaleY,
  7427. bitmap, bitmapWidth, bitmapHeight;
  7428. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7429. if ( material.map === null ) {
  7430. scaleX = element.object.scale.x;
  7431. scaleY = element.object.scale.y;
  7432. // TODO: Be able to disable this
  7433. scaleX *= element.scale.x * _canvasWidthHalf;
  7434. scaleY *= element.scale.y * _canvasHeightHalf;
  7435. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7436. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7437. return;
  7438. }
  7439. setFillStyle( material.color.getContextStyle() );
  7440. _context.save();
  7441. _context.translate( v1.x, v1.y );
  7442. _context.rotate( - element.rotation );
  7443. _context.scale( scaleX, scaleY );
  7444. _context.fillRect( -1, -1, 2, 2 );
  7445. _context.restore();
  7446. } else {
  7447. bitmap = material.map.image;
  7448. bitmapWidth = bitmap.width >> 1;
  7449. bitmapHeight = bitmap.height >> 1;
  7450. scaleX = element.scale.x * _canvasWidthHalf;
  7451. scaleY = element.scale.y * _canvasHeightHalf;
  7452. width = scaleX * bitmapWidth;
  7453. height = scaleY * bitmapHeight;
  7454. // TODO: Rotations break this...
  7455. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7456. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7457. return;
  7458. }
  7459. _context.save();
  7460. _context.translate( v1.x, v1.y );
  7461. _context.rotate( - element.rotation );
  7462. _context.scale( scaleX, - scaleY );
  7463. _context.translate( - bitmapWidth, - bitmapHeight );
  7464. _context.drawImage( bitmap, 0, 0 );
  7465. _context.restore();
  7466. }
  7467. /* DEBUG
  7468. setStrokeStyle( 'rgb(255,255,0)' );
  7469. _context.beginPath();
  7470. _context.moveTo( v1.x - 10, v1.y );
  7471. _context.lineTo( v1.x + 10, v1.y );
  7472. _context.moveTo( v1.x, v1.y - 10 );
  7473. _context.lineTo( v1.x, v1.y + 10 );
  7474. _context.stroke();
  7475. */
  7476. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7477. width = element.scale.x * _canvasWidthHalf;
  7478. height = element.scale.y * _canvasHeightHalf;
  7479. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7480. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7481. return;
  7482. }
  7483. setStrokeStyle( material.color.getContextStyle() );
  7484. setFillStyle( material.color.getContextStyle() );
  7485. _context.save();
  7486. _context.translate( v1.x, v1.y );
  7487. _context.rotate( - element.rotation );
  7488. _context.scale( width, height );
  7489. material.program( _context );
  7490. _context.restore();
  7491. }
  7492. }
  7493. function renderLine( v1, v2, element, material, scene ) {
  7494. setOpacity( material.opacity );
  7495. setBlending( material.blending );
  7496. _context.beginPath();
  7497. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7498. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7499. if ( material instanceof THREE.LineBasicMaterial ) {
  7500. setLineWidth( material.linewidth );
  7501. setLineCap( material.linecap );
  7502. setLineJoin( material.linejoin );
  7503. setStrokeStyle( material.color.getContextStyle() );
  7504. _context.stroke();
  7505. _bboxRect.inflate( material.linewidth * 2 );
  7506. }
  7507. }
  7508. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7509. _this.info.render.vertices += 3;
  7510. _this.info.render.faces ++;
  7511. setOpacity( material.opacity );
  7512. setBlending( material.blending );
  7513. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7514. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7515. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7516. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7517. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  7518. _diffuseColor.copy( material.color );
  7519. _emissiveColor.copy( material.emissive );
  7520. if ( material.vertexColors === THREE.FaceColors ) {
  7521. _diffuseColor.r *= element.color.r;
  7522. _diffuseColor.g *= element.color.g;
  7523. _diffuseColor.b *= element.color.b;
  7524. }
  7525. if ( _enableLighting === true ) {
  7526. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7527. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7528. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7529. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7530. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7531. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7532. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7533. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7534. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7535. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7536. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7537. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7538. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7539. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7540. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7541. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7542. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7543. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7544. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7545. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7546. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7547. } else {
  7548. _color.r = _ambientLight.r;
  7549. _color.g = _ambientLight.g;
  7550. _color.b = _ambientLight.b;
  7551. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7552. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7553. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7554. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7555. material.wireframe === true
  7556. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7557. : fillPath( _color );
  7558. }
  7559. } else {
  7560. material.wireframe === true
  7561. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7562. : fillPath( material.color );
  7563. }
  7564. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7565. if ( material.map !== null ) {
  7566. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7567. _uvs = element.uvs[ 0 ];
  7568. 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 );
  7569. }
  7570. } else if ( material.envMap !== null ) {
  7571. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7572. var cameraMatrix = camera.matrixWorldInverse;
  7573. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7574. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7575. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7576. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7577. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7578. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7579. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7580. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7581. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7582. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7583. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7584. }*/
  7585. } else {
  7586. _color.copy( material.color );
  7587. if ( material.vertexColors === THREE.FaceColors ) {
  7588. _color.r *= element.color.r;
  7589. _color.g *= element.color.g;
  7590. _color.b *= element.color.b;
  7591. }
  7592. material.wireframe === true
  7593. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7594. : fillPath( _color );
  7595. }
  7596. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7597. _near = camera.near;
  7598. _far = camera.far;
  7599. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7600. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7601. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7602. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7603. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7604. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7605. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7606. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7607. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7608. _color.r = normalToComponent( element.normalWorld.x );
  7609. _color.g = normalToComponent( element.normalWorld.y );
  7610. _color.b = normalToComponent( element.normalWorld.z );
  7611. material.wireframe === true
  7612. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7613. : fillPath( _color );
  7614. }
  7615. }
  7616. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7617. _this.info.render.vertices += 4;
  7618. _this.info.render.faces ++;
  7619. setOpacity( material.opacity );
  7620. setBlending( material.blending );
  7621. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7622. // Let renderFace3() handle this
  7623. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7624. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7625. return;
  7626. }
  7627. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7628. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7629. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7630. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7631. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7632. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7633. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7634. _diffuseColor.copy( material.color );
  7635. _emissiveColor.copy( material.emissive );
  7636. if ( material.vertexColors === THREE.FaceColors ) {
  7637. _diffuseColor.r *= element.color.r;
  7638. _diffuseColor.g *= element.color.g;
  7639. _diffuseColor.b *= element.color.b;
  7640. }
  7641. if ( _enableLighting === true ) {
  7642. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7643. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7644. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7645. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7646. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7647. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7648. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7649. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7650. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7651. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7652. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7653. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7654. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7655. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7656. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7657. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7658. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7659. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  7660. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  7661. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  7662. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7663. // TODO: UVs are incorrect, v4->v3?
  7664. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7665. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7666. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7667. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7668. } else {
  7669. _color.r = _ambientLight.r;
  7670. _color.g = _ambientLight.g;
  7671. _color.b = _ambientLight.b;
  7672. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7673. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7674. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7675. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7676. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7677. material.wireframe === true
  7678. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7679. : fillPath( _color );
  7680. }
  7681. } else {
  7682. _color.r = _diffuseColor.r + _emissiveColor.r;
  7683. _color.g = _diffuseColor.g + _emissiveColor.g;
  7684. _color.b = _diffuseColor.b + _emissiveColor.b;
  7685. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7686. material.wireframe === true
  7687. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7688. : fillPath( _color );
  7689. }
  7690. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  7691. _color.copy( material.color );
  7692. if ( material.vertexColors === THREE.FaceColors ) {
  7693. _color.r *= element.color.r;
  7694. _color.g *= element.color.g;
  7695. _color.b *= element.color.b;
  7696. }
  7697. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7698. material.wireframe === true
  7699. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7700. : fillPath( _color );
  7701. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7702. _color.r = normalToComponent( element.normalWorld.x );
  7703. _color.g = normalToComponent( element.normalWorld.y );
  7704. _color.b = normalToComponent( element.normalWorld.z );
  7705. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7706. material.wireframe === true
  7707. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7708. : fillPath( _color );
  7709. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7710. _near = camera.near;
  7711. _far = camera.far;
  7712. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7713. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7714. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7715. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7716. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7717. // TODO: UVs are incorrect, v4->v3?
  7718. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7719. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7720. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7721. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7722. }
  7723. }
  7724. //
  7725. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7726. _context.beginPath();
  7727. _context.moveTo( x0, y0 );
  7728. _context.lineTo( x1, y1 );
  7729. _context.lineTo( x2, y2 );
  7730. _context.closePath();
  7731. }
  7732. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7733. _context.beginPath();
  7734. _context.moveTo( x0, y0 );
  7735. _context.lineTo( x1, y1 );
  7736. _context.lineTo( x2, y2 );
  7737. _context.lineTo( x3, y3 );
  7738. _context.closePath();
  7739. }
  7740. function strokePath( color, linewidth, linecap, linejoin ) {
  7741. setLineWidth( linewidth );
  7742. setLineCap( linecap );
  7743. setLineJoin( linejoin );
  7744. setStrokeStyle( color.getContextStyle() );
  7745. _context.stroke();
  7746. _bboxRect.inflate( linewidth * 2 );
  7747. }
  7748. function fillPath( color ) {
  7749. setFillStyle( color.getContextStyle() );
  7750. _context.fill();
  7751. }
  7752. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7753. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  7754. if ( texture.needsUpdate === true ) {
  7755. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7756. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7757. _patterns[ texture.id ] = _context.createPattern(
  7758. texture.image, repeatX === true && repeatY === true
  7759. ? 'repeat'
  7760. : repeatX === true && repeatY === false
  7761. ? 'repeat-x'
  7762. : repeatX === false && repeatY === true
  7763. ? 'repeat-y'
  7764. : 'no-repeat'
  7765. );
  7766. texture.needsUpdate = false;
  7767. }
  7768. _patterns[ texture.id ] === undefined
  7769. ? setFillStyle( 'rgba(0,0,0,1)' )
  7770. : setFillStyle( _patterns[ texture.id ] );
  7771. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7772. var a, b, c, d, e, f, det, idet,
  7773. offsetX = texture.offset.x / texture.repeat.x,
  7774. offsetY = texture.offset.y / texture.repeat.y,
  7775. width = texture.image.width * texture.repeat.x,
  7776. height = texture.image.height * texture.repeat.y;
  7777. u0 = ( u0 + offsetX ) * width;
  7778. v0 = ( 1.0 - v0 + offsetY ) * height;
  7779. u1 = ( u1 + offsetX ) * width;
  7780. v1 = ( 1.0 - v1 + offsetY ) * height;
  7781. u2 = ( u2 + offsetX ) * width;
  7782. v2 = ( 1.0 - v2 + offsetY ) * height;
  7783. x1 -= x0; y1 -= y0;
  7784. x2 -= x0; y2 -= y0;
  7785. u1 -= u0; v1 -= v0;
  7786. u2 -= u0; v2 -= v0;
  7787. det = u1 * v2 - u2 * v1;
  7788. if ( det === 0 ) {
  7789. if ( _imagedatas[ texture.id ] === undefined ) {
  7790. var canvas = document.createElement( 'canvas' )
  7791. canvas.width = texture.image.width;
  7792. canvas.height = texture.image.height;
  7793. var context = canvas.getContext( '2d' );
  7794. context.drawImage( texture.image, 0, 0 );
  7795. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7796. }
  7797. var data = _imagedatas[ texture.id ];
  7798. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7799. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7800. fillPath( _color );
  7801. return;
  7802. }
  7803. idet = 1 / det;
  7804. a = ( v2 * x1 - v1 * x2 ) * idet;
  7805. b = ( v2 * y1 - v1 * y2 ) * idet;
  7806. c = ( u1 * x2 - u2 * x1 ) * idet;
  7807. d = ( u1 * y2 - u2 * y1 ) * idet;
  7808. e = x0 - a * u0 - c * v0;
  7809. f = y0 - b * u0 - d * v0;
  7810. _context.save();
  7811. _context.transform( a, b, c, d, e, f );
  7812. _context.fill();
  7813. _context.restore();
  7814. }
  7815. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7816. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7817. var a, b, c, d, e, f, det, idet,
  7818. width = image.width - 1,
  7819. height = image.height - 1;
  7820. u0 *= width; v0 *= height;
  7821. u1 *= width; v1 *= height;
  7822. u2 *= width; v2 *= height;
  7823. x1 -= x0; y1 -= y0;
  7824. x2 -= x0; y2 -= y0;
  7825. u1 -= u0; v1 -= v0;
  7826. u2 -= u0; v2 -= v0;
  7827. det = u1 * v2 - u2 * v1;
  7828. idet = 1 / det;
  7829. a = ( v2 * x1 - v1 * x2 ) * idet;
  7830. b = ( v2 * y1 - v1 * y2 ) * idet;
  7831. c = ( u1 * x2 - u2 * x1 ) * idet;
  7832. d = ( u1 * y2 - u2 * y1 ) * idet;
  7833. e = x0 - a * u0 - c * v0;
  7834. f = y0 - b * u0 - d * v0;
  7835. _context.save();
  7836. _context.transform( a, b, c, d, e, f );
  7837. _context.clip();
  7838. _context.drawImage( image, 0, 0 );
  7839. _context.restore();
  7840. }
  7841. function getGradientTexture( color1, color2, color3, color4 ) {
  7842. // http://mrdoob.com/blog/post/710
  7843. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  7844. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  7845. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  7846. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  7847. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  7848. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  7849. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  7850. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  7851. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  7852. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  7853. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  7854. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  7855. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7856. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7857. return _gradientMap;
  7858. }
  7859. function smoothstep( value, min, max ) {
  7860. var x = ( value - min ) / ( max - min );
  7861. return x * x * ( 3 - 2 * x );
  7862. }
  7863. function normalToComponent( normal ) {
  7864. var component = ( normal + 1 ) * 0.5;
  7865. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7866. }
  7867. // Hide anti-alias gaps
  7868. function expand( v1, v2 ) {
  7869. var x = v2.x - v1.x, y = v2.y - v1.y,
  7870. det = x * x + y * y, idet;
  7871. if ( det === 0 ) return;
  7872. idet = 1 / Math.sqrt( det );
  7873. x *= idet; y *= idet;
  7874. v2.x += x; v2.y += y;
  7875. v1.x -= x; v1.y -= y;
  7876. }
  7877. };
  7878. // Context cached methods.
  7879. function setOpacity( value ) {
  7880. if ( _contextGlobalAlpha !== value ) {
  7881. _context.globalAlpha = value;
  7882. _contextGlobalAlpha = value;
  7883. }
  7884. }
  7885. function setBlending( value ) {
  7886. if ( _contextGlobalCompositeOperation !== value ) {
  7887. if ( value === THREE.NormalBlending ) {
  7888. _context.globalCompositeOperation = 'source-over';
  7889. } else if ( value === THREE.AdditiveBlending ) {
  7890. _context.globalCompositeOperation = 'lighter';
  7891. } else if ( value === THREE.SubtractiveBlending ) {
  7892. _context.globalCompositeOperation = 'darker';
  7893. }
  7894. _contextGlobalCompositeOperation = value;
  7895. }
  7896. }
  7897. function setLineWidth( value ) {
  7898. if ( _contextLineWidth !== value ) {
  7899. _context.lineWidth = value;
  7900. _contextLineWidth = value;
  7901. }
  7902. }
  7903. function setLineCap( value ) {
  7904. // "butt", "round", "square"
  7905. if ( _contextLineCap !== value ) {
  7906. _context.lineCap = value;
  7907. _contextLineCap = value;
  7908. }
  7909. }
  7910. function setLineJoin( value ) {
  7911. // "round", "bevel", "miter"
  7912. if ( _contextLineJoin !== value ) {
  7913. _context.lineJoin = value;
  7914. _contextLineJoin = value;
  7915. }
  7916. }
  7917. function setStrokeStyle( value ) {
  7918. if ( _contextStrokeStyle !== value ) {
  7919. _context.strokeStyle = value;
  7920. _contextStrokeStyle = value;
  7921. }
  7922. }
  7923. function setFillStyle( value ) {
  7924. if ( _contextFillStyle !== value ) {
  7925. _context.fillStyle = value;
  7926. _contextFillStyle = value;
  7927. }
  7928. }
  7929. };
  7930. /**
  7931. * @author alteredq / http://alteredqualia.com/
  7932. * @author mrdoob / http://mrdoob.com/
  7933. * @author mikael emtinger / http://gomo.se/
  7934. */
  7935. THREE.ShaderChunk = {
  7936. // FOG
  7937. fog_pars_fragment: [
  7938. "#ifdef USE_FOG",
  7939. "uniform vec3 fogColor;",
  7940. "#ifdef FOG_EXP2",
  7941. "uniform float fogDensity;",
  7942. "#else",
  7943. "uniform float fogNear;",
  7944. "uniform float fogFar;",
  7945. "#endif",
  7946. "#endif"
  7947. ].join("\n"),
  7948. fog_fragment: [
  7949. "#ifdef USE_FOG",
  7950. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  7951. "#ifdef FOG_EXP2",
  7952. "const float LOG2 = 1.442695;",
  7953. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  7954. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  7955. "#else",
  7956. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  7957. "#endif",
  7958. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  7959. "#endif"
  7960. ].join("\n"),
  7961. // ENVIRONMENT MAP
  7962. envmap_pars_fragment: [
  7963. "#ifdef USE_ENVMAP",
  7964. "uniform float reflectivity;",
  7965. "uniform samplerCube envMap;",
  7966. "uniform float flipEnvMap;",
  7967. "uniform int combine;",
  7968. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  7969. "uniform bool useRefract;",
  7970. "uniform float refractionRatio;",
  7971. "#else",
  7972. "varying vec3 vReflect;",
  7973. "#endif",
  7974. "#endif"
  7975. ].join("\n"),
  7976. envmap_fragment: [
  7977. "#ifdef USE_ENVMAP",
  7978. "vec3 reflectVec;",
  7979. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  7980. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  7981. "if ( useRefract ) {",
  7982. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  7983. "} else { ",
  7984. "reflectVec = reflect( cameraToVertex, normal );",
  7985. "}",
  7986. "#else",
  7987. "reflectVec = vReflect;",
  7988. "#endif",
  7989. "#ifdef DOUBLE_SIDED",
  7990. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  7991. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  7992. "#else",
  7993. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  7994. "#endif",
  7995. "#ifdef GAMMA_INPUT",
  7996. "cubeColor.xyz *= cubeColor.xyz;",
  7997. "#endif",
  7998. "if ( combine == 1 ) {",
  7999. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8000. "} else if ( combine == 2 ) {",
  8001. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8002. "} else {",
  8003. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8004. "}",
  8005. "#endif"
  8006. ].join("\n"),
  8007. envmap_pars_vertex: [
  8008. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8009. "varying vec3 vReflect;",
  8010. "uniform float refractionRatio;",
  8011. "uniform bool useRefract;",
  8012. "#endif"
  8013. ].join("\n"),
  8014. worldpos_vertex : [
  8015. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8016. "#ifdef USE_SKINNING",
  8017. "vec4 worldPosition = modelMatrix * skinned;",
  8018. "#endif",
  8019. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8020. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8021. "#endif",
  8022. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8023. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8024. "#endif",
  8025. "#endif"
  8026. ].join("\n"),
  8027. envmap_vertex : [
  8028. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8029. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8030. "worldNormal = normalize( worldNormal );",
  8031. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8032. "if ( useRefract ) {",
  8033. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8034. "} else {",
  8035. "vReflect = reflect( cameraToVertex, worldNormal );",
  8036. "}",
  8037. "#endif"
  8038. ].join("\n"),
  8039. // COLOR MAP (particles)
  8040. map_particle_pars_fragment: [
  8041. "#ifdef USE_MAP",
  8042. "uniform sampler2D map;",
  8043. "#endif"
  8044. ].join("\n"),
  8045. map_particle_fragment: [
  8046. "#ifdef USE_MAP",
  8047. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8048. "#endif"
  8049. ].join("\n"),
  8050. // COLOR MAP (triangles)
  8051. map_pars_vertex: [
  8052. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8053. "varying vec2 vUv;",
  8054. "uniform vec4 offsetRepeat;",
  8055. "#endif"
  8056. ].join("\n"),
  8057. map_pars_fragment: [
  8058. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8059. "varying vec2 vUv;",
  8060. "#endif",
  8061. "#ifdef USE_MAP",
  8062. "uniform sampler2D map;",
  8063. "#endif",
  8064. ].join("\n"),
  8065. map_vertex: [
  8066. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8067. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8068. "#endif"
  8069. ].join("\n"),
  8070. map_fragment: [
  8071. "#ifdef USE_MAP",
  8072. "#ifdef GAMMA_INPUT",
  8073. "vec4 texelColor = texture2D( map, vUv );",
  8074. "texelColor.xyz *= texelColor.xyz;",
  8075. "gl_FragColor = gl_FragColor * texelColor;",
  8076. "#else",
  8077. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  8078. "#endif",
  8079. "#endif"
  8080. ].join("\n"),
  8081. // LIGHT MAP
  8082. lightmap_pars_fragment: [
  8083. "#ifdef USE_LIGHTMAP",
  8084. "varying vec2 vUv2;",
  8085. "uniform sampler2D lightMap;",
  8086. "#endif"
  8087. ].join("\n"),
  8088. lightmap_pars_vertex: [
  8089. "#ifdef USE_LIGHTMAP",
  8090. "varying vec2 vUv2;",
  8091. "#endif"
  8092. ].join("\n"),
  8093. lightmap_fragment: [
  8094. "#ifdef USE_LIGHTMAP",
  8095. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8096. "#endif"
  8097. ].join("\n"),
  8098. lightmap_vertex: [
  8099. "#ifdef USE_LIGHTMAP",
  8100. "vUv2 = uv2;",
  8101. "#endif"
  8102. ].join("\n"),
  8103. // BUMP MAP
  8104. bumpmap_pars_fragment: [
  8105. "#ifdef USE_BUMPMAP",
  8106. "uniform sampler2D bumpMap;",
  8107. "uniform float bumpScale;",
  8108. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8109. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8110. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8111. "vec2 dHdxy_fwd() {",
  8112. "vec2 dSTdx = dFdx( vUv );",
  8113. "vec2 dSTdy = dFdy( vUv );",
  8114. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8115. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8116. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8117. "return vec2( dBx, dBy );",
  8118. "}",
  8119. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8120. "vec3 vSigmaX = dFdx( surf_pos );",
  8121. "vec3 vSigmaY = dFdy( surf_pos );",
  8122. "vec3 vN = surf_norm;", // normalized
  8123. "vec3 R1 = cross( vSigmaY, vN );",
  8124. "vec3 R2 = cross( vN, vSigmaX );",
  8125. "float fDet = dot( vSigmaX, R1 );",
  8126. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8127. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8128. "}",
  8129. "#endif"
  8130. ].join("\n"),
  8131. // NORMAL MAP
  8132. normalmap_pars_fragment: [
  8133. "#ifdef USE_NORMALMAP",
  8134. "uniform sampler2D normalMap;",
  8135. "uniform vec2 normalScale;",
  8136. // Per-Pixel Tangent Space Normal Mapping
  8137. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8138. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8139. "vec3 q0 = dFdx( eye_pos.xyz );",
  8140. "vec3 q1 = dFdy( eye_pos.xyz );",
  8141. "vec2 st0 = dFdx( vUv.st );",
  8142. "vec2 st1 = dFdy( vUv.st );",
  8143. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8144. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8145. "vec3 N = normalize( surf_norm );",
  8146. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8147. "mapN.xy = normalScale * mapN.xy;",
  8148. "mat3 tsn = mat3( S, T, N );",
  8149. "return normalize( tsn * mapN );",
  8150. "}",
  8151. "#endif"
  8152. ].join("\n"),
  8153. // SPECULAR MAP
  8154. specularmap_pars_fragment: [
  8155. "#ifdef USE_SPECULARMAP",
  8156. "uniform sampler2D specularMap;",
  8157. "#endif"
  8158. ].join("\n"),
  8159. specularmap_fragment: [
  8160. "float specularStrength;",
  8161. "#ifdef USE_SPECULARMAP",
  8162. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8163. "specularStrength = texelSpecular.r;",
  8164. "#else",
  8165. "specularStrength = 1.0;",
  8166. "#endif"
  8167. ].join("\n"),
  8168. // LIGHTS LAMBERT
  8169. lights_lambert_pars_vertex: [
  8170. "uniform vec3 ambient;",
  8171. "uniform vec3 diffuse;",
  8172. "uniform vec3 emissive;",
  8173. "uniform vec3 ambientLightColor;",
  8174. "#if MAX_DIR_LIGHTS > 0",
  8175. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8176. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8177. "#endif",
  8178. "#if MAX_HEMI_LIGHTS > 0",
  8179. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8180. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8181. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8182. "#endif",
  8183. "#if MAX_POINT_LIGHTS > 0",
  8184. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8185. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8186. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8187. "#endif",
  8188. "#if MAX_SPOT_LIGHTS > 0",
  8189. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8190. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8191. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8192. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8193. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8194. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8195. "#endif",
  8196. "#ifdef WRAP_AROUND",
  8197. "uniform vec3 wrapRGB;",
  8198. "#endif"
  8199. ].join("\n"),
  8200. lights_lambert_vertex: [
  8201. "vLightFront = vec3( 0.0 );",
  8202. "#ifdef DOUBLE_SIDED",
  8203. "vLightBack = vec3( 0.0 );",
  8204. "#endif",
  8205. "transformedNormal = normalize( transformedNormal );",
  8206. "#if MAX_DIR_LIGHTS > 0",
  8207. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8208. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8209. "vec3 dirVector = normalize( lDirection.xyz );",
  8210. "float dotProduct = dot( transformedNormal, dirVector );",
  8211. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8212. "#ifdef DOUBLE_SIDED",
  8213. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8214. "#ifdef WRAP_AROUND",
  8215. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8216. "#endif",
  8217. "#endif",
  8218. "#ifdef WRAP_AROUND",
  8219. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8220. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8221. "#ifdef DOUBLE_SIDED",
  8222. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8223. "#endif",
  8224. "#endif",
  8225. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8226. "#ifdef DOUBLE_SIDED",
  8227. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8228. "#endif",
  8229. "}",
  8230. "#endif",
  8231. "#if MAX_POINT_LIGHTS > 0",
  8232. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8233. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8234. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8235. "float lDistance = 1.0;",
  8236. "if ( pointLightDistance[ i ] > 0.0 )",
  8237. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8238. "lVector = normalize( lVector );",
  8239. "float dotProduct = dot( transformedNormal, lVector );",
  8240. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8241. "#ifdef DOUBLE_SIDED",
  8242. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8243. "#ifdef WRAP_AROUND",
  8244. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8245. "#endif",
  8246. "#endif",
  8247. "#ifdef WRAP_AROUND",
  8248. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8249. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8250. "#ifdef DOUBLE_SIDED",
  8251. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8252. "#endif",
  8253. "#endif",
  8254. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8255. "#ifdef DOUBLE_SIDED",
  8256. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8257. "#endif",
  8258. "}",
  8259. "#endif",
  8260. "#if MAX_SPOT_LIGHTS > 0",
  8261. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8262. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8263. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8264. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8265. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8266. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8267. "float lDistance = 1.0;",
  8268. "if ( spotLightDistance[ i ] > 0.0 )",
  8269. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8270. "lVector = normalize( lVector );",
  8271. "float dotProduct = dot( transformedNormal, lVector );",
  8272. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8273. "#ifdef DOUBLE_SIDED",
  8274. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8275. "#ifdef WRAP_AROUND",
  8276. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8277. "#endif",
  8278. "#endif",
  8279. "#ifdef WRAP_AROUND",
  8280. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8281. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8282. "#ifdef DOUBLE_SIDED",
  8283. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8284. "#endif",
  8285. "#endif",
  8286. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8287. "#ifdef DOUBLE_SIDED",
  8288. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8289. "#endif",
  8290. "}",
  8291. "}",
  8292. "#endif",
  8293. "#if MAX_HEMI_LIGHTS > 0",
  8294. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8295. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8296. "vec3 lVector = normalize( lDirection.xyz );",
  8297. "float dotProduct = dot( transformedNormal, lVector );",
  8298. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8299. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8300. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8301. "#ifdef DOUBLE_SIDED",
  8302. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8303. "#endif",
  8304. "}",
  8305. "#endif",
  8306. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8307. "#ifdef DOUBLE_SIDED",
  8308. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8309. "#endif"
  8310. ].join("\n"),
  8311. // LIGHTS PHONG
  8312. lights_phong_pars_vertex: [
  8313. "#ifndef PHONG_PER_PIXEL",
  8314. "#if MAX_POINT_LIGHTS > 0",
  8315. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8316. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8317. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8318. "#endif",
  8319. "#if MAX_SPOT_LIGHTS > 0",
  8320. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8321. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8322. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8323. "#endif",
  8324. "#endif",
  8325. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8326. "varying vec3 vWorldPosition;",
  8327. "#endif"
  8328. ].join("\n"),
  8329. lights_phong_vertex: [
  8330. "#ifndef PHONG_PER_PIXEL",
  8331. "#if MAX_POINT_LIGHTS > 0",
  8332. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8333. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8334. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8335. "float lDistance = 1.0;",
  8336. "if ( pointLightDistance[ i ] > 0.0 )",
  8337. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8338. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8339. "}",
  8340. "#endif",
  8341. "#if MAX_SPOT_LIGHTS > 0",
  8342. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8343. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8344. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8345. "float lDistance = 1.0;",
  8346. "if ( spotLightDistance[ i ] > 0.0 )",
  8347. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8348. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8349. "}",
  8350. "#endif",
  8351. "#endif",
  8352. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8353. "vWorldPosition = worldPosition.xyz;",
  8354. "#endif"
  8355. ].join("\n"),
  8356. lights_phong_pars_fragment: [
  8357. "uniform vec3 ambientLightColor;",
  8358. "#if MAX_DIR_LIGHTS > 0",
  8359. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8360. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8361. "#endif",
  8362. "#if MAX_HEMI_LIGHTS > 0",
  8363. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8364. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8365. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8366. "#endif",
  8367. "#if MAX_POINT_LIGHTS > 0",
  8368. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8369. "#ifdef PHONG_PER_PIXEL",
  8370. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8371. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8372. "#else",
  8373. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8374. "#endif",
  8375. "#endif",
  8376. "#if MAX_SPOT_LIGHTS > 0",
  8377. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8378. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8379. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8380. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8381. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8382. "#ifdef PHONG_PER_PIXEL",
  8383. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8384. "#else",
  8385. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8386. "#endif",
  8387. "#endif",
  8388. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8389. "varying vec3 vWorldPosition;",
  8390. "#endif",
  8391. "#ifdef WRAP_AROUND",
  8392. "uniform vec3 wrapRGB;",
  8393. "#endif",
  8394. "varying vec3 vViewPosition;",
  8395. "varying vec3 vNormal;"
  8396. ].join("\n"),
  8397. lights_phong_fragment: [
  8398. "vec3 normal = normalize( vNormal );",
  8399. "vec3 viewPosition = normalize( vViewPosition );",
  8400. "#ifdef DOUBLE_SIDED",
  8401. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8402. "#endif",
  8403. "#ifdef USE_NORMALMAP",
  8404. "normal = perturbNormal2Arb( -viewPosition, normal );",
  8405. "#elif defined( USE_BUMPMAP )",
  8406. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8407. "#endif",
  8408. "#if MAX_POINT_LIGHTS > 0",
  8409. "vec3 pointDiffuse = vec3( 0.0 );",
  8410. "vec3 pointSpecular = vec3( 0.0 );",
  8411. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8412. "#ifdef PHONG_PER_PIXEL",
  8413. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8414. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8415. "float lDistance = 1.0;",
  8416. "if ( pointLightDistance[ i ] > 0.0 )",
  8417. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8418. "lVector = normalize( lVector );",
  8419. "#else",
  8420. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8421. "float lDistance = vPointLight[ i ].w;",
  8422. "#endif",
  8423. // diffuse
  8424. "float dotProduct = dot( normal, lVector );",
  8425. "#ifdef WRAP_AROUND",
  8426. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8427. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8428. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8429. "#else",
  8430. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8431. "#endif",
  8432. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8433. // specular
  8434. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8435. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8436. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8437. "#ifdef PHYSICALLY_BASED_SHADING",
  8438. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8439. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8440. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8441. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8442. "#else",
  8443. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8444. "#endif",
  8445. "}",
  8446. "#endif",
  8447. "#if MAX_SPOT_LIGHTS > 0",
  8448. "vec3 spotDiffuse = vec3( 0.0 );",
  8449. "vec3 spotSpecular = vec3( 0.0 );",
  8450. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8451. "#ifdef PHONG_PER_PIXEL",
  8452. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8453. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8454. "float lDistance = 1.0;",
  8455. "if ( spotLightDistance[ i ] > 0.0 )",
  8456. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8457. "lVector = normalize( lVector );",
  8458. "#else",
  8459. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8460. "float lDistance = vSpotLight[ i ].w;",
  8461. "#endif",
  8462. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8463. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8464. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8465. // diffuse
  8466. "float dotProduct = dot( normal, lVector );",
  8467. "#ifdef WRAP_AROUND",
  8468. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8469. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8470. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8471. "#else",
  8472. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8473. "#endif",
  8474. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8475. // specular
  8476. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8477. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8478. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8479. "#ifdef PHYSICALLY_BASED_SHADING",
  8480. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8481. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8482. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8483. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8484. "#else",
  8485. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8486. "#endif",
  8487. "}",
  8488. "}",
  8489. "#endif",
  8490. "#if MAX_DIR_LIGHTS > 0",
  8491. "vec3 dirDiffuse = vec3( 0.0 );",
  8492. "vec3 dirSpecular = vec3( 0.0 );" ,
  8493. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8494. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8495. "vec3 dirVector = normalize( lDirection.xyz );",
  8496. // diffuse
  8497. "float dotProduct = dot( normal, dirVector );",
  8498. "#ifdef WRAP_AROUND",
  8499. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8500. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8501. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8502. "#else",
  8503. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8504. "#endif",
  8505. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8506. // specular
  8507. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8508. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8509. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8510. "#ifdef PHYSICALLY_BASED_SHADING",
  8511. /*
  8512. // fresnel term from skin shader
  8513. "const float F0 = 0.128;",
  8514. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8515. "float exponential = pow( base, 5.0 );",
  8516. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8517. */
  8518. /*
  8519. // fresnel term from fresnel shader
  8520. "const float mFresnelBias = 0.08;",
  8521. "const float mFresnelScale = 0.3;",
  8522. "const float mFresnelPower = 5.0;",
  8523. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8524. */
  8525. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8526. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8527. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8528. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8529. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8530. "#else",
  8531. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8532. "#endif",
  8533. "}",
  8534. "#endif",
  8535. "#if MAX_HEMI_LIGHTS > 0",
  8536. "vec3 hemiDiffuse = vec3( 0.0 );",
  8537. "vec3 hemiSpecular = vec3( 0.0 );" ,
  8538. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8539. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8540. "vec3 lVector = normalize( lDirection.xyz );",
  8541. // diffuse
  8542. "float dotProduct = dot( normal, lVector );",
  8543. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8544. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8545. "hemiDiffuse += diffuse * hemiColor;",
  8546. // specular (sky light)
  8547. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  8548. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  8549. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  8550. // specular (ground light)
  8551. "vec3 lVectorGround = -lVector;",
  8552. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  8553. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  8554. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  8555. "#ifdef PHYSICALLY_BASED_SHADING",
  8556. "float dotProductGround = dot( normal, lVectorGround );",
  8557. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8558. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8559. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  8560. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  8561. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  8562. "#else",
  8563. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  8564. "#endif",
  8565. "}",
  8566. "#endif",
  8567. "vec3 totalDiffuse = vec3( 0.0 );",
  8568. "vec3 totalSpecular = vec3( 0.0 );",
  8569. "#if MAX_DIR_LIGHTS > 0",
  8570. "totalDiffuse += dirDiffuse;",
  8571. "totalSpecular += dirSpecular;",
  8572. "#endif",
  8573. "#if MAX_HEMI_LIGHTS > 0",
  8574. "totalDiffuse += hemiDiffuse;",
  8575. "totalSpecular += hemiSpecular;",
  8576. "#endif",
  8577. "#if MAX_POINT_LIGHTS > 0",
  8578. "totalDiffuse += pointDiffuse;",
  8579. "totalSpecular += pointSpecular;",
  8580. "#endif",
  8581. "#if MAX_SPOT_LIGHTS > 0",
  8582. "totalDiffuse += spotDiffuse;",
  8583. "totalSpecular += spotSpecular;",
  8584. "#endif",
  8585. "#ifdef METAL",
  8586. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8587. "#else",
  8588. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8589. "#endif"
  8590. ].join("\n"),
  8591. // VERTEX COLORS
  8592. color_pars_fragment: [
  8593. "#ifdef USE_COLOR",
  8594. "varying vec3 vColor;",
  8595. "#endif"
  8596. ].join("\n"),
  8597. color_fragment: [
  8598. "#ifdef USE_COLOR",
  8599. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8600. "#endif"
  8601. ].join("\n"),
  8602. color_pars_vertex: [
  8603. "#ifdef USE_COLOR",
  8604. "varying vec3 vColor;",
  8605. "#endif"
  8606. ].join("\n"),
  8607. color_vertex: [
  8608. "#ifdef USE_COLOR",
  8609. "#ifdef GAMMA_INPUT",
  8610. "vColor = color * color;",
  8611. "#else",
  8612. "vColor = color;",
  8613. "#endif",
  8614. "#endif"
  8615. ].join("\n"),
  8616. // SKINNING
  8617. skinning_pars_vertex: [
  8618. "#ifdef USE_SKINNING",
  8619. "#ifdef BONE_TEXTURE",
  8620. "uniform sampler2D boneTexture;",
  8621. "mat4 getBoneMatrix( const in float i ) {",
  8622. "float j = i * 4.0;",
  8623. "float x = mod( j, N_BONE_PIXEL_X );",
  8624. "float y = floor( j / N_BONE_PIXEL_X );",
  8625. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8626. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8627. "y = dy * ( y + 0.5 );",
  8628. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8629. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8630. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8631. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8632. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8633. "return bone;",
  8634. "}",
  8635. "#else",
  8636. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8637. "mat4 getBoneMatrix( const in float i ) {",
  8638. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8639. "return bone;",
  8640. "}",
  8641. "#endif",
  8642. "#endif"
  8643. ].join("\n"),
  8644. skinbase_vertex: [
  8645. "#ifdef USE_SKINNING",
  8646. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8647. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8648. "#endif"
  8649. ].join("\n"),
  8650. skinning_vertex: [
  8651. "#ifdef USE_SKINNING",
  8652. "#ifdef USE_MORPHTARGETS",
  8653. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8654. "#else",
  8655. "vec4 skinVertex = vec4( position, 1.0 );",
  8656. "#endif",
  8657. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8658. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8659. "#endif"
  8660. ].join("\n"),
  8661. // MORPHING
  8662. morphtarget_pars_vertex: [
  8663. "#ifdef USE_MORPHTARGETS",
  8664. "#ifndef USE_MORPHNORMALS",
  8665. "uniform float morphTargetInfluences[ 8 ];",
  8666. "#else",
  8667. "uniform float morphTargetInfluences[ 4 ];",
  8668. "#endif",
  8669. "#endif"
  8670. ].join("\n"),
  8671. morphtarget_vertex: [
  8672. "#ifdef USE_MORPHTARGETS",
  8673. "vec3 morphed = vec3( 0.0 );",
  8674. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8675. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8676. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8677. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8678. "#ifndef USE_MORPHNORMALS",
  8679. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8680. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8681. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8682. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8683. "#endif",
  8684. "morphed += position;",
  8685. "#endif"
  8686. ].join("\n"),
  8687. default_vertex : [
  8688. "vec4 mvPosition;",
  8689. "#ifdef USE_SKINNING",
  8690. "mvPosition = modelViewMatrix * skinned;",
  8691. "#endif",
  8692. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  8693. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  8694. "#endif",
  8695. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  8696. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8697. "#endif",
  8698. "gl_Position = projectionMatrix * mvPosition;",
  8699. ].join("\n"),
  8700. morphnormal_vertex: [
  8701. "#ifdef USE_MORPHNORMALS",
  8702. "vec3 morphedNormal = vec3( 0.0 );",
  8703. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8704. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8705. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8706. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8707. "morphedNormal += normal;",
  8708. "#endif"
  8709. ].join("\n"),
  8710. skinnormal_vertex: [
  8711. "#ifdef USE_SKINNING",
  8712. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8713. "skinMatrix += skinWeight.y * boneMatY;",
  8714. "#ifdef USE_MORPHNORMALS",
  8715. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8716. "#else",
  8717. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8718. "#endif",
  8719. "#endif"
  8720. ].join("\n"),
  8721. defaultnormal_vertex: [
  8722. "vec3 objectNormal;",
  8723. "#ifdef USE_SKINNING",
  8724. "objectNormal = skinnedNormal.xyz;",
  8725. "#endif",
  8726. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  8727. "objectNormal = morphedNormal;",
  8728. "#endif",
  8729. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  8730. "objectNormal = normal;",
  8731. "#endif",
  8732. "#ifdef FLIP_SIDED",
  8733. "objectNormal = -objectNormal;",
  8734. "#endif",
  8735. "vec3 transformedNormal = normalMatrix * objectNormal;",
  8736. ].join("\n"),
  8737. // SHADOW MAP
  8738. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8739. // http://spidergl.org/example.php?id=6
  8740. // http://fabiensanglard.net/shadowmapping
  8741. shadowmap_pars_fragment: [
  8742. "#ifdef USE_SHADOWMAP",
  8743. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8744. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8745. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8746. "uniform float shadowBias[ MAX_SHADOWS ];",
  8747. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8748. "float unpackDepth( const in vec4 rgba_depth ) {",
  8749. "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 );",
  8750. "float depth = dot( rgba_depth, bit_shift );",
  8751. "return depth;",
  8752. "}",
  8753. "#endif"
  8754. ].join("\n"),
  8755. shadowmap_fragment: [
  8756. "#ifdef USE_SHADOWMAP",
  8757. "#ifdef SHADOWMAP_DEBUG",
  8758. "vec3 frustumColors[3];",
  8759. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8760. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8761. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8762. "#endif",
  8763. "#ifdef SHADOWMAP_CASCADE",
  8764. "int inFrustumCount = 0;",
  8765. "#endif",
  8766. "float fDepth;",
  8767. "vec3 shadowColor = vec3( 1.0 );",
  8768. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8769. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8770. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8771. // "if ( all( something, something ) )" using this instead
  8772. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8773. "bool inFrustum = all( inFrustumVec );",
  8774. // don't shadow pixels outside of light frustum
  8775. // use just first frustum (for cascades)
  8776. // don't shadow pixels behind far plane of light frustum
  8777. "#ifdef SHADOWMAP_CASCADE",
  8778. "inFrustumCount += int( inFrustum );",
  8779. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8780. "#else",
  8781. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8782. "#endif",
  8783. "bool frustumTest = all( frustumTestVec );",
  8784. "if ( frustumTest ) {",
  8785. "shadowCoord.z += shadowBias[ i ];",
  8786. "#ifdef SHADOWMAP_SOFT",
  8787. // Percentage-close filtering
  8788. // (9 pixel kernel)
  8789. // http://fabiensanglard.net/shadowmappingPCF/
  8790. "float shadow = 0.0;",
  8791. /*
  8792. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8793. // must enroll loop manually
  8794. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8795. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8796. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8797. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8798. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8799. "float fDepth = unpackDepth( rgbaDepth );",
  8800. "if ( fDepth < shadowCoord.z )",
  8801. "shadow += 1.0;",
  8802. "}",
  8803. "shadow /= 9.0;",
  8804. */
  8805. "const float shadowDelta = 1.0 / 9.0;",
  8806. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8807. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8808. "float dx0 = -1.25 * xPixelOffset;",
  8809. "float dy0 = -1.25 * yPixelOffset;",
  8810. "float dx1 = 1.25 * xPixelOffset;",
  8811. "float dy1 = 1.25 * yPixelOffset;",
  8812. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8813. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8814. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8815. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8816. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8817. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8818. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8819. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8820. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8821. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8822. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8823. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8824. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8825. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8826. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8827. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8828. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8829. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8830. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8831. "#else",
  8832. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8833. "float fDepth = unpackDepth( rgbaDepth );",
  8834. "if ( fDepth < shadowCoord.z )",
  8835. // spot with multiple shadows is darker
  8836. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8837. // spot with multiple shadows has the same color as single shadow spot
  8838. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8839. "#endif",
  8840. "}",
  8841. "#ifdef SHADOWMAP_DEBUG",
  8842. "#ifdef SHADOWMAP_CASCADE",
  8843. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8844. "#else",
  8845. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8846. "#endif",
  8847. "#endif",
  8848. "}",
  8849. "#ifdef GAMMA_OUTPUT",
  8850. "shadowColor *= shadowColor;",
  8851. "#endif",
  8852. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8853. "#endif"
  8854. ].join("\n"),
  8855. shadowmap_pars_vertex: [
  8856. "#ifdef USE_SHADOWMAP",
  8857. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8858. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8859. "#endif"
  8860. ].join("\n"),
  8861. shadowmap_vertex: [
  8862. "#ifdef USE_SHADOWMAP",
  8863. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8864. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  8865. "}",
  8866. "#endif"
  8867. ].join("\n"),
  8868. // ALPHATEST
  8869. alphatest_fragment: [
  8870. "#ifdef ALPHATEST",
  8871. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8872. "#endif"
  8873. ].join("\n"),
  8874. // LINEAR SPACE
  8875. linear_to_gamma_fragment: [
  8876. "#ifdef GAMMA_OUTPUT",
  8877. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8878. "#endif"
  8879. ].join("\n"),
  8880. };
  8881. THREE.UniformsUtils = {
  8882. merge: function ( uniforms ) {
  8883. var u, p, tmp, merged = {};
  8884. for ( u = 0; u < uniforms.length; u ++ ) {
  8885. tmp = this.clone( uniforms[ u ] );
  8886. for ( p in tmp ) {
  8887. merged[ p ] = tmp[ p ];
  8888. }
  8889. }
  8890. return merged;
  8891. },
  8892. clone: function ( uniforms_src ) {
  8893. var u, p, parameter, parameter_src, uniforms_dst = {};
  8894. for ( u in uniforms_src ) {
  8895. uniforms_dst[ u ] = {};
  8896. for ( p in uniforms_src[ u ] ) {
  8897. parameter_src = uniforms_src[ u ][ p ];
  8898. if ( parameter_src instanceof THREE.Color ||
  8899. parameter_src instanceof THREE.Vector2 ||
  8900. parameter_src instanceof THREE.Vector3 ||
  8901. parameter_src instanceof THREE.Vector4 ||
  8902. parameter_src instanceof THREE.Matrix4 ||
  8903. parameter_src instanceof THREE.Texture ) {
  8904. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8905. } else if ( parameter_src instanceof Array ) {
  8906. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8907. } else {
  8908. uniforms_dst[ u ][ p ] = parameter_src;
  8909. }
  8910. }
  8911. }
  8912. return uniforms_dst;
  8913. }
  8914. };
  8915. THREE.UniformsLib = {
  8916. common: {
  8917. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8918. "opacity" : { type: "f", value: 1.0 },
  8919. "map" : { type: "t", value: null },
  8920. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  8921. "lightMap" : { type: "t", value: null },
  8922. "specularMap" : { type: "t", value: null },
  8923. "envMap" : { type: "t", value: null },
  8924. "flipEnvMap" : { type: "f", value: -1 },
  8925. "useRefract" : { type: "i", value: 0 },
  8926. "reflectivity" : { type: "f", value: 1.0 },
  8927. "refractionRatio" : { type: "f", value: 0.98 },
  8928. "combine" : { type: "i", value: 0 },
  8929. "morphTargetInfluences" : { type: "f", value: 0 }
  8930. },
  8931. bump: {
  8932. "bumpMap" : { type: "t", value: null },
  8933. "bumpScale" : { type: "f", value: 1 }
  8934. },
  8935. normalmap: {
  8936. "normalMap" : { type: "t", value: null },
  8937. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  8938. },
  8939. fog : {
  8940. "fogDensity" : { type: "f", value: 0.00025 },
  8941. "fogNear" : { type: "f", value: 1 },
  8942. "fogFar" : { type: "f", value: 2000 },
  8943. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8944. },
  8945. lights: {
  8946. "ambientLightColor" : { type: "fv", value: [] },
  8947. "directionalLightDirection" : { type: "fv", value: [] },
  8948. "directionalLightColor" : { type: "fv", value: [] },
  8949. "hemisphereLightDirection" : { type: "fv", value: [] },
  8950. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  8951. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  8952. "pointLightColor" : { type: "fv", value: [] },
  8953. "pointLightPosition" : { type: "fv", value: [] },
  8954. "pointLightDistance" : { type: "fv1", value: [] },
  8955. "spotLightColor" : { type: "fv", value: [] },
  8956. "spotLightPosition" : { type: "fv", value: [] },
  8957. "spotLightDirection" : { type: "fv", value: [] },
  8958. "spotLightDistance" : { type: "fv1", value: [] },
  8959. "spotLightAngleCos" : { type: "fv1", value: [] },
  8960. "spotLightExponent" : { type: "fv1", value: [] }
  8961. },
  8962. particle: {
  8963. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8964. "opacity" : { type: "f", value: 1.0 },
  8965. "size" : { type: "f", value: 1.0 },
  8966. "scale" : { type: "f", value: 1.0 },
  8967. "map" : { type: "t", value: null },
  8968. "fogDensity" : { type: "f", value: 0.00025 },
  8969. "fogNear" : { type: "f", value: 1 },
  8970. "fogFar" : { type: "f", value: 2000 },
  8971. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8972. },
  8973. shadowmap: {
  8974. "shadowMap": { type: "tv", value: [] },
  8975. "shadowMapSize": { type: "v2v", value: [] },
  8976. "shadowBias" : { type: "fv1", value: [] },
  8977. "shadowDarkness": { type: "fv1", value: [] },
  8978. "shadowMatrix" : { type: "m4v", value: [] },
  8979. }
  8980. };
  8981. THREE.ShaderLib = {
  8982. 'depth': {
  8983. uniforms: {
  8984. "mNear": { type: "f", value: 1.0 },
  8985. "mFar" : { type: "f", value: 2000.0 },
  8986. "opacity" : { type: "f", value: 1.0 }
  8987. },
  8988. vertexShader: [
  8989. "void main() {",
  8990. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  8991. "}"
  8992. ].join("\n"),
  8993. fragmentShader: [
  8994. "uniform float mNear;",
  8995. "uniform float mFar;",
  8996. "uniform float opacity;",
  8997. "void main() {",
  8998. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8999. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9000. "gl_FragColor = vec4( vec3( color ), opacity );",
  9001. "}"
  9002. ].join("\n")
  9003. },
  9004. 'normal': {
  9005. uniforms: {
  9006. "opacity" : { type: "f", value: 1.0 }
  9007. },
  9008. vertexShader: [
  9009. "varying vec3 vNormal;",
  9010. "void main() {",
  9011. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9012. "vNormal = normalize( normalMatrix * normal );",
  9013. "gl_Position = projectionMatrix * mvPosition;",
  9014. "}"
  9015. ].join("\n"),
  9016. fragmentShader: [
  9017. "uniform float opacity;",
  9018. "varying vec3 vNormal;",
  9019. "void main() {",
  9020. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9021. "}"
  9022. ].join("\n")
  9023. },
  9024. 'basic': {
  9025. uniforms: THREE.UniformsUtils.merge( [
  9026. THREE.UniformsLib[ "common" ],
  9027. THREE.UniformsLib[ "fog" ],
  9028. THREE.UniformsLib[ "shadowmap" ]
  9029. ] ),
  9030. vertexShader: [
  9031. THREE.ShaderChunk[ "map_pars_vertex" ],
  9032. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9033. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9034. THREE.ShaderChunk[ "color_pars_vertex" ],
  9035. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9036. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9037. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9038. "void main() {",
  9039. THREE.ShaderChunk[ "map_vertex" ],
  9040. THREE.ShaderChunk[ "lightmap_vertex" ],
  9041. THREE.ShaderChunk[ "color_vertex" ],
  9042. "#ifdef USE_ENVMAP",
  9043. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9044. THREE.ShaderChunk[ "skinbase_vertex" ],
  9045. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9046. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9047. "#endif",
  9048. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9049. THREE.ShaderChunk[ "skinning_vertex" ],
  9050. THREE.ShaderChunk[ "default_vertex" ],
  9051. THREE.ShaderChunk[ "worldpos_vertex" ],
  9052. THREE.ShaderChunk[ "envmap_vertex" ],
  9053. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9054. "}"
  9055. ].join("\n"),
  9056. fragmentShader: [
  9057. "uniform vec3 diffuse;",
  9058. "uniform float opacity;",
  9059. THREE.ShaderChunk[ "color_pars_fragment" ],
  9060. THREE.ShaderChunk[ "map_pars_fragment" ],
  9061. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9062. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9063. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9064. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9065. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9066. "void main() {",
  9067. "gl_FragColor = vec4( diffuse, opacity );",
  9068. THREE.ShaderChunk[ "map_fragment" ],
  9069. THREE.ShaderChunk[ "alphatest_fragment" ],
  9070. THREE.ShaderChunk[ "specularmap_fragment" ],
  9071. THREE.ShaderChunk[ "lightmap_fragment" ],
  9072. THREE.ShaderChunk[ "color_fragment" ],
  9073. THREE.ShaderChunk[ "envmap_fragment" ],
  9074. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9075. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9076. THREE.ShaderChunk[ "fog_fragment" ],
  9077. "}"
  9078. ].join("\n")
  9079. },
  9080. 'lambert': {
  9081. uniforms: THREE.UniformsUtils.merge( [
  9082. THREE.UniformsLib[ "common" ],
  9083. THREE.UniformsLib[ "fog" ],
  9084. THREE.UniformsLib[ "lights" ],
  9085. THREE.UniformsLib[ "shadowmap" ],
  9086. {
  9087. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9088. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9089. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9090. }
  9091. ] ),
  9092. vertexShader: [
  9093. "#define LAMBERT",
  9094. "varying vec3 vLightFront;",
  9095. "#ifdef DOUBLE_SIDED",
  9096. "varying vec3 vLightBack;",
  9097. "#endif",
  9098. THREE.ShaderChunk[ "map_pars_vertex" ],
  9099. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9100. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9101. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9102. THREE.ShaderChunk[ "color_pars_vertex" ],
  9103. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9104. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9105. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9106. "void main() {",
  9107. THREE.ShaderChunk[ "map_vertex" ],
  9108. THREE.ShaderChunk[ "lightmap_vertex" ],
  9109. THREE.ShaderChunk[ "color_vertex" ],
  9110. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9111. THREE.ShaderChunk[ "skinbase_vertex" ],
  9112. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9113. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9114. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9115. THREE.ShaderChunk[ "skinning_vertex" ],
  9116. THREE.ShaderChunk[ "default_vertex" ],
  9117. THREE.ShaderChunk[ "worldpos_vertex" ],
  9118. THREE.ShaderChunk[ "envmap_vertex" ],
  9119. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9120. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9121. "}"
  9122. ].join("\n"),
  9123. fragmentShader: [
  9124. "uniform float opacity;",
  9125. "varying vec3 vLightFront;",
  9126. "#ifdef DOUBLE_SIDED",
  9127. "varying vec3 vLightBack;",
  9128. "#endif",
  9129. THREE.ShaderChunk[ "color_pars_fragment" ],
  9130. THREE.ShaderChunk[ "map_pars_fragment" ],
  9131. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9132. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9133. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9134. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9135. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9136. "void main() {",
  9137. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9138. THREE.ShaderChunk[ "map_fragment" ],
  9139. THREE.ShaderChunk[ "alphatest_fragment" ],
  9140. THREE.ShaderChunk[ "specularmap_fragment" ],
  9141. "#ifdef DOUBLE_SIDED",
  9142. //"float isFront = float( gl_FrontFacing );",
  9143. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9144. "if ( gl_FrontFacing )",
  9145. "gl_FragColor.xyz *= vLightFront;",
  9146. "else",
  9147. "gl_FragColor.xyz *= vLightBack;",
  9148. "#else",
  9149. "gl_FragColor.xyz *= vLightFront;",
  9150. "#endif",
  9151. THREE.ShaderChunk[ "lightmap_fragment" ],
  9152. THREE.ShaderChunk[ "color_fragment" ],
  9153. THREE.ShaderChunk[ "envmap_fragment" ],
  9154. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9155. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9156. THREE.ShaderChunk[ "fog_fragment" ],
  9157. "}"
  9158. ].join("\n")
  9159. },
  9160. 'phong': {
  9161. uniforms: THREE.UniformsUtils.merge( [
  9162. THREE.UniformsLib[ "common" ],
  9163. THREE.UniformsLib[ "bump" ],
  9164. THREE.UniformsLib[ "normalmap" ],
  9165. THREE.UniformsLib[ "fog" ],
  9166. THREE.UniformsLib[ "lights" ],
  9167. THREE.UniformsLib[ "shadowmap" ],
  9168. {
  9169. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9170. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9171. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9172. "shininess": { type: "f", value: 30 },
  9173. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9174. }
  9175. ] ),
  9176. vertexShader: [
  9177. "#define PHONG",
  9178. "varying vec3 vViewPosition;",
  9179. "varying vec3 vNormal;",
  9180. THREE.ShaderChunk[ "map_pars_vertex" ],
  9181. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9182. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9183. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9184. THREE.ShaderChunk[ "color_pars_vertex" ],
  9185. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9186. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9187. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9188. "void main() {",
  9189. THREE.ShaderChunk[ "map_vertex" ],
  9190. THREE.ShaderChunk[ "lightmap_vertex" ],
  9191. THREE.ShaderChunk[ "color_vertex" ],
  9192. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9193. THREE.ShaderChunk[ "skinbase_vertex" ],
  9194. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9195. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9196. "vNormal = normalize( transformedNormal );",
  9197. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9198. THREE.ShaderChunk[ "skinning_vertex" ],
  9199. THREE.ShaderChunk[ "default_vertex" ],
  9200. "vViewPosition = -mvPosition.xyz;",
  9201. THREE.ShaderChunk[ "worldpos_vertex" ],
  9202. THREE.ShaderChunk[ "envmap_vertex" ],
  9203. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9204. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9205. "}"
  9206. ].join("\n"),
  9207. fragmentShader: [
  9208. "uniform vec3 diffuse;",
  9209. "uniform float opacity;",
  9210. "uniform vec3 ambient;",
  9211. "uniform vec3 emissive;",
  9212. "uniform vec3 specular;",
  9213. "uniform float shininess;",
  9214. THREE.ShaderChunk[ "color_pars_fragment" ],
  9215. THREE.ShaderChunk[ "map_pars_fragment" ],
  9216. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9217. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9218. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9219. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9220. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9221. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9222. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9223. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9224. "void main() {",
  9225. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9226. THREE.ShaderChunk[ "map_fragment" ],
  9227. THREE.ShaderChunk[ "alphatest_fragment" ],
  9228. THREE.ShaderChunk[ "specularmap_fragment" ],
  9229. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9230. THREE.ShaderChunk[ "lightmap_fragment" ],
  9231. THREE.ShaderChunk[ "color_fragment" ],
  9232. THREE.ShaderChunk[ "envmap_fragment" ],
  9233. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9234. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9235. THREE.ShaderChunk[ "fog_fragment" ],
  9236. "}"
  9237. ].join("\n")
  9238. },
  9239. 'particle_basic': {
  9240. uniforms: THREE.UniformsUtils.merge( [
  9241. THREE.UniformsLib[ "particle" ],
  9242. THREE.UniformsLib[ "shadowmap" ]
  9243. ] ),
  9244. vertexShader: [
  9245. "uniform float size;",
  9246. "uniform float scale;",
  9247. THREE.ShaderChunk[ "color_pars_vertex" ],
  9248. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9249. "void main() {",
  9250. THREE.ShaderChunk[ "color_vertex" ],
  9251. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9252. "#ifdef USE_SIZEATTENUATION",
  9253. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9254. "#else",
  9255. "gl_PointSize = size;",
  9256. "#endif",
  9257. "gl_Position = projectionMatrix * mvPosition;",
  9258. THREE.ShaderChunk[ "worldpos_vertex" ],
  9259. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9260. "}"
  9261. ].join("\n"),
  9262. fragmentShader: [
  9263. "uniform vec3 psColor;",
  9264. "uniform float opacity;",
  9265. THREE.ShaderChunk[ "color_pars_fragment" ],
  9266. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9267. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9268. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9269. "void main() {",
  9270. "gl_FragColor = vec4( psColor, opacity );",
  9271. THREE.ShaderChunk[ "map_particle_fragment" ],
  9272. THREE.ShaderChunk[ "alphatest_fragment" ],
  9273. THREE.ShaderChunk[ "color_fragment" ],
  9274. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9275. THREE.ShaderChunk[ "fog_fragment" ],
  9276. "}"
  9277. ].join("\n")
  9278. },
  9279. 'dashed': {
  9280. uniforms: THREE.UniformsUtils.merge( [
  9281. THREE.UniformsLib[ "common" ],
  9282. THREE.UniformsLib[ "fog" ],
  9283. {
  9284. "scale": { type: "f", value: 1 },
  9285. "dashSize": { type: "f", value: 1 },
  9286. "totalSize": { type: "f", value: 2 }
  9287. }
  9288. ] ),
  9289. vertexShader: [
  9290. "uniform float scale;",
  9291. "attribute float lineDistance;",
  9292. "varying float vLineDistance;",
  9293. THREE.ShaderChunk[ "color_pars_vertex" ],
  9294. "void main() {",
  9295. THREE.ShaderChunk[ "color_vertex" ],
  9296. "vLineDistance = scale * lineDistance;",
  9297. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9298. "gl_Position = projectionMatrix * mvPosition;",
  9299. "}"
  9300. ].join("\n"),
  9301. fragmentShader: [
  9302. "uniform vec3 diffuse;",
  9303. "uniform float opacity;",
  9304. "uniform float dashSize;",
  9305. "uniform float totalSize;",
  9306. "varying float vLineDistance;",
  9307. THREE.ShaderChunk[ "color_pars_fragment" ],
  9308. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9309. "void main() {",
  9310. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  9311. "discard;",
  9312. "}",
  9313. "gl_FragColor = vec4( diffuse, opacity );",
  9314. THREE.ShaderChunk[ "color_fragment" ],
  9315. THREE.ShaderChunk[ "fog_fragment" ],
  9316. "}"
  9317. ].join("\n")
  9318. },
  9319. // Depth encoding into RGBA texture
  9320. // based on SpiderGL shadow map example
  9321. // http://spidergl.org/example.php?id=6
  9322. // originally from
  9323. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  9324. // see also here:
  9325. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  9326. 'depthRGBA': {
  9327. uniforms: {},
  9328. vertexShader: [
  9329. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9330. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9331. "void main() {",
  9332. THREE.ShaderChunk[ "skinbase_vertex" ],
  9333. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9334. THREE.ShaderChunk[ "skinning_vertex" ],
  9335. THREE.ShaderChunk[ "default_vertex" ],
  9336. "}"
  9337. ].join("\n"),
  9338. fragmentShader: [
  9339. "vec4 pack_depth( const in float depth ) {",
  9340. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  9341. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  9342. "vec4 res = fract( depth * bit_shift );",
  9343. "res -= res.xxyz * bit_mask;",
  9344. "return res;",
  9345. "}",
  9346. "void main() {",
  9347. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  9348. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  9349. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  9350. //"gl_FragData[ 0 ] = pack_depth( z );",
  9351. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  9352. "}"
  9353. ].join("\n")
  9354. }
  9355. };
  9356. /**
  9357. * @author supereggbert / http://www.paulbrunt.co.uk/
  9358. * @author mrdoob / http://mrdoob.com/
  9359. * @author alteredq / http://alteredqualia.com/
  9360. * @author szimek / https://github.com/szimek/
  9361. */
  9362. THREE.WebGLRenderer = function ( parameters ) {
  9363. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9364. parameters = parameters || {};
  9365. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  9366. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  9367. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  9368. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  9369. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  9370. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  9371. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  9372. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  9373. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  9374. // public properties
  9375. this.domElement = _canvas;
  9376. this.context = null;
  9377. // clearing
  9378. this.autoClear = true;
  9379. this.autoClearColor = true;
  9380. this.autoClearDepth = true;
  9381. this.autoClearStencil = true;
  9382. // scene graph
  9383. this.sortObjects = true;
  9384. this.autoUpdateObjects = true;
  9385. this.autoUpdateScene = true;
  9386. // physically based shading
  9387. this.gammaInput = false;
  9388. this.gammaOutput = false;
  9389. this.physicallyBasedShading = false;
  9390. // shadow map
  9391. this.shadowMapEnabled = false;
  9392. this.shadowMapAutoUpdate = true;
  9393. this.shadowMapSoft = true;
  9394. this.shadowMapCullFrontFaces = true;
  9395. this.shadowMapDebug = false;
  9396. this.shadowMapCascade = false;
  9397. // morphs
  9398. this.maxMorphTargets = 8;
  9399. this.maxMorphNormals = 4;
  9400. // flags
  9401. this.autoScaleCubemaps = true;
  9402. // custom render plugins
  9403. this.renderPluginsPre = [];
  9404. this.renderPluginsPost = [];
  9405. // info
  9406. this.info = {
  9407. memory: {
  9408. programs: 0,
  9409. geometries: 0,
  9410. textures: 0
  9411. },
  9412. render: {
  9413. calls: 0,
  9414. vertices: 0,
  9415. faces: 0,
  9416. points: 0
  9417. }
  9418. };
  9419. // internal properties
  9420. var _this = this,
  9421. _programs = [],
  9422. _programs_counter = 0,
  9423. // internal state cache
  9424. _currentProgram = null,
  9425. _currentFramebuffer = null,
  9426. _currentMaterialId = -1,
  9427. _currentGeometryGroupHash = null,
  9428. _currentCamera = null,
  9429. _geometryGroupCounter = 0,
  9430. _usedTextureUnits = 0,
  9431. // GL state cache
  9432. _oldDoubleSided = -1,
  9433. _oldFlipSided = -1,
  9434. _oldBlending = -1,
  9435. _oldBlendEquation = -1,
  9436. _oldBlendSrc = -1,
  9437. _oldBlendDst = -1,
  9438. _oldDepthTest = -1,
  9439. _oldDepthWrite = -1,
  9440. _oldPolygonOffset = null,
  9441. _oldPolygonOffsetFactor = null,
  9442. _oldPolygonOffsetUnits = null,
  9443. _oldLineWidth = null,
  9444. _viewportX = 0,
  9445. _viewportY = 0,
  9446. _viewportWidth = 0,
  9447. _viewportHeight = 0,
  9448. _currentWidth = 0,
  9449. _currentHeight = 0,
  9450. // frustum
  9451. _frustum = new THREE.Frustum(),
  9452. // camera matrices cache
  9453. _projScreenMatrix = new THREE.Matrix4(),
  9454. _projScreenMatrixPS = new THREE.Matrix4(),
  9455. _vector3 = new THREE.Vector4(),
  9456. // light arrays cache
  9457. _direction = new THREE.Vector3(),
  9458. _lightsNeedUpdate = true,
  9459. _lights = {
  9460. ambient: [ 0, 0, 0 ],
  9461. directional: { length: 0, colors: new Array(), positions: new Array() },
  9462. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9463. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  9464. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  9465. };
  9466. // initialize
  9467. var _gl;
  9468. var _glExtensionTextureFloat;
  9469. var _glExtensionStandardDerivatives;
  9470. var _glExtensionTextureFilterAnisotropic;
  9471. var _glExtensionCompressedTextureS3TC;
  9472. initGL();
  9473. setDefaultGLState();
  9474. this.context = _gl;
  9475. // GPU capabilities
  9476. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  9477. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9478. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9479. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9480. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9481. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9482. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9483. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  9484. // API
  9485. this.getContext = function () {
  9486. return _gl;
  9487. };
  9488. this.supportsVertexTextures = function () {
  9489. return _supportsVertexTextures;
  9490. };
  9491. this.getMaxAnisotropy = function () {
  9492. return _maxAnisotropy;
  9493. };
  9494. this.setSize = function ( width, height ) {
  9495. _canvas.width = width;
  9496. _canvas.height = height;
  9497. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9498. };
  9499. this.setViewport = function ( x, y, width, height ) {
  9500. _viewportX = x !== undefined ? x : 0;
  9501. _viewportY = y !== undefined ? y : 0;
  9502. _viewportWidth = width !== undefined ? width : _canvas.width;
  9503. _viewportHeight = height !== undefined ? height : _canvas.height;
  9504. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9505. };
  9506. this.setScissor = function ( x, y, width, height ) {
  9507. _gl.scissor( x, y, width, height );
  9508. };
  9509. this.enableScissorTest = function ( enable ) {
  9510. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9511. };
  9512. // Clearing
  9513. this.setClearColorHex = function ( hex, alpha ) {
  9514. _clearColor.setHex( hex );
  9515. _clearAlpha = alpha;
  9516. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9517. };
  9518. this.setClearColor = function ( color, alpha ) {
  9519. _clearColor.copy( color );
  9520. _clearAlpha = alpha;
  9521. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9522. };
  9523. this.getClearColor = function () {
  9524. return _clearColor;
  9525. };
  9526. this.getClearAlpha = function () {
  9527. return _clearAlpha;
  9528. };
  9529. this.clear = function ( color, depth, stencil ) {
  9530. var bits = 0;
  9531. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9532. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9533. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9534. _gl.clear( bits );
  9535. };
  9536. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9537. this.setRenderTarget( renderTarget );
  9538. this.clear( color, depth, stencil );
  9539. };
  9540. // Plugins
  9541. this.addPostPlugin = function ( plugin ) {
  9542. plugin.init( this );
  9543. this.renderPluginsPost.push( plugin );
  9544. };
  9545. this.addPrePlugin = function ( plugin ) {
  9546. plugin.init( this );
  9547. this.renderPluginsPre.push( plugin );
  9548. };
  9549. // Deallocation
  9550. this.deallocateObject = function ( object ) {
  9551. if ( ! object.__webglInit ) return;
  9552. object.__webglInit = false;
  9553. delete object._modelViewMatrix;
  9554. delete object._normalMatrix;
  9555. delete object._normalMatrixArray;
  9556. delete object._modelViewMatrixArray;
  9557. delete object._modelMatrixArray;
  9558. if ( object instanceof THREE.Mesh ) {
  9559. for ( var g in object.geometry.geometryGroups ) {
  9560. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9561. }
  9562. } else if ( object instanceof THREE.Ribbon ) {
  9563. deleteRibbonBuffers( object.geometry );
  9564. } else if ( object instanceof THREE.Line ) {
  9565. deleteLineBuffers( object.geometry );
  9566. } else if ( object instanceof THREE.ParticleSystem ) {
  9567. deleteParticleBuffers( object.geometry );
  9568. }
  9569. };
  9570. this.deallocateTexture = function ( texture ) {
  9571. if ( ! texture.__webglInit ) return;
  9572. texture.__webglInit = false;
  9573. _gl.deleteTexture( texture.__webglTexture );
  9574. _this.info.memory.textures --;
  9575. };
  9576. this.deallocateRenderTarget = function ( renderTarget ) {
  9577. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9578. _gl.deleteTexture( renderTarget.__webglTexture );
  9579. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9580. for ( var i = 0; i < 6; i ++ ) {
  9581. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9582. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9583. }
  9584. } else {
  9585. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9586. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9587. }
  9588. };
  9589. this.deallocateMaterial = function ( material ) {
  9590. var program = material.program;
  9591. if ( ! program ) return;
  9592. material.program = undefined;
  9593. // only deallocate GL program if this was the last use of shared program
  9594. // assumed there is only single copy of any program in the _programs list
  9595. // (that's how it's constructed)
  9596. var i, il, programInfo;
  9597. var deleteProgram = false;
  9598. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9599. programInfo = _programs[ i ];
  9600. if ( programInfo.program === program ) {
  9601. programInfo.usedTimes --;
  9602. if ( programInfo.usedTimes === 0 ) {
  9603. deleteProgram = true;
  9604. }
  9605. break;
  9606. }
  9607. }
  9608. if ( deleteProgram ) {
  9609. // avoid using array.splice, this is costlier than creating new array from scratch
  9610. var newPrograms = [];
  9611. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9612. programInfo = _programs[ i ];
  9613. if ( programInfo.program !== program ) {
  9614. newPrograms.push( programInfo );
  9615. }
  9616. }
  9617. _programs = newPrograms;
  9618. _gl.deleteProgram( program );
  9619. _this.info.memory.programs --;
  9620. }
  9621. };
  9622. // Rendering
  9623. this.updateShadowMap = function ( scene, camera ) {
  9624. _currentProgram = null;
  9625. _oldBlending = -1;
  9626. _oldDepthTest = -1;
  9627. _oldDepthWrite = -1;
  9628. _currentGeometryGroupHash = -1;
  9629. _currentMaterialId = -1;
  9630. _lightsNeedUpdate = true;
  9631. _oldDoubleSided = -1;
  9632. _oldFlipSided = -1;
  9633. this.shadowMapPlugin.update( scene, camera );
  9634. };
  9635. // Internal functions
  9636. // Buffer allocation
  9637. function createParticleBuffers ( geometry ) {
  9638. geometry.__webglVertexBuffer = _gl.createBuffer();
  9639. geometry.__webglColorBuffer = _gl.createBuffer();
  9640. _this.info.memory.geometries ++;
  9641. };
  9642. function createLineBuffers ( geometry ) {
  9643. geometry.__webglVertexBuffer = _gl.createBuffer();
  9644. geometry.__webglColorBuffer = _gl.createBuffer();
  9645. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  9646. _this.info.memory.geometries ++;
  9647. };
  9648. function createRibbonBuffers ( geometry ) {
  9649. geometry.__webglVertexBuffer = _gl.createBuffer();
  9650. geometry.__webglColorBuffer = _gl.createBuffer();
  9651. geometry.__webglNormalBuffer = _gl.createBuffer();
  9652. _this.info.memory.geometries ++;
  9653. };
  9654. function createMeshBuffers ( geometryGroup ) {
  9655. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9656. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9657. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9658. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9659. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9660. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9661. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9662. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9663. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9664. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9665. var m, ml;
  9666. if ( geometryGroup.numMorphTargets ) {
  9667. geometryGroup.__webglMorphTargetsBuffers = [];
  9668. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9669. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9670. }
  9671. }
  9672. if ( geometryGroup.numMorphNormals ) {
  9673. geometryGroup.__webglMorphNormalsBuffers = [];
  9674. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9675. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9676. }
  9677. }
  9678. _this.info.memory.geometries ++;
  9679. };
  9680. // Buffer deallocation
  9681. function deleteParticleBuffers ( geometry ) {
  9682. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9683. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9684. deleteCustomAttributesBuffers( geometry );
  9685. _this.info.memory.geometries --;
  9686. };
  9687. function deleteLineBuffers ( geometry ) {
  9688. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9689. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9690. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  9691. deleteCustomAttributesBuffers( geometry );
  9692. _this.info.memory.geometries --;
  9693. };
  9694. function deleteRibbonBuffers ( geometry ) {
  9695. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9696. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9697. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  9698. deleteCustomAttributesBuffers( geometry );
  9699. _this.info.memory.geometries --;
  9700. };
  9701. function deleteMeshBuffers ( geometryGroup ) {
  9702. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9703. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9704. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9705. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9706. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9707. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9708. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9709. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9710. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9711. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9712. var m, ml;
  9713. if ( geometryGroup.numMorphTargets ) {
  9714. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9715. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9716. }
  9717. }
  9718. if ( geometryGroup.numMorphNormals ) {
  9719. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9720. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9721. }
  9722. }
  9723. deleteCustomAttributesBuffers( geometryGroup );
  9724. _this.info.memory.geometries --;
  9725. };
  9726. function deleteCustomAttributesBuffers( geometry ) {
  9727. if ( geometry.__webglCustomAttributesList ) {
  9728. for ( var id in geometry.__webglCustomAttributesList ) {
  9729. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  9730. }
  9731. }
  9732. };
  9733. // Buffer initialization
  9734. function initCustomAttributes ( geometry, object ) {
  9735. var nvertices = geometry.vertices.length;
  9736. var material = object.material;
  9737. if ( material.attributes ) {
  9738. if ( geometry.__webglCustomAttributesList === undefined ) {
  9739. geometry.__webglCustomAttributesList = [];
  9740. }
  9741. for ( var a in material.attributes ) {
  9742. var attribute = material.attributes[ a ];
  9743. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9744. attribute.__webglInitialized = true;
  9745. var size = 1; // "f" and "i"
  9746. if ( attribute.type === "v2" ) size = 2;
  9747. else if ( attribute.type === "v3" ) size = 3;
  9748. else if ( attribute.type === "v4" ) size = 4;
  9749. else if ( attribute.type === "c" ) size = 3;
  9750. attribute.size = size;
  9751. attribute.array = new Float32Array( nvertices * size );
  9752. attribute.buffer = _gl.createBuffer();
  9753. attribute.buffer.belongsToAttribute = a;
  9754. attribute.needsUpdate = true;
  9755. }
  9756. geometry.__webglCustomAttributesList.push( attribute );
  9757. }
  9758. }
  9759. };
  9760. function initParticleBuffers ( geometry, object ) {
  9761. var nvertices = geometry.vertices.length;
  9762. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9763. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9764. geometry.__sortArray = [];
  9765. geometry.__webglParticleCount = nvertices;
  9766. initCustomAttributes ( geometry, object );
  9767. };
  9768. function initLineBuffers ( geometry, object ) {
  9769. var nvertices = geometry.vertices.length;
  9770. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9771. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9772. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  9773. geometry.__webglLineCount = nvertices;
  9774. initCustomAttributes ( geometry, object );
  9775. };
  9776. function initRibbonBuffers ( geometry, object ) {
  9777. var nvertices = geometry.vertices.length;
  9778. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9779. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9780. geometry.__normalArray = new Float32Array( nvertices * 3 );
  9781. geometry.__webglVertexCount = nvertices;
  9782. initCustomAttributes ( geometry, object );
  9783. };
  9784. function initMeshBuffers ( geometryGroup, object ) {
  9785. var geometry = object.geometry,
  9786. faces3 = geometryGroup.faces3,
  9787. faces4 = geometryGroup.faces4,
  9788. nvertices = faces3.length * 3 + faces4.length * 4,
  9789. ntris = faces3.length * 1 + faces4.length * 2,
  9790. nlines = faces3.length * 3 + faces4.length * 4,
  9791. material = getBufferMaterial( object, geometryGroup ),
  9792. uvType = bufferGuessUVType( material ),
  9793. normalType = bufferGuessNormalType( material ),
  9794. vertexColorType = bufferGuessVertexColorType( material );
  9795. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9796. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9797. if ( normalType ) {
  9798. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9799. }
  9800. if ( geometry.hasTangents ) {
  9801. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9802. }
  9803. if ( vertexColorType ) {
  9804. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9805. }
  9806. if ( uvType ) {
  9807. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9808. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9809. }
  9810. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9811. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9812. }
  9813. }
  9814. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9815. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9816. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9817. }
  9818. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9819. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9820. var m, ml;
  9821. if ( geometryGroup.numMorphTargets ) {
  9822. geometryGroup.__morphTargetsArrays = [];
  9823. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9824. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9825. }
  9826. }
  9827. if ( geometryGroup.numMorphNormals ) {
  9828. geometryGroup.__morphNormalsArrays = [];
  9829. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9830. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9831. }
  9832. }
  9833. geometryGroup.__webglFaceCount = ntris * 3;
  9834. geometryGroup.__webglLineCount = nlines * 2;
  9835. // custom attributes
  9836. if ( material.attributes ) {
  9837. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9838. geometryGroup.__webglCustomAttributesList = [];
  9839. }
  9840. for ( var a in material.attributes ) {
  9841. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9842. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9843. var originalAttribute = material.attributes[ a ];
  9844. var attribute = {};
  9845. for ( var property in originalAttribute ) {
  9846. attribute[ property ] = originalAttribute[ property ];
  9847. }
  9848. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9849. attribute.__webglInitialized = true;
  9850. var size = 1; // "f" and "i"
  9851. if( attribute.type === "v2" ) size = 2;
  9852. else if( attribute.type === "v3" ) size = 3;
  9853. else if( attribute.type === "v4" ) size = 4;
  9854. else if( attribute.type === "c" ) size = 3;
  9855. attribute.size = size;
  9856. attribute.array = new Float32Array( nvertices * size );
  9857. attribute.buffer = _gl.createBuffer();
  9858. attribute.buffer.belongsToAttribute = a;
  9859. originalAttribute.needsUpdate = true;
  9860. attribute.__original = originalAttribute;
  9861. }
  9862. geometryGroup.__webglCustomAttributesList.push( attribute );
  9863. }
  9864. }
  9865. geometryGroup.__inittedArrays = true;
  9866. };
  9867. function getBufferMaterial( object, geometryGroup ) {
  9868. return object.material instanceof THREE.MeshFaceMaterial
  9869. ? object.material.materials[ geometryGroup.materialIndex ]
  9870. : object.material;
  9871. };
  9872. function materialNeedsSmoothNormals ( material ) {
  9873. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9874. };
  9875. function bufferGuessNormalType ( material ) {
  9876. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9877. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9878. return false;
  9879. }
  9880. if ( materialNeedsSmoothNormals( material ) ) {
  9881. return THREE.SmoothShading;
  9882. } else {
  9883. return THREE.FlatShading;
  9884. }
  9885. };
  9886. function bufferGuessVertexColorType ( material ) {
  9887. if ( material.vertexColors ) {
  9888. return material.vertexColors;
  9889. }
  9890. return false;
  9891. };
  9892. function bufferGuessUVType ( material ) {
  9893. // material must use some texture to require uvs
  9894. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  9895. return true;
  9896. }
  9897. return false;
  9898. };
  9899. //
  9900. function initDirectBuffers( geometry ) {
  9901. var a, attribute, type;
  9902. for ( a in geometry.attributes ) {
  9903. if ( a === "index" ) {
  9904. type = _gl.ELEMENT_ARRAY_BUFFER;
  9905. } else {
  9906. type = _gl.ARRAY_BUFFER;
  9907. }
  9908. attribute = geometry.attributes[ a ];
  9909. attribute.buffer = _gl.createBuffer();
  9910. _gl.bindBuffer( type, attribute.buffer );
  9911. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  9912. }
  9913. };
  9914. // Buffer setting
  9915. function setParticleBuffers ( geometry, hint, object ) {
  9916. var v, c, vertex, offset, index, color,
  9917. vertices = geometry.vertices,
  9918. vl = vertices.length,
  9919. colors = geometry.colors,
  9920. cl = colors.length,
  9921. vertexArray = geometry.__vertexArray,
  9922. colorArray = geometry.__colorArray,
  9923. sortArray = geometry.__sortArray,
  9924. dirtyVertices = geometry.verticesNeedUpdate,
  9925. dirtyElements = geometry.elementsNeedUpdate,
  9926. dirtyColors = geometry.colorsNeedUpdate,
  9927. customAttributes = geometry.__webglCustomAttributesList,
  9928. i, il,
  9929. a, ca, cal, value,
  9930. customAttribute;
  9931. if ( object.sortParticles ) {
  9932. _projScreenMatrixPS.copy( _projScreenMatrix );
  9933. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  9934. for ( v = 0; v < vl; v ++ ) {
  9935. vertex = vertices[ v ];
  9936. _vector3.copy( vertex );
  9937. _projScreenMatrixPS.multiplyVector3( _vector3 );
  9938. sortArray[ v ] = [ _vector3.z, v ];
  9939. }
  9940. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  9941. for ( v = 0; v < vl; v ++ ) {
  9942. vertex = vertices[ sortArray[v][1] ];
  9943. offset = v * 3;
  9944. vertexArray[ offset ] = vertex.x;
  9945. vertexArray[ offset + 1 ] = vertex.y;
  9946. vertexArray[ offset + 2 ] = vertex.z;
  9947. }
  9948. for ( c = 0; c < cl; c ++ ) {
  9949. offset = c * 3;
  9950. color = colors[ sortArray[c][1] ];
  9951. colorArray[ offset ] = color.r;
  9952. colorArray[ offset + 1 ] = color.g;
  9953. colorArray[ offset + 2 ] = color.b;
  9954. }
  9955. if ( customAttributes ) {
  9956. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9957. customAttribute = customAttributes[ i ];
  9958. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  9959. offset = 0;
  9960. cal = customAttribute.value.length;
  9961. if ( customAttribute.size === 1 ) {
  9962. for ( ca = 0; ca < cal; ca ++ ) {
  9963. index = sortArray[ ca ][ 1 ];
  9964. customAttribute.array[ ca ] = customAttribute.value[ index ];
  9965. }
  9966. } else if ( customAttribute.size === 2 ) {
  9967. for ( ca = 0; ca < cal; ca ++ ) {
  9968. index = sortArray[ ca ][ 1 ];
  9969. value = customAttribute.value[ index ];
  9970. customAttribute.array[ offset ] = value.x;
  9971. customAttribute.array[ offset + 1 ] = value.y;
  9972. offset += 2;
  9973. }
  9974. } else if ( customAttribute.size === 3 ) {
  9975. if ( customAttribute.type === "c" ) {
  9976. for ( ca = 0; ca < cal; ca ++ ) {
  9977. index = sortArray[ ca ][ 1 ];
  9978. value = customAttribute.value[ index ];
  9979. customAttribute.array[ offset ] = value.r;
  9980. customAttribute.array[ offset + 1 ] = value.g;
  9981. customAttribute.array[ offset + 2 ] = value.b;
  9982. offset += 3;
  9983. }
  9984. } else {
  9985. for ( ca = 0; ca < cal; ca ++ ) {
  9986. index = sortArray[ ca ][ 1 ];
  9987. value = customAttribute.value[ index ];
  9988. customAttribute.array[ offset ] = value.x;
  9989. customAttribute.array[ offset + 1 ] = value.y;
  9990. customAttribute.array[ offset + 2 ] = value.z;
  9991. offset += 3;
  9992. }
  9993. }
  9994. } else if ( customAttribute.size === 4 ) {
  9995. for ( ca = 0; ca < cal; ca ++ ) {
  9996. index = sortArray[ ca ][ 1 ];
  9997. value = customAttribute.value[ index ];
  9998. customAttribute.array[ offset ] = value.x;
  9999. customAttribute.array[ offset + 1 ] = value.y;
  10000. customAttribute.array[ offset + 2 ] = value.z;
  10001. customAttribute.array[ offset + 3 ] = value.w;
  10002. offset += 4;
  10003. }
  10004. }
  10005. }
  10006. }
  10007. } else {
  10008. if ( dirtyVertices ) {
  10009. for ( v = 0; v < vl; v ++ ) {
  10010. vertex = vertices[ v ];
  10011. offset = v * 3;
  10012. vertexArray[ offset ] = vertex.x;
  10013. vertexArray[ offset + 1 ] = vertex.y;
  10014. vertexArray[ offset + 2 ] = vertex.z;
  10015. }
  10016. }
  10017. if ( dirtyColors ) {
  10018. for ( c = 0; c < cl; c ++ ) {
  10019. color = colors[ c ];
  10020. offset = c * 3;
  10021. colorArray[ offset ] = color.r;
  10022. colorArray[ offset + 1 ] = color.g;
  10023. colorArray[ offset + 2 ] = color.b;
  10024. }
  10025. }
  10026. if ( customAttributes ) {
  10027. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10028. customAttribute = customAttributes[ i ];
  10029. if ( customAttribute.needsUpdate &&
  10030. ( customAttribute.boundTo === undefined ||
  10031. customAttribute.boundTo === "vertices") ) {
  10032. cal = customAttribute.value.length;
  10033. offset = 0;
  10034. if ( customAttribute.size === 1 ) {
  10035. for ( ca = 0; ca < cal; ca ++ ) {
  10036. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10037. }
  10038. } else if ( customAttribute.size === 2 ) {
  10039. for ( ca = 0; ca < cal; ca ++ ) {
  10040. value = customAttribute.value[ ca ];
  10041. customAttribute.array[ offset ] = value.x;
  10042. customAttribute.array[ offset + 1 ] = value.y;
  10043. offset += 2;
  10044. }
  10045. } else if ( customAttribute.size === 3 ) {
  10046. if ( customAttribute.type === "c" ) {
  10047. for ( ca = 0; ca < cal; ca ++ ) {
  10048. value = customAttribute.value[ ca ];
  10049. customAttribute.array[ offset ] = value.r;
  10050. customAttribute.array[ offset + 1 ] = value.g;
  10051. customAttribute.array[ offset + 2 ] = value.b;
  10052. offset += 3;
  10053. }
  10054. } else {
  10055. for ( ca = 0; ca < cal; ca ++ ) {
  10056. value = customAttribute.value[ ca ];
  10057. customAttribute.array[ offset ] = value.x;
  10058. customAttribute.array[ offset + 1 ] = value.y;
  10059. customAttribute.array[ offset + 2 ] = value.z;
  10060. offset += 3;
  10061. }
  10062. }
  10063. } else if ( customAttribute.size === 4 ) {
  10064. for ( ca = 0; ca < cal; ca ++ ) {
  10065. value = customAttribute.value[ ca ];
  10066. customAttribute.array[ offset ] = value.x;
  10067. customAttribute.array[ offset + 1 ] = value.y;
  10068. customAttribute.array[ offset + 2 ] = value.z;
  10069. customAttribute.array[ offset + 3 ] = value.w;
  10070. offset += 4;
  10071. }
  10072. }
  10073. }
  10074. }
  10075. }
  10076. }
  10077. if ( dirtyVertices || object.sortParticles ) {
  10078. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10079. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10080. }
  10081. if ( dirtyColors || object.sortParticles ) {
  10082. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10083. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10084. }
  10085. if ( customAttributes ) {
  10086. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10087. customAttribute = customAttributes[ i ];
  10088. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10089. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10090. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10091. }
  10092. }
  10093. }
  10094. };
  10095. function setLineBuffers ( geometry, hint ) {
  10096. var v, c, d, vertex, offset, color,
  10097. vertices = geometry.vertices,
  10098. colors = geometry.colors,
  10099. lineDistances = geometry.lineDistances,
  10100. vl = vertices.length,
  10101. cl = colors.length,
  10102. dl = lineDistances.length,
  10103. vertexArray = geometry.__vertexArray,
  10104. colorArray = geometry.__colorArray,
  10105. lineDistanceArray = geometry.__lineDistanceArray,
  10106. dirtyVertices = geometry.verticesNeedUpdate,
  10107. dirtyColors = geometry.colorsNeedUpdate,
  10108. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10109. customAttributes = geometry.__webglCustomAttributesList,
  10110. i, il,
  10111. a, ca, cal, value,
  10112. customAttribute;
  10113. if ( dirtyVertices ) {
  10114. for ( v = 0; v < vl; v ++ ) {
  10115. vertex = vertices[ v ];
  10116. offset = v * 3;
  10117. vertexArray[ offset ] = vertex.x;
  10118. vertexArray[ offset + 1 ] = vertex.y;
  10119. vertexArray[ offset + 2 ] = vertex.z;
  10120. }
  10121. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10122. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10123. }
  10124. if ( dirtyColors ) {
  10125. for ( c = 0; c < cl; c ++ ) {
  10126. color = colors[ c ];
  10127. offset = c * 3;
  10128. colorArray[ offset ] = color.r;
  10129. colorArray[ offset + 1 ] = color.g;
  10130. colorArray[ offset + 2 ] = color.b;
  10131. }
  10132. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10133. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10134. }
  10135. if ( dirtyLineDistances ) {
  10136. for ( d = 0; d < dl; d ++ ) {
  10137. lineDistanceArray[ d ] = lineDistances[ d ];
  10138. }
  10139. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10140. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10141. }
  10142. if ( customAttributes ) {
  10143. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10144. customAttribute = customAttributes[ i ];
  10145. if ( customAttribute.needsUpdate &&
  10146. ( customAttribute.boundTo === undefined ||
  10147. customAttribute.boundTo === "vertices" ) ) {
  10148. offset = 0;
  10149. cal = customAttribute.value.length;
  10150. if ( customAttribute.size === 1 ) {
  10151. for ( ca = 0; ca < cal; ca ++ ) {
  10152. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10153. }
  10154. } else if ( customAttribute.size === 2 ) {
  10155. for ( ca = 0; ca < cal; ca ++ ) {
  10156. value = customAttribute.value[ ca ];
  10157. customAttribute.array[ offset ] = value.x;
  10158. customAttribute.array[ offset + 1 ] = value.y;
  10159. offset += 2;
  10160. }
  10161. } else if ( customAttribute.size === 3 ) {
  10162. if ( customAttribute.type === "c" ) {
  10163. for ( ca = 0; ca < cal; ca ++ ) {
  10164. value = customAttribute.value[ ca ];
  10165. customAttribute.array[ offset ] = value.r;
  10166. customAttribute.array[ offset + 1 ] = value.g;
  10167. customAttribute.array[ offset + 2 ] = value.b;
  10168. offset += 3;
  10169. }
  10170. } else {
  10171. for ( ca = 0; ca < cal; ca ++ ) {
  10172. value = customAttribute.value[ ca ];
  10173. customAttribute.array[ offset ] = value.x;
  10174. customAttribute.array[ offset + 1 ] = value.y;
  10175. customAttribute.array[ offset + 2 ] = value.z;
  10176. offset += 3;
  10177. }
  10178. }
  10179. } else if ( customAttribute.size === 4 ) {
  10180. for ( ca = 0; ca < cal; ca ++ ) {
  10181. value = customAttribute.value[ ca ];
  10182. customAttribute.array[ offset ] = value.x;
  10183. customAttribute.array[ offset + 1 ] = value.y;
  10184. customAttribute.array[ offset + 2 ] = value.z;
  10185. customAttribute.array[ offset + 3 ] = value.w;
  10186. offset += 4;
  10187. }
  10188. }
  10189. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10190. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10191. }
  10192. }
  10193. }
  10194. };
  10195. function setRibbonBuffers ( geometry, hint ) {
  10196. var v, c, n, vertex, offset, color, normal,
  10197. i, il, ca, cal, customAttribute, value,
  10198. vertices = geometry.vertices,
  10199. colors = geometry.colors,
  10200. normals = geometry.normals,
  10201. vl = vertices.length,
  10202. cl = colors.length,
  10203. nl = normals.length,
  10204. vertexArray = geometry.__vertexArray,
  10205. colorArray = geometry.__colorArray,
  10206. normalArray = geometry.__normalArray,
  10207. dirtyVertices = geometry.verticesNeedUpdate,
  10208. dirtyColors = geometry.colorsNeedUpdate,
  10209. dirtyNormals = geometry.normalsNeedUpdate,
  10210. customAttributes = geometry.__webglCustomAttributesList;
  10211. if ( dirtyVertices ) {
  10212. for ( v = 0; v < vl; v ++ ) {
  10213. vertex = vertices[ v ];
  10214. offset = v * 3;
  10215. vertexArray[ offset ] = vertex.x;
  10216. vertexArray[ offset + 1 ] = vertex.y;
  10217. vertexArray[ offset + 2 ] = vertex.z;
  10218. }
  10219. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10220. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10221. }
  10222. if ( dirtyColors ) {
  10223. for ( c = 0; c < cl; c ++ ) {
  10224. color = colors[ c ];
  10225. offset = c * 3;
  10226. colorArray[ offset ] = color.r;
  10227. colorArray[ offset + 1 ] = color.g;
  10228. colorArray[ offset + 2 ] = color.b;
  10229. }
  10230. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10231. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10232. }
  10233. if ( dirtyNormals ) {
  10234. for ( n = 0; n < nl; n ++ ) {
  10235. normal = normals[ n ];
  10236. offset = n * 3;
  10237. normalArray[ offset ] = normal.x;
  10238. normalArray[ offset + 1 ] = normal.y;
  10239. normalArray[ offset + 2 ] = normal.z;
  10240. }
  10241. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  10242. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10243. }
  10244. if ( customAttributes ) {
  10245. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10246. customAttribute = customAttributes[ i ];
  10247. if ( customAttribute.needsUpdate &&
  10248. ( customAttribute.boundTo === undefined ||
  10249. customAttribute.boundTo === "vertices" ) ) {
  10250. offset = 0;
  10251. cal = customAttribute.value.length;
  10252. if ( customAttribute.size === 1 ) {
  10253. for ( ca = 0; ca < cal; ca ++ ) {
  10254. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10255. }
  10256. } else if ( customAttribute.size === 2 ) {
  10257. for ( ca = 0; ca < cal; ca ++ ) {
  10258. value = customAttribute.value[ ca ];
  10259. customAttribute.array[ offset ] = value.x;
  10260. customAttribute.array[ offset + 1 ] = value.y;
  10261. offset += 2;
  10262. }
  10263. } else if ( customAttribute.size === 3 ) {
  10264. if ( customAttribute.type === "c" ) {
  10265. for ( ca = 0; ca < cal; ca ++ ) {
  10266. value = customAttribute.value[ ca ];
  10267. customAttribute.array[ offset ] = value.r;
  10268. customAttribute.array[ offset + 1 ] = value.g;
  10269. customAttribute.array[ offset + 2 ] = value.b;
  10270. offset += 3;
  10271. }
  10272. } else {
  10273. for ( ca = 0; ca < cal; ca ++ ) {
  10274. value = customAttribute.value[ ca ];
  10275. customAttribute.array[ offset ] = value.x;
  10276. customAttribute.array[ offset + 1 ] = value.y;
  10277. customAttribute.array[ offset + 2 ] = value.z;
  10278. offset += 3;
  10279. }
  10280. }
  10281. } else if ( customAttribute.size === 4 ) {
  10282. for ( ca = 0; ca < cal; ca ++ ) {
  10283. value = customAttribute.value[ ca ];
  10284. customAttribute.array[ offset ] = value.x;
  10285. customAttribute.array[ offset + 1 ] = value.y;
  10286. customAttribute.array[ offset + 2 ] = value.z;
  10287. customAttribute.array[ offset + 3 ] = value.w;
  10288. offset += 4;
  10289. }
  10290. }
  10291. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10292. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10293. }
  10294. }
  10295. }
  10296. };
  10297. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  10298. if ( ! geometryGroup.__inittedArrays ) {
  10299. return;
  10300. }
  10301. var normalType = bufferGuessNormalType( material ),
  10302. vertexColorType = bufferGuessVertexColorType( material ),
  10303. uvType = bufferGuessUVType( material ),
  10304. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  10305. var f, fl, fi, face,
  10306. vertexNormals, faceNormal, normal,
  10307. vertexColors, faceColor,
  10308. vertexTangents,
  10309. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  10310. c1, c2, c3, c4,
  10311. sw1, sw2, sw3, sw4,
  10312. si1, si2, si3, si4,
  10313. sa1, sa2, sa3, sa4,
  10314. sb1, sb2, sb3, sb4,
  10315. m, ml, i, il,
  10316. vn, uvi, uv2i,
  10317. vk, vkl, vka,
  10318. nka, chf, faceVertexNormals,
  10319. a,
  10320. vertexIndex = 0,
  10321. offset = 0,
  10322. offset_uv = 0,
  10323. offset_uv2 = 0,
  10324. offset_face = 0,
  10325. offset_normal = 0,
  10326. offset_tangent = 0,
  10327. offset_line = 0,
  10328. offset_color = 0,
  10329. offset_skin = 0,
  10330. offset_morphTarget = 0,
  10331. offset_custom = 0,
  10332. offset_customSrc = 0,
  10333. value,
  10334. vertexArray = geometryGroup.__vertexArray,
  10335. uvArray = geometryGroup.__uvArray,
  10336. uv2Array = geometryGroup.__uv2Array,
  10337. normalArray = geometryGroup.__normalArray,
  10338. tangentArray = geometryGroup.__tangentArray,
  10339. colorArray = geometryGroup.__colorArray,
  10340. skinIndexArray = geometryGroup.__skinIndexArray,
  10341. skinWeightArray = geometryGroup.__skinWeightArray,
  10342. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  10343. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  10344. customAttributes = geometryGroup.__webglCustomAttributesList,
  10345. customAttribute,
  10346. faceArray = geometryGroup.__faceArray,
  10347. lineArray = geometryGroup.__lineArray,
  10348. geometry = object.geometry, // this is shared for all chunks
  10349. dirtyVertices = geometry.verticesNeedUpdate,
  10350. dirtyElements = geometry.elementsNeedUpdate,
  10351. dirtyUvs = geometry.uvsNeedUpdate,
  10352. dirtyNormals = geometry.normalsNeedUpdate,
  10353. dirtyTangents = geometry.tangentsNeedUpdate,
  10354. dirtyColors = geometry.colorsNeedUpdate,
  10355. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  10356. vertices = geometry.vertices,
  10357. chunk_faces3 = geometryGroup.faces3,
  10358. chunk_faces4 = geometryGroup.faces4,
  10359. obj_faces = geometry.faces,
  10360. obj_uvs = geometry.faceVertexUvs[ 0 ],
  10361. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  10362. obj_colors = geometry.colors,
  10363. obj_skinIndices = geometry.skinIndices,
  10364. obj_skinWeights = geometry.skinWeights,
  10365. morphTargets = geometry.morphTargets,
  10366. morphNormals = geometry.morphNormals;
  10367. if ( dirtyVertices ) {
  10368. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10369. face = obj_faces[ chunk_faces3[ f ] ];
  10370. v1 = vertices[ face.a ];
  10371. v2 = vertices[ face.b ];
  10372. v3 = vertices[ face.c ];
  10373. vertexArray[ offset ] = v1.x;
  10374. vertexArray[ offset + 1 ] = v1.y;
  10375. vertexArray[ offset + 2 ] = v1.z;
  10376. vertexArray[ offset + 3 ] = v2.x;
  10377. vertexArray[ offset + 4 ] = v2.y;
  10378. vertexArray[ offset + 5 ] = v2.z;
  10379. vertexArray[ offset + 6 ] = v3.x;
  10380. vertexArray[ offset + 7 ] = v3.y;
  10381. vertexArray[ offset + 8 ] = v3.z;
  10382. offset += 9;
  10383. }
  10384. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10385. face = obj_faces[ chunk_faces4[ f ] ];
  10386. v1 = vertices[ face.a ];
  10387. v2 = vertices[ face.b ];
  10388. v3 = vertices[ face.c ];
  10389. v4 = vertices[ face.d ];
  10390. vertexArray[ offset ] = v1.x;
  10391. vertexArray[ offset + 1 ] = v1.y;
  10392. vertexArray[ offset + 2 ] = v1.z;
  10393. vertexArray[ offset + 3 ] = v2.x;
  10394. vertexArray[ offset + 4 ] = v2.y;
  10395. vertexArray[ offset + 5 ] = v2.z;
  10396. vertexArray[ offset + 6 ] = v3.x;
  10397. vertexArray[ offset + 7 ] = v3.y;
  10398. vertexArray[ offset + 8 ] = v3.z;
  10399. vertexArray[ offset + 9 ] = v4.x;
  10400. vertexArray[ offset + 10 ] = v4.y;
  10401. vertexArray[ offset + 11 ] = v4.z;
  10402. offset += 12;
  10403. }
  10404. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10405. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10406. }
  10407. if ( dirtyMorphTargets ) {
  10408. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  10409. offset_morphTarget = 0;
  10410. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10411. chf = chunk_faces3[ f ];
  10412. face = obj_faces[ chf ];
  10413. // morph positions
  10414. v1 = morphTargets[ vk ].vertices[ face.a ];
  10415. v2 = morphTargets[ vk ].vertices[ face.b ];
  10416. v3 = morphTargets[ vk ].vertices[ face.c ];
  10417. vka = morphTargetsArrays[ vk ];
  10418. vka[ offset_morphTarget ] = v1.x;
  10419. vka[ offset_morphTarget + 1 ] = v1.y;
  10420. vka[ offset_morphTarget + 2 ] = v1.z;
  10421. vka[ offset_morphTarget + 3 ] = v2.x;
  10422. vka[ offset_morphTarget + 4 ] = v2.y;
  10423. vka[ offset_morphTarget + 5 ] = v2.z;
  10424. vka[ offset_morphTarget + 6 ] = v3.x;
  10425. vka[ offset_morphTarget + 7 ] = v3.y;
  10426. vka[ offset_morphTarget + 8 ] = v3.z;
  10427. // morph normals
  10428. if ( material.morphNormals ) {
  10429. if ( needsSmoothNormals ) {
  10430. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10431. n1 = faceVertexNormals.a;
  10432. n2 = faceVertexNormals.b;
  10433. n3 = faceVertexNormals.c;
  10434. } else {
  10435. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10436. n2 = n1;
  10437. n3 = n1;
  10438. }
  10439. nka = morphNormalsArrays[ vk ];
  10440. nka[ offset_morphTarget ] = n1.x;
  10441. nka[ offset_morphTarget + 1 ] = n1.y;
  10442. nka[ offset_morphTarget + 2 ] = n1.z;
  10443. nka[ offset_morphTarget + 3 ] = n2.x;
  10444. nka[ offset_morphTarget + 4 ] = n2.y;
  10445. nka[ offset_morphTarget + 5 ] = n2.z;
  10446. nka[ offset_morphTarget + 6 ] = n3.x;
  10447. nka[ offset_morphTarget + 7 ] = n3.y;
  10448. nka[ offset_morphTarget + 8 ] = n3.z;
  10449. }
  10450. //
  10451. offset_morphTarget += 9;
  10452. }
  10453. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10454. chf = chunk_faces4[ f ];
  10455. face = obj_faces[ chf ];
  10456. // morph positions
  10457. v1 = morphTargets[ vk ].vertices[ face.a ];
  10458. v2 = morphTargets[ vk ].vertices[ face.b ];
  10459. v3 = morphTargets[ vk ].vertices[ face.c ];
  10460. v4 = morphTargets[ vk ].vertices[ face.d ];
  10461. vka = morphTargetsArrays[ vk ];
  10462. vka[ offset_morphTarget ] = v1.x;
  10463. vka[ offset_morphTarget + 1 ] = v1.y;
  10464. vka[ offset_morphTarget + 2 ] = v1.z;
  10465. vka[ offset_morphTarget + 3 ] = v2.x;
  10466. vka[ offset_morphTarget + 4 ] = v2.y;
  10467. vka[ offset_morphTarget + 5 ] = v2.z;
  10468. vka[ offset_morphTarget + 6 ] = v3.x;
  10469. vka[ offset_morphTarget + 7 ] = v3.y;
  10470. vka[ offset_morphTarget + 8 ] = v3.z;
  10471. vka[ offset_morphTarget + 9 ] = v4.x;
  10472. vka[ offset_morphTarget + 10 ] = v4.y;
  10473. vka[ offset_morphTarget + 11 ] = v4.z;
  10474. // morph normals
  10475. if ( material.morphNormals ) {
  10476. if ( needsSmoothNormals ) {
  10477. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10478. n1 = faceVertexNormals.a;
  10479. n2 = faceVertexNormals.b;
  10480. n3 = faceVertexNormals.c;
  10481. n4 = faceVertexNormals.d;
  10482. } else {
  10483. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10484. n2 = n1;
  10485. n3 = n1;
  10486. n4 = n1;
  10487. }
  10488. nka = morphNormalsArrays[ vk ];
  10489. nka[ offset_morphTarget ] = n1.x;
  10490. nka[ offset_morphTarget + 1 ] = n1.y;
  10491. nka[ offset_morphTarget + 2 ] = n1.z;
  10492. nka[ offset_morphTarget + 3 ] = n2.x;
  10493. nka[ offset_morphTarget + 4 ] = n2.y;
  10494. nka[ offset_morphTarget + 5 ] = n2.z;
  10495. nka[ offset_morphTarget + 6 ] = n3.x;
  10496. nka[ offset_morphTarget + 7 ] = n3.y;
  10497. nka[ offset_morphTarget + 8 ] = n3.z;
  10498. nka[ offset_morphTarget + 9 ] = n4.x;
  10499. nka[ offset_morphTarget + 10 ] = n4.y;
  10500. nka[ offset_morphTarget + 11 ] = n4.z;
  10501. }
  10502. //
  10503. offset_morphTarget += 12;
  10504. }
  10505. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  10506. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  10507. if ( material.morphNormals ) {
  10508. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  10509. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  10510. }
  10511. }
  10512. }
  10513. if ( obj_skinWeights.length ) {
  10514. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10515. face = obj_faces[ chunk_faces3[ f ] ];
  10516. // weights
  10517. sw1 = obj_skinWeights[ face.a ];
  10518. sw2 = obj_skinWeights[ face.b ];
  10519. sw3 = obj_skinWeights[ face.c ];
  10520. skinWeightArray[ offset_skin ] = sw1.x;
  10521. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10522. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10523. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10524. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10525. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10526. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10527. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10528. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10529. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10530. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10531. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10532. // indices
  10533. si1 = obj_skinIndices[ face.a ];
  10534. si2 = obj_skinIndices[ face.b ];
  10535. si3 = obj_skinIndices[ face.c ];
  10536. skinIndexArray[ offset_skin ] = si1.x;
  10537. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10538. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10539. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10540. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10541. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10542. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10543. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10544. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10545. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10546. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10547. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10548. offset_skin += 12;
  10549. }
  10550. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10551. face = obj_faces[ chunk_faces4[ f ] ];
  10552. // weights
  10553. sw1 = obj_skinWeights[ face.a ];
  10554. sw2 = obj_skinWeights[ face.b ];
  10555. sw3 = obj_skinWeights[ face.c ];
  10556. sw4 = obj_skinWeights[ face.d ];
  10557. skinWeightArray[ offset_skin ] = sw1.x;
  10558. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10559. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10560. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10561. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10562. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10563. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10564. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10565. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10566. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10567. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10568. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10569. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10570. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10571. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10572. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10573. // indices
  10574. si1 = obj_skinIndices[ face.a ];
  10575. si2 = obj_skinIndices[ face.b ];
  10576. si3 = obj_skinIndices[ face.c ];
  10577. si4 = obj_skinIndices[ face.d ];
  10578. skinIndexArray[ offset_skin ] = si1.x;
  10579. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10580. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10581. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10582. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10583. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10584. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10585. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10586. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10587. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10588. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10589. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10590. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10591. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10592. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10593. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10594. offset_skin += 16;
  10595. }
  10596. if ( offset_skin > 0 ) {
  10597. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10598. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10599. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10600. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10601. }
  10602. }
  10603. if ( dirtyColors && vertexColorType ) {
  10604. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10605. face = obj_faces[ chunk_faces3[ f ] ];
  10606. vertexColors = face.vertexColors;
  10607. faceColor = face.color;
  10608. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10609. c1 = vertexColors[ 0 ];
  10610. c2 = vertexColors[ 1 ];
  10611. c3 = vertexColors[ 2 ];
  10612. } else {
  10613. c1 = faceColor;
  10614. c2 = faceColor;
  10615. c3 = faceColor;
  10616. }
  10617. colorArray[ offset_color ] = c1.r;
  10618. colorArray[ offset_color + 1 ] = c1.g;
  10619. colorArray[ offset_color + 2 ] = c1.b;
  10620. colorArray[ offset_color + 3 ] = c2.r;
  10621. colorArray[ offset_color + 4 ] = c2.g;
  10622. colorArray[ offset_color + 5 ] = c2.b;
  10623. colorArray[ offset_color + 6 ] = c3.r;
  10624. colorArray[ offset_color + 7 ] = c3.g;
  10625. colorArray[ offset_color + 8 ] = c3.b;
  10626. offset_color += 9;
  10627. }
  10628. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10629. face = obj_faces[ chunk_faces4[ f ] ];
  10630. vertexColors = face.vertexColors;
  10631. faceColor = face.color;
  10632. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10633. c1 = vertexColors[ 0 ];
  10634. c2 = vertexColors[ 1 ];
  10635. c3 = vertexColors[ 2 ];
  10636. c4 = vertexColors[ 3 ];
  10637. } else {
  10638. c1 = faceColor;
  10639. c2 = faceColor;
  10640. c3 = faceColor;
  10641. c4 = faceColor;
  10642. }
  10643. colorArray[ offset_color ] = c1.r;
  10644. colorArray[ offset_color + 1 ] = c1.g;
  10645. colorArray[ offset_color + 2 ] = c1.b;
  10646. colorArray[ offset_color + 3 ] = c2.r;
  10647. colorArray[ offset_color + 4 ] = c2.g;
  10648. colorArray[ offset_color + 5 ] = c2.b;
  10649. colorArray[ offset_color + 6 ] = c3.r;
  10650. colorArray[ offset_color + 7 ] = c3.g;
  10651. colorArray[ offset_color + 8 ] = c3.b;
  10652. colorArray[ offset_color + 9 ] = c4.r;
  10653. colorArray[ offset_color + 10 ] = c4.g;
  10654. colorArray[ offset_color + 11 ] = c4.b;
  10655. offset_color += 12;
  10656. }
  10657. if ( offset_color > 0 ) {
  10658. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10659. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10660. }
  10661. }
  10662. if ( dirtyTangents && geometry.hasTangents ) {
  10663. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10664. face = obj_faces[ chunk_faces3[ f ] ];
  10665. vertexTangents = face.vertexTangents;
  10666. t1 = vertexTangents[ 0 ];
  10667. t2 = vertexTangents[ 1 ];
  10668. t3 = vertexTangents[ 2 ];
  10669. tangentArray[ offset_tangent ] = t1.x;
  10670. tangentArray[ offset_tangent + 1 ] = t1.y;
  10671. tangentArray[ offset_tangent + 2 ] = t1.z;
  10672. tangentArray[ offset_tangent + 3 ] = t1.w;
  10673. tangentArray[ offset_tangent + 4 ] = t2.x;
  10674. tangentArray[ offset_tangent + 5 ] = t2.y;
  10675. tangentArray[ offset_tangent + 6 ] = t2.z;
  10676. tangentArray[ offset_tangent + 7 ] = t2.w;
  10677. tangentArray[ offset_tangent + 8 ] = t3.x;
  10678. tangentArray[ offset_tangent + 9 ] = t3.y;
  10679. tangentArray[ offset_tangent + 10 ] = t3.z;
  10680. tangentArray[ offset_tangent + 11 ] = t3.w;
  10681. offset_tangent += 12;
  10682. }
  10683. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10684. face = obj_faces[ chunk_faces4[ f ] ];
  10685. vertexTangents = face.vertexTangents;
  10686. t1 = vertexTangents[ 0 ];
  10687. t2 = vertexTangents[ 1 ];
  10688. t3 = vertexTangents[ 2 ];
  10689. t4 = vertexTangents[ 3 ];
  10690. tangentArray[ offset_tangent ] = t1.x;
  10691. tangentArray[ offset_tangent + 1 ] = t1.y;
  10692. tangentArray[ offset_tangent + 2 ] = t1.z;
  10693. tangentArray[ offset_tangent + 3 ] = t1.w;
  10694. tangentArray[ offset_tangent + 4 ] = t2.x;
  10695. tangentArray[ offset_tangent + 5 ] = t2.y;
  10696. tangentArray[ offset_tangent + 6 ] = t2.z;
  10697. tangentArray[ offset_tangent + 7 ] = t2.w;
  10698. tangentArray[ offset_tangent + 8 ] = t3.x;
  10699. tangentArray[ offset_tangent + 9 ] = t3.y;
  10700. tangentArray[ offset_tangent + 10 ] = t3.z;
  10701. tangentArray[ offset_tangent + 11 ] = t3.w;
  10702. tangentArray[ offset_tangent + 12 ] = t4.x;
  10703. tangentArray[ offset_tangent + 13 ] = t4.y;
  10704. tangentArray[ offset_tangent + 14 ] = t4.z;
  10705. tangentArray[ offset_tangent + 15 ] = t4.w;
  10706. offset_tangent += 16;
  10707. }
  10708. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10709. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10710. }
  10711. if ( dirtyNormals && normalType ) {
  10712. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10713. face = obj_faces[ chunk_faces3[ f ] ];
  10714. vertexNormals = face.vertexNormals;
  10715. faceNormal = face.normal;
  10716. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10717. for ( i = 0; i < 3; i ++ ) {
  10718. vn = vertexNormals[ i ];
  10719. normalArray[ offset_normal ] = vn.x;
  10720. normalArray[ offset_normal + 1 ] = vn.y;
  10721. normalArray[ offset_normal + 2 ] = vn.z;
  10722. offset_normal += 3;
  10723. }
  10724. } else {
  10725. for ( i = 0; i < 3; i ++ ) {
  10726. normalArray[ offset_normal ] = faceNormal.x;
  10727. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10728. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10729. offset_normal += 3;
  10730. }
  10731. }
  10732. }
  10733. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10734. face = obj_faces[ chunk_faces4[ f ] ];
  10735. vertexNormals = face.vertexNormals;
  10736. faceNormal = face.normal;
  10737. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10738. for ( i = 0; i < 4; i ++ ) {
  10739. vn = vertexNormals[ i ];
  10740. normalArray[ offset_normal ] = vn.x;
  10741. normalArray[ offset_normal + 1 ] = vn.y;
  10742. normalArray[ offset_normal + 2 ] = vn.z;
  10743. offset_normal += 3;
  10744. }
  10745. } else {
  10746. for ( i = 0; i < 4; i ++ ) {
  10747. normalArray[ offset_normal ] = faceNormal.x;
  10748. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10749. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10750. offset_normal += 3;
  10751. }
  10752. }
  10753. }
  10754. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10755. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10756. }
  10757. if ( dirtyUvs && obj_uvs && uvType ) {
  10758. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10759. fi = chunk_faces3[ f ];
  10760. uv = obj_uvs[ fi ];
  10761. if ( uv === undefined ) continue;
  10762. for ( i = 0; i < 3; i ++ ) {
  10763. uvi = uv[ i ];
  10764. uvArray[ offset_uv ] = uvi.u;
  10765. uvArray[ offset_uv + 1 ] = uvi.v;
  10766. offset_uv += 2;
  10767. }
  10768. }
  10769. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10770. fi = chunk_faces4[ f ];
  10771. uv = obj_uvs[ fi ];
  10772. if ( uv === undefined ) continue;
  10773. for ( i = 0; i < 4; i ++ ) {
  10774. uvi = uv[ i ];
  10775. uvArray[ offset_uv ] = uvi.u;
  10776. uvArray[ offset_uv + 1 ] = uvi.v;
  10777. offset_uv += 2;
  10778. }
  10779. }
  10780. if ( offset_uv > 0 ) {
  10781. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10782. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10783. }
  10784. }
  10785. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10786. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10787. fi = chunk_faces3[ f ];
  10788. uv2 = obj_uvs2[ fi ];
  10789. if ( uv2 === undefined ) continue;
  10790. for ( i = 0; i < 3; i ++ ) {
  10791. uv2i = uv2[ i ];
  10792. uv2Array[ offset_uv2 ] = uv2i.u;
  10793. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10794. offset_uv2 += 2;
  10795. }
  10796. }
  10797. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10798. fi = chunk_faces4[ f ];
  10799. uv2 = obj_uvs2[ fi ];
  10800. if ( uv2 === undefined ) continue;
  10801. for ( i = 0; i < 4; i ++ ) {
  10802. uv2i = uv2[ i ];
  10803. uv2Array[ offset_uv2 ] = uv2i.u;
  10804. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10805. offset_uv2 += 2;
  10806. }
  10807. }
  10808. if ( offset_uv2 > 0 ) {
  10809. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10810. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10811. }
  10812. }
  10813. if ( dirtyElements ) {
  10814. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10815. faceArray[ offset_face ] = vertexIndex;
  10816. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10817. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10818. offset_face += 3;
  10819. lineArray[ offset_line ] = vertexIndex;
  10820. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10821. lineArray[ offset_line + 2 ] = vertexIndex;
  10822. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10823. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10824. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10825. offset_line += 6;
  10826. vertexIndex += 3;
  10827. }
  10828. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10829. faceArray[ offset_face ] = vertexIndex;
  10830. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10831. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10832. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10833. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10834. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10835. offset_face += 6;
  10836. lineArray[ offset_line ] = vertexIndex;
  10837. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10838. lineArray[ offset_line + 2 ] = vertexIndex;
  10839. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10840. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10841. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10842. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10843. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10844. offset_line += 8;
  10845. vertexIndex += 4;
  10846. }
  10847. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10848. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10849. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10850. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10851. }
  10852. if ( customAttributes ) {
  10853. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10854. customAttribute = customAttributes[ i ];
  10855. if ( ! customAttribute.__original.needsUpdate ) continue;
  10856. offset_custom = 0;
  10857. offset_customSrc = 0;
  10858. if ( customAttribute.size === 1 ) {
  10859. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10860. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10861. face = obj_faces[ chunk_faces3[ f ] ];
  10862. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10863. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10864. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10865. offset_custom += 3;
  10866. }
  10867. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10868. face = obj_faces[ chunk_faces4[ f ] ];
  10869. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10870. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10871. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10872. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10873. offset_custom += 4;
  10874. }
  10875. } else if ( customAttribute.boundTo === "faces" ) {
  10876. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10877. value = customAttribute.value[ chunk_faces3[ f ] ];
  10878. customAttribute.array[ offset_custom ] = value;
  10879. customAttribute.array[ offset_custom + 1 ] = value;
  10880. customAttribute.array[ offset_custom + 2 ] = value;
  10881. offset_custom += 3;
  10882. }
  10883. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10884. value = customAttribute.value[ chunk_faces4[ f ] ];
  10885. customAttribute.array[ offset_custom ] = value;
  10886. customAttribute.array[ offset_custom + 1 ] = value;
  10887. customAttribute.array[ offset_custom + 2 ] = value;
  10888. customAttribute.array[ offset_custom + 3 ] = value;
  10889. offset_custom += 4;
  10890. }
  10891. }
  10892. } else if ( customAttribute.size === 2 ) {
  10893. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10894. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10895. face = obj_faces[ chunk_faces3[ f ] ];
  10896. v1 = customAttribute.value[ face.a ];
  10897. v2 = customAttribute.value[ face.b ];
  10898. v3 = customAttribute.value[ face.c ];
  10899. customAttribute.array[ offset_custom ] = v1.x;
  10900. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10901. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10902. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10903. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10904. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10905. offset_custom += 6;
  10906. }
  10907. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10908. face = obj_faces[ chunk_faces4[ f ] ];
  10909. v1 = customAttribute.value[ face.a ];
  10910. v2 = customAttribute.value[ face.b ];
  10911. v3 = customAttribute.value[ face.c ];
  10912. v4 = customAttribute.value[ face.d ];
  10913. customAttribute.array[ offset_custom ] = v1.x;
  10914. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10915. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10916. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10917. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10918. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10919. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10920. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10921. offset_custom += 8;
  10922. }
  10923. } else if ( customAttribute.boundTo === "faces" ) {
  10924. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10925. value = customAttribute.value[ chunk_faces3[ f ] ];
  10926. v1 = value;
  10927. v2 = value;
  10928. v3 = value;
  10929. customAttribute.array[ offset_custom ] = v1.x;
  10930. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10931. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10932. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10933. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10934. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10935. offset_custom += 6;
  10936. }
  10937. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10938. value = customAttribute.value[ chunk_faces4[ f ] ];
  10939. v1 = value;
  10940. v2 = value;
  10941. v3 = value;
  10942. v4 = value;
  10943. customAttribute.array[ offset_custom ] = v1.x;
  10944. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10945. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10946. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10947. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10948. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10949. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10950. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10951. offset_custom += 8;
  10952. }
  10953. }
  10954. } else if ( customAttribute.size === 3 ) {
  10955. var pp;
  10956. if ( customAttribute.type === "c" ) {
  10957. pp = [ "r", "g", "b" ];
  10958. } else {
  10959. pp = [ "x", "y", "z" ];
  10960. }
  10961. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10962. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10963. face = obj_faces[ chunk_faces3[ f ] ];
  10964. v1 = customAttribute.value[ face.a ];
  10965. v2 = customAttribute.value[ face.b ];
  10966. v3 = customAttribute.value[ face.c ];
  10967. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10968. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10969. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10970. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10971. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10972. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10973. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10974. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10975. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10976. offset_custom += 9;
  10977. }
  10978. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10979. face = obj_faces[ chunk_faces4[ f ] ];
  10980. v1 = customAttribute.value[ face.a ];
  10981. v2 = customAttribute.value[ face.b ];
  10982. v3 = customAttribute.value[ face.c ];
  10983. v4 = customAttribute.value[ face.d ];
  10984. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10985. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10986. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10987. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10988. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10989. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10990. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10991. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10992. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10993. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10994. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10995. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10996. offset_custom += 12;
  10997. }
  10998. } else if ( customAttribute.boundTo === "faces" ) {
  10999. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11000. value = customAttribute.value[ chunk_faces3[ f ] ];
  11001. v1 = value;
  11002. v2 = value;
  11003. v3 = value;
  11004. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11005. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11006. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11007. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11008. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11009. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11010. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11011. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11012. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11013. offset_custom += 9;
  11014. }
  11015. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11016. value = customAttribute.value[ chunk_faces4[ f ] ];
  11017. v1 = value;
  11018. v2 = value;
  11019. v3 = value;
  11020. v4 = value;
  11021. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11022. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11023. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11024. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11025. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11026. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11027. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11028. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11029. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11030. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11031. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11032. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11033. offset_custom += 12;
  11034. }
  11035. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11036. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11037. value = customAttribute.value[ chunk_faces3[ f ] ];
  11038. v1 = value[ 0 ];
  11039. v2 = value[ 1 ];
  11040. v3 = value[ 2 ];
  11041. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11042. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11043. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11044. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11045. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11046. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11047. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11048. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11049. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11050. offset_custom += 9;
  11051. }
  11052. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11053. value = customAttribute.value[ chunk_faces4[ f ] ];
  11054. v1 = value[ 0 ];
  11055. v2 = value[ 1 ];
  11056. v3 = value[ 2 ];
  11057. v4 = value[ 3 ];
  11058. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11059. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11060. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11061. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11062. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11063. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11064. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11065. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11066. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11067. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11068. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11069. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11070. offset_custom += 12;
  11071. }
  11072. }
  11073. } else if ( customAttribute.size === 4 ) {
  11074. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11075. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11076. face = obj_faces[ chunk_faces3[ f ] ];
  11077. v1 = customAttribute.value[ face.a ];
  11078. v2 = customAttribute.value[ face.b ];
  11079. v3 = customAttribute.value[ face.c ];
  11080. customAttribute.array[ offset_custom ] = v1.x;
  11081. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11082. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11083. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11084. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11085. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11086. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11087. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11088. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11089. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11090. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11091. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11092. offset_custom += 12;
  11093. }
  11094. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11095. face = obj_faces[ chunk_faces4[ f ] ];
  11096. v1 = customAttribute.value[ face.a ];
  11097. v2 = customAttribute.value[ face.b ];
  11098. v3 = customAttribute.value[ face.c ];
  11099. v4 = customAttribute.value[ face.d ];
  11100. customAttribute.array[ offset_custom ] = v1.x;
  11101. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11102. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11103. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11104. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11105. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11106. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11107. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11108. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11109. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11110. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11111. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11112. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11113. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11114. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11115. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11116. offset_custom += 16;
  11117. }
  11118. } else if ( customAttribute.boundTo === "faces" ) {
  11119. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11120. value = customAttribute.value[ chunk_faces3[ f ] ];
  11121. v1 = value;
  11122. v2 = value;
  11123. v3 = value;
  11124. customAttribute.array[ offset_custom ] = v1.x;
  11125. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11126. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11127. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11128. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11129. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11130. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11131. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11132. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11133. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11134. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11135. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11136. offset_custom += 12;
  11137. }
  11138. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11139. value = customAttribute.value[ chunk_faces4[ f ] ];
  11140. v1 = value;
  11141. v2 = value;
  11142. v3 = value;
  11143. v4 = value;
  11144. customAttribute.array[ offset_custom ] = v1.x;
  11145. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11146. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11147. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11148. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11149. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11150. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11151. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11152. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11153. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11154. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11155. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11156. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11157. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11158. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11159. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11160. offset_custom += 16;
  11161. }
  11162. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11163. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11164. value = customAttribute.value[ chunk_faces3[ f ] ];
  11165. v1 = value[ 0 ];
  11166. v2 = value[ 1 ];
  11167. v3 = value[ 2 ];
  11168. customAttribute.array[ offset_custom ] = v1.x;
  11169. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11170. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11171. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11172. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11173. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11174. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11175. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11176. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11177. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11178. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11179. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11180. offset_custom += 12;
  11181. }
  11182. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11183. value = customAttribute.value[ chunk_faces4[ f ] ];
  11184. v1 = value[ 0 ];
  11185. v2 = value[ 1 ];
  11186. v3 = value[ 2 ];
  11187. v4 = value[ 3 ];
  11188. customAttribute.array[ offset_custom ] = v1.x;
  11189. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11190. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11191. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11192. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11193. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11194. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11195. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11196. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11197. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11198. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11199. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11200. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11201. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11202. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11203. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11204. offset_custom += 16;
  11205. }
  11206. }
  11207. }
  11208. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11209. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11210. }
  11211. }
  11212. if ( dispose ) {
  11213. delete geometryGroup.__inittedArrays;
  11214. delete geometryGroup.__colorArray;
  11215. delete geometryGroup.__normalArray;
  11216. delete geometryGroup.__tangentArray;
  11217. delete geometryGroup.__uvArray;
  11218. delete geometryGroup.__uv2Array;
  11219. delete geometryGroup.__faceArray;
  11220. delete geometryGroup.__vertexArray;
  11221. delete geometryGroup.__lineArray;
  11222. delete geometryGroup.__skinIndexArray;
  11223. delete geometryGroup.__skinWeightArray;
  11224. }
  11225. };
  11226. function setDirectBuffers ( geometry, hint, dispose ) {
  11227. var attributes = geometry.attributes;
  11228. var index = attributes[ "index" ];
  11229. var position = attributes[ "position" ];
  11230. var normal = attributes[ "normal" ];
  11231. var uv = attributes[ "uv" ];
  11232. var color = attributes[ "color" ];
  11233. var tangent = attributes[ "tangent" ];
  11234. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  11235. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11236. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  11237. }
  11238. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  11239. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11240. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  11241. }
  11242. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  11243. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11244. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  11245. }
  11246. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  11247. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11248. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  11249. }
  11250. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  11251. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11252. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  11253. }
  11254. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  11255. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11256. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  11257. }
  11258. if ( dispose ) {
  11259. for ( var i in geometry.attributes ) {
  11260. delete geometry.attributes[ i ].array;
  11261. }
  11262. }
  11263. };
  11264. // Buffer rendering
  11265. this.renderBufferImmediate = function ( object, program, material ) {
  11266. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11267. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11268. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11269. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11270. if ( object.hasPositions ) {
  11271. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11272. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11273. _gl.enableVertexAttribArray( program.attributes.position );
  11274. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11275. }
  11276. if ( object.hasNormals ) {
  11277. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11278. if ( material.shading === THREE.FlatShading ) {
  11279. var nx, ny, nz,
  11280. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11281. normalArray,
  11282. i, il = object.count * 3;
  11283. for( i = 0; i < il; i += 9 ) {
  11284. normalArray = object.normalArray;
  11285. nax = normalArray[ i ];
  11286. nay = normalArray[ i + 1 ];
  11287. naz = normalArray[ i + 2 ];
  11288. nbx = normalArray[ i + 3 ];
  11289. nby = normalArray[ i + 4 ];
  11290. nbz = normalArray[ i + 5 ];
  11291. ncx = normalArray[ i + 6 ];
  11292. ncy = normalArray[ i + 7 ];
  11293. ncz = normalArray[ i + 8 ];
  11294. nx = ( nax + nbx + ncx ) / 3;
  11295. ny = ( nay + nby + ncy ) / 3;
  11296. nz = ( naz + nbz + ncz ) / 3;
  11297. normalArray[ i ] = nx;
  11298. normalArray[ i + 1 ] = ny;
  11299. normalArray[ i + 2 ] = nz;
  11300. normalArray[ i + 3 ] = nx;
  11301. normalArray[ i + 4 ] = ny;
  11302. normalArray[ i + 5 ] = nz;
  11303. normalArray[ i + 6 ] = nx;
  11304. normalArray[ i + 7 ] = ny;
  11305. normalArray[ i + 8 ] = nz;
  11306. }
  11307. }
  11308. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11309. _gl.enableVertexAttribArray( program.attributes.normal );
  11310. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11311. }
  11312. if ( object.hasUvs && material.map ) {
  11313. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11314. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11315. _gl.enableVertexAttribArray( program.attributes.uv );
  11316. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11317. }
  11318. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11319. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11320. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11321. _gl.enableVertexAttribArray( program.attributes.color );
  11322. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11323. }
  11324. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11325. object.count = 0;
  11326. };
  11327. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  11328. if ( material.visible === false ) return;
  11329. var program, attributes, linewidth, primitives, a, attribute;
  11330. program = setProgram( camera, lights, fog, material, object );
  11331. attributes = program.attributes;
  11332. var updateBuffers = false,
  11333. wireframeBit = material.wireframe ? 1 : 0,
  11334. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11335. if ( geometryHash !== _currentGeometryGroupHash ) {
  11336. _currentGeometryGroupHash = geometryHash;
  11337. updateBuffers = true;
  11338. }
  11339. // render mesh
  11340. if ( object instanceof THREE.Mesh ) {
  11341. var offsets = geometry.offsets;
  11342. // if there is more than 1 chunk
  11343. // must set attribute pointers to use new offsets for each chunk
  11344. // even if geometry and materials didn't change
  11345. if ( offsets.length > 1 ) updateBuffers = true;
  11346. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  11347. var startIndex = offsets[ i ].index;
  11348. if ( updateBuffers ) {
  11349. // vertices
  11350. var position = geometry.attributes[ "position" ];
  11351. var positionSize = position.itemSize;
  11352. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11353. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  11354. // normals
  11355. var normal = geometry.attributes[ "normal" ];
  11356. if ( attributes.normal >= 0 && normal ) {
  11357. var normalSize = normal.itemSize;
  11358. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11359. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  11360. }
  11361. // uvs
  11362. var uv = geometry.attributes[ "uv" ];
  11363. if ( attributes.uv >= 0 && uv ) {
  11364. if ( uv.buffer ) {
  11365. var uvSize = uv.itemSize;
  11366. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11367. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  11368. _gl.enableVertexAttribArray( attributes.uv );
  11369. } else {
  11370. _gl.disableVertexAttribArray( attributes.uv );
  11371. }
  11372. }
  11373. // colors
  11374. var color = geometry.attributes[ "color" ];
  11375. if ( attributes.color >= 0 && color ) {
  11376. var colorSize = color.itemSize;
  11377. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11378. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  11379. }
  11380. // tangents
  11381. var tangent = geometry.attributes[ "tangent" ];
  11382. if ( attributes.tangent >= 0 && tangent ) {
  11383. var tangentSize = tangent.itemSize;
  11384. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11385. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  11386. }
  11387. // indices
  11388. var index = geometry.attributes[ "index" ];
  11389. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11390. }
  11391. // render indexed triangles
  11392. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  11393. _this.info.render.calls ++;
  11394. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11395. _this.info.render.faces += offsets[ i ].count / 3;
  11396. }
  11397. // render particles
  11398. } else if ( object instanceof THREE.ParticleSystem ) {
  11399. if ( updateBuffers ) {
  11400. // vertices
  11401. var position = geometry.attributes[ "position" ];
  11402. var positionSize = position.itemSize;
  11403. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11404. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11405. // colors
  11406. var color = geometry.attributes[ "color" ];
  11407. if ( attributes.color >= 0 && color ) {
  11408. var colorSize = color.itemSize;
  11409. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11410. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11411. }
  11412. // render particles
  11413. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  11414. _this.info.render.calls ++;
  11415. _this.info.render.points += position.numItems / 3;
  11416. }
  11417. }
  11418. };
  11419. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11420. if ( material.visible === false ) return;
  11421. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11422. program = setProgram( camera, lights, fog, material, object );
  11423. attributes = program.attributes;
  11424. var updateBuffers = false,
  11425. wireframeBit = material.wireframe ? 1 : 0,
  11426. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11427. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11428. _currentGeometryGroupHash = geometryGroupHash;
  11429. updateBuffers = true;
  11430. }
  11431. // vertices
  11432. if ( !material.morphTargets && attributes.position >= 0 ) {
  11433. if ( updateBuffers ) {
  11434. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11435. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11436. }
  11437. } else {
  11438. if ( object.morphTargetBase ) {
  11439. setupMorphTargets( material, geometryGroup, object );
  11440. }
  11441. }
  11442. if ( updateBuffers ) {
  11443. // custom attributes
  11444. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11445. if ( geometryGroup.__webglCustomAttributesList ) {
  11446. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11447. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11448. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11449. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  11450. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  11451. }
  11452. }
  11453. }
  11454. // colors
  11455. if ( attributes.color >= 0 ) {
  11456. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11457. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11458. }
  11459. // normals
  11460. if ( attributes.normal >= 0 ) {
  11461. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11462. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11463. }
  11464. // tangents
  11465. if ( attributes.tangent >= 0 ) {
  11466. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11467. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  11468. }
  11469. // uvs
  11470. if ( attributes.uv >= 0 ) {
  11471. if ( geometryGroup.__webglUVBuffer ) {
  11472. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11473. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11474. _gl.enableVertexAttribArray( attributes.uv );
  11475. } else {
  11476. _gl.disableVertexAttribArray( attributes.uv );
  11477. }
  11478. }
  11479. if ( attributes.uv2 >= 0 ) {
  11480. if ( geometryGroup.__webglUV2Buffer ) {
  11481. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11482. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  11483. _gl.enableVertexAttribArray( attributes.uv2 );
  11484. } else {
  11485. _gl.disableVertexAttribArray( attributes.uv2 );
  11486. }
  11487. }
  11488. if ( material.skinning &&
  11489. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11490. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11491. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  11492. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11493. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  11494. }
  11495. // line distances
  11496. if ( attributes.lineDistance >= 0 ) {
  11497. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  11498. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  11499. }
  11500. }
  11501. // render mesh
  11502. if ( object instanceof THREE.Mesh ) {
  11503. // wireframe
  11504. if ( material.wireframe ) {
  11505. setLineWidth( material.wireframeLinewidth );
  11506. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11507. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  11508. // triangles
  11509. } else {
  11510. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11511. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  11512. }
  11513. _this.info.render.calls ++;
  11514. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11515. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11516. // render lines
  11517. } else if ( object instanceof THREE.Line ) {
  11518. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11519. setLineWidth( material.linewidth );
  11520. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11521. _this.info.render.calls ++;
  11522. // render particles
  11523. } else if ( object instanceof THREE.ParticleSystem ) {
  11524. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11525. _this.info.render.calls ++;
  11526. _this.info.render.points += geometryGroup.__webglParticleCount;
  11527. // render ribbon
  11528. } else if ( object instanceof THREE.Ribbon ) {
  11529. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11530. _this.info.render.calls ++;
  11531. }
  11532. };
  11533. function setupMorphTargets ( material, geometryGroup, object ) {
  11534. // set base
  11535. var attributes = material.program.attributes;
  11536. if ( object.morphTargetBase !== -1 ) {
  11537. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11538. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11539. } else if ( attributes.position >= 0 ) {
  11540. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11541. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11542. }
  11543. if ( object.morphTargetForcedOrder.length ) {
  11544. // set forced order
  11545. var m = 0;
  11546. var order = object.morphTargetForcedOrder;
  11547. var influences = object.morphTargetInfluences;
  11548. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11549. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11550. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11551. if ( material.morphNormals ) {
  11552. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11553. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11554. }
  11555. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11556. m ++;
  11557. }
  11558. } else {
  11559. // find the most influencing
  11560. var influence, activeInfluenceIndices = [];
  11561. var influences = object.morphTargetInfluences;
  11562. var i, il = influences.length;
  11563. for ( i = 0; i < il; i ++ ) {
  11564. influence = influences[ i ];
  11565. if ( influence > 0 ) {
  11566. activeInfluenceIndices.push( [ i, influence ] );
  11567. }
  11568. }
  11569. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11570. activeInfluenceIndices.sort( numericalSort );
  11571. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11572. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11573. activeInfluenceIndices.sort( numericalSort );
  11574. } else if ( activeInfluenceIndices.length === 0 ) {
  11575. activeInfluenceIndices.push( [ 0, 0 ] );
  11576. };
  11577. var influenceIndex, m = 0;
  11578. while ( m < material.numSupportedMorphTargets ) {
  11579. if ( activeInfluenceIndices[ m ] ) {
  11580. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11581. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11582. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11583. if ( material.morphNormals ) {
  11584. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11585. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11586. }
  11587. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11588. } else {
  11589. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11590. if ( material.morphNormals ) {
  11591. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11592. }
  11593. object.__webglMorphTargetInfluences[ m ] = 0;
  11594. }
  11595. m ++;
  11596. }
  11597. }
  11598. // load updated influences uniform
  11599. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11600. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11601. }
  11602. };
  11603. // Sorting
  11604. function painterSortStable ( a, b ) {
  11605. if ( a.z !== b.z ) {
  11606. return b.z - a.z;
  11607. } else {
  11608. return b.id - a.id;
  11609. }
  11610. };
  11611. function numericalSort ( a, b ) {
  11612. return b[ 1 ] - a[ 1 ];
  11613. };
  11614. // Rendering
  11615. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11616. if ( camera instanceof THREE.Camera === false ) {
  11617. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11618. return;
  11619. }
  11620. var i, il,
  11621. webglObject, object,
  11622. renderList,
  11623. lights = scene.__lights,
  11624. fog = scene.fog;
  11625. // reset caching for this frame
  11626. _currentMaterialId = -1;
  11627. _lightsNeedUpdate = true;
  11628. // update scene graph
  11629. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11630. // update camera matrices and frustum
  11631. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11632. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11633. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11634. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11635. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11636. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11637. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11638. _frustum.setFromMatrix( _projScreenMatrix );
  11639. // update WebGL objects
  11640. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11641. // custom render plugins (pre pass)
  11642. renderPlugins( this.renderPluginsPre, scene, camera );
  11643. //
  11644. _this.info.render.calls = 0;
  11645. _this.info.render.vertices = 0;
  11646. _this.info.render.faces = 0;
  11647. _this.info.render.points = 0;
  11648. this.setRenderTarget( renderTarget );
  11649. if ( this.autoClear || forceClear ) {
  11650. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11651. }
  11652. // set matrices for regular objects (frustum culled)
  11653. renderList = scene.__webglObjects;
  11654. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11655. webglObject = renderList[ i ];
  11656. object = webglObject.object;
  11657. webglObject.render = false;
  11658. if ( object.visible ) {
  11659. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11660. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11661. setupMatrices( object, camera );
  11662. unrollBufferMaterial( webglObject );
  11663. webglObject.render = true;
  11664. if ( this.sortObjects === true ) {
  11665. if ( object.renderDepth !== null ) {
  11666. webglObject.z = object.renderDepth;
  11667. } else {
  11668. _vector3.copy( object.matrixWorld.getPosition() );
  11669. _projScreenMatrix.multiplyVector3( _vector3 );
  11670. webglObject.z = _vector3.z;
  11671. }
  11672. webglObject.id = object.id;
  11673. }
  11674. }
  11675. }
  11676. }
  11677. if ( this.sortObjects ) {
  11678. renderList.sort( painterSortStable );
  11679. }
  11680. // set matrices for immediate objects
  11681. renderList = scene.__webglObjectsImmediate;
  11682. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11683. webglObject = renderList[ i ];
  11684. object = webglObject.object;
  11685. if ( object.visible ) {
  11686. /*
  11687. if ( object.matrixAutoUpdate ) {
  11688. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11689. }
  11690. */
  11691. setupMatrices( object, camera );
  11692. unrollImmediateBufferMaterial( webglObject );
  11693. }
  11694. }
  11695. if ( scene.overrideMaterial ) {
  11696. var material = scene.overrideMaterial;
  11697. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11698. this.setDepthTest( material.depthTest );
  11699. this.setDepthWrite( material.depthWrite );
  11700. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11701. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11702. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11703. } else {
  11704. // opaque pass (front-to-back order)
  11705. this.setBlending( THREE.NormalBlending );
  11706. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  11707. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  11708. // transparent pass (back-to-front order)
  11709. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  11710. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  11711. }
  11712. // custom render plugins (post pass)
  11713. renderPlugins( this.renderPluginsPost, scene, camera );
  11714. // Generate mipmap if we're using any kind of mipmap filtering
  11715. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11716. updateRenderTargetMipmap( renderTarget );
  11717. }
  11718. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11719. this.setDepthTest( true );
  11720. this.setDepthWrite( true );
  11721. // _gl.finish();
  11722. };
  11723. function renderPlugins( plugins, scene, camera ) {
  11724. if ( ! plugins.length ) return;
  11725. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11726. // reset state for plugin (to start from clean slate)
  11727. _currentProgram = null;
  11728. _currentCamera = null;
  11729. _oldBlending = -1;
  11730. _oldDepthTest = -1;
  11731. _oldDepthWrite = -1;
  11732. _oldDoubleSided = -1;
  11733. _oldFlipSided = -1;
  11734. _currentGeometryGroupHash = -1;
  11735. _currentMaterialId = -1;
  11736. _lightsNeedUpdate = true;
  11737. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11738. // reset state after plugin (anything could have changed)
  11739. _currentProgram = null;
  11740. _currentCamera = null;
  11741. _oldBlending = -1;
  11742. _oldDepthTest = -1;
  11743. _oldDepthWrite = -1;
  11744. _oldDoubleSided = -1;
  11745. _oldFlipSided = -1;
  11746. _currentGeometryGroupHash = -1;
  11747. _currentMaterialId = -1;
  11748. _lightsNeedUpdate = true;
  11749. }
  11750. };
  11751. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11752. var webglObject, object, buffer, material, start, end, delta;
  11753. if ( reverse ) {
  11754. start = renderList.length - 1;
  11755. end = -1;
  11756. delta = -1;
  11757. } else {
  11758. start = 0;
  11759. end = renderList.length;
  11760. delta = 1;
  11761. }
  11762. for ( var i = start; i !== end; i += delta ) {
  11763. webglObject = renderList[ i ];
  11764. if ( webglObject.render ) {
  11765. object = webglObject.object;
  11766. buffer = webglObject.buffer;
  11767. if ( overrideMaterial ) {
  11768. material = overrideMaterial;
  11769. } else {
  11770. material = webglObject[ materialType ];
  11771. if ( ! material ) continue;
  11772. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11773. _this.setDepthTest( material.depthTest );
  11774. _this.setDepthWrite( material.depthWrite );
  11775. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11776. }
  11777. _this.setMaterialFaces( material );
  11778. if ( buffer instanceof THREE.BufferGeometry ) {
  11779. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11780. } else {
  11781. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11782. }
  11783. }
  11784. }
  11785. };
  11786. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11787. var webglObject, object, material, program;
  11788. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11789. webglObject = renderList[ i ];
  11790. object = webglObject.object;
  11791. if ( object.visible ) {
  11792. if ( overrideMaterial ) {
  11793. material = overrideMaterial;
  11794. } else {
  11795. material = webglObject[ materialType ];
  11796. if ( ! material ) continue;
  11797. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11798. _this.setDepthTest( material.depthTest );
  11799. _this.setDepthWrite( material.depthWrite );
  11800. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11801. }
  11802. _this.renderImmediateObject( camera, lights, fog, material, object );
  11803. }
  11804. }
  11805. };
  11806. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11807. var program = setProgram( camera, lights, fog, material, object );
  11808. _currentGeometryGroupHash = -1;
  11809. _this.setMaterialFaces( material );
  11810. if ( object.immediateRenderCallback ) {
  11811. object.immediateRenderCallback( program, _gl, _frustum );
  11812. } else {
  11813. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11814. }
  11815. };
  11816. function unrollImmediateBufferMaterial ( globject ) {
  11817. var object = globject.object,
  11818. material = object.material;
  11819. if ( material.transparent ) {
  11820. globject.transparent = material;
  11821. globject.opaque = null;
  11822. } else {
  11823. globject.opaque = material;
  11824. globject.transparent = null;
  11825. }
  11826. };
  11827. function unrollBufferMaterial ( globject ) {
  11828. var object = globject.object,
  11829. buffer = globject.buffer,
  11830. material, materialIndex, meshMaterial;
  11831. meshMaterial = object.material;
  11832. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11833. materialIndex = buffer.materialIndex;
  11834. if ( materialIndex >= 0 ) {
  11835. material = meshMaterial.materials[ materialIndex ];
  11836. if ( material.transparent ) {
  11837. globject.transparent = material;
  11838. globject.opaque = null;
  11839. } else {
  11840. globject.opaque = material;
  11841. globject.transparent = null;
  11842. }
  11843. }
  11844. } else {
  11845. material = meshMaterial;
  11846. if ( material ) {
  11847. if ( material.transparent ) {
  11848. globject.transparent = material;
  11849. globject.opaque = null;
  11850. } else {
  11851. globject.opaque = material;
  11852. globject.transparent = null;
  11853. }
  11854. }
  11855. }
  11856. };
  11857. // Geometry splitting
  11858. function sortFacesByMaterial ( geometry, material ) {
  11859. var f, fl, face, materialIndex, vertices,
  11860. materialHash, groupHash,
  11861. hash_map = {};
  11862. var numMorphTargets = geometry.morphTargets.length;
  11863. var numMorphNormals = geometry.morphNormals.length;
  11864. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  11865. geometry.geometryGroups = {};
  11866. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11867. face = geometry.faces[ f ];
  11868. materialIndex = usesFaceMaterial ? face.materialIndex : undefined;
  11869. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  11870. if ( hash_map[ materialHash ] === undefined ) {
  11871. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  11872. }
  11873. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11874. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11875. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11876. }
  11877. vertices = face instanceof THREE.Face3 ? 3 : 4;
  11878. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  11879. hash_map[ materialHash ].counter += 1;
  11880. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11881. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11882. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11883. }
  11884. }
  11885. if ( face instanceof THREE.Face3 ) {
  11886. geometry.geometryGroups[ groupHash ].faces3.push( f );
  11887. } else {
  11888. geometry.geometryGroups[ groupHash ].faces4.push( f );
  11889. }
  11890. geometry.geometryGroups[ groupHash ].vertices += vertices;
  11891. }
  11892. geometry.geometryGroupsList = [];
  11893. for ( var g in geometry.geometryGroups ) {
  11894. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  11895. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  11896. }
  11897. };
  11898. // Objects refresh
  11899. this.initWebGLObjects = function ( scene ) {
  11900. if ( !scene.__webglObjects ) {
  11901. scene.__webglObjects = [];
  11902. scene.__webglObjectsImmediate = [];
  11903. scene.__webglSprites = [];
  11904. scene.__webglFlares = [];
  11905. }
  11906. while ( scene.__objectsAdded.length ) {
  11907. addObject( scene.__objectsAdded[ 0 ], scene );
  11908. scene.__objectsAdded.splice( 0, 1 );
  11909. }
  11910. while ( scene.__objectsRemoved.length ) {
  11911. removeObject( scene.__objectsRemoved[ 0 ], scene );
  11912. scene.__objectsRemoved.splice( 0, 1 );
  11913. }
  11914. // update must be called after objects adding / removal
  11915. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  11916. updateObject( scene.__webglObjects[ o ].object );
  11917. }
  11918. };
  11919. // Objects adding
  11920. function addObject ( object, scene ) {
  11921. var g, geometry, material, geometryGroup;
  11922. if ( ! object.__webglInit ) {
  11923. object.__webglInit = true;
  11924. object._modelViewMatrix = new THREE.Matrix4();
  11925. object._normalMatrix = new THREE.Matrix3();
  11926. if ( object instanceof THREE.Mesh ) {
  11927. geometry = object.geometry;
  11928. material = object.material;
  11929. if ( geometry instanceof THREE.Geometry ) {
  11930. if ( geometry.geometryGroups === undefined ) {
  11931. sortFacesByMaterial( geometry, material );
  11932. }
  11933. // create separate VBOs per geometry chunk
  11934. for ( g in geometry.geometryGroups ) {
  11935. geometryGroup = geometry.geometryGroups[ g ];
  11936. // initialise VBO on the first access
  11937. if ( ! geometryGroup.__webglVertexBuffer ) {
  11938. createMeshBuffers( geometryGroup );
  11939. initMeshBuffers( geometryGroup, object );
  11940. geometry.verticesNeedUpdate = true;
  11941. geometry.morphTargetsNeedUpdate = true;
  11942. geometry.elementsNeedUpdate = true;
  11943. geometry.uvsNeedUpdate = true;
  11944. geometry.normalsNeedUpdate = true;
  11945. geometry.tangentsNeedUpdate = true;
  11946. geometry.colorsNeedUpdate = true;
  11947. }
  11948. }
  11949. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11950. initDirectBuffers( geometry );
  11951. }
  11952. } else if ( object instanceof THREE.Ribbon ) {
  11953. geometry = object.geometry;
  11954. if ( ! geometry.__webglVertexBuffer ) {
  11955. createRibbonBuffers( geometry );
  11956. initRibbonBuffers( geometry, object );
  11957. geometry.verticesNeedUpdate = true;
  11958. geometry.colorsNeedUpdate = true;
  11959. geometry.normalsNeedUpdate = true;
  11960. }
  11961. } else if ( object instanceof THREE.Line ) {
  11962. geometry = object.geometry;
  11963. if ( ! geometry.__webglVertexBuffer ) {
  11964. createLineBuffers( geometry );
  11965. initLineBuffers( geometry, object );
  11966. geometry.verticesNeedUpdate = true;
  11967. geometry.colorsNeedUpdate = true;
  11968. geometry.lineDistancesNeedUpdate = true;
  11969. }
  11970. } else if ( object instanceof THREE.ParticleSystem ) {
  11971. geometry = object.geometry;
  11972. if ( ! geometry.__webglVertexBuffer ) {
  11973. if ( geometry instanceof THREE.Geometry ) {
  11974. createParticleBuffers( geometry );
  11975. initParticleBuffers( geometry, object );
  11976. geometry.verticesNeedUpdate = true;
  11977. geometry.colorsNeedUpdate = true;
  11978. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11979. initDirectBuffers( geometry );
  11980. }
  11981. }
  11982. }
  11983. }
  11984. if ( ! object.__webglActive ) {
  11985. if ( object instanceof THREE.Mesh ) {
  11986. geometry = object.geometry;
  11987. if ( geometry instanceof THREE.BufferGeometry ) {
  11988. addBuffer( scene.__webglObjects, geometry, object );
  11989. } else {
  11990. for ( g in geometry.geometryGroups ) {
  11991. geometryGroup = geometry.geometryGroups[ g ];
  11992. addBuffer( scene.__webglObjects, geometryGroup, object );
  11993. }
  11994. }
  11995. } else if ( object instanceof THREE.Ribbon ||
  11996. object instanceof THREE.Line ||
  11997. object instanceof THREE.ParticleSystem ) {
  11998. geometry = object.geometry;
  11999. addBuffer( scene.__webglObjects, geometry, object );
  12000. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12001. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12002. } else if ( object instanceof THREE.Sprite ) {
  12003. scene.__webglSprites.push( object );
  12004. } else if ( object instanceof THREE.LensFlare ) {
  12005. scene.__webglFlares.push( object );
  12006. }
  12007. object.__webglActive = true;
  12008. }
  12009. };
  12010. function addBuffer ( objlist, buffer, object ) {
  12011. objlist.push(
  12012. {
  12013. buffer: buffer,
  12014. object: object,
  12015. opaque: null,
  12016. transparent: null
  12017. }
  12018. );
  12019. };
  12020. function addBufferImmediate ( objlist, object ) {
  12021. objlist.push(
  12022. {
  12023. object: object,
  12024. opaque: null,
  12025. transparent: null
  12026. }
  12027. );
  12028. };
  12029. // Objects updates
  12030. function updateObject ( object ) {
  12031. var geometry = object.geometry,
  12032. geometryGroup, customAttributesDirty, material;
  12033. if ( object instanceof THREE.Mesh ) {
  12034. if ( geometry instanceof THREE.BufferGeometry ) {
  12035. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12036. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12037. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12038. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12039. }
  12040. geometry.verticesNeedUpdate = false;
  12041. geometry.elementsNeedUpdate = false;
  12042. geometry.uvsNeedUpdate = false;
  12043. geometry.normalsNeedUpdate = false;
  12044. geometry.colorsNeedUpdate = false;
  12045. geometry.tangentsNeedUpdate = false;
  12046. } else {
  12047. // check all geometry groups
  12048. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12049. geometryGroup = geometry.geometryGroupsList[ i ];
  12050. material = getBufferMaterial( object, geometryGroup );
  12051. if ( geometry.buffersNeedUpdate ) {
  12052. initMeshBuffers( geometryGroup, object );
  12053. }
  12054. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12055. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12056. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12057. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12058. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12059. }
  12060. }
  12061. geometry.verticesNeedUpdate = false;
  12062. geometry.morphTargetsNeedUpdate = false;
  12063. geometry.elementsNeedUpdate = false;
  12064. geometry.uvsNeedUpdate = false;
  12065. geometry.normalsNeedUpdate = false;
  12066. geometry.colorsNeedUpdate = false;
  12067. geometry.tangentsNeedUpdate = false;
  12068. geometry.buffersNeedUpdate = false;
  12069. material.attributes && clearCustomAttributes( material );
  12070. }
  12071. } else if ( object instanceof THREE.Ribbon ) {
  12072. material = getBufferMaterial( object, geometry );
  12073. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12074. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12075. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12076. }
  12077. geometry.verticesNeedUpdate = false;
  12078. geometry.colorsNeedUpdate = false;
  12079. geometry.normalsNeedUpdate = false;
  12080. material.attributes && clearCustomAttributes( material );
  12081. } else if ( object instanceof THREE.Line ) {
  12082. material = getBufferMaterial( object, geometry );
  12083. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12084. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12085. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12086. }
  12087. geometry.verticesNeedUpdate = false;
  12088. geometry.colorsNeedUpdate = false;
  12089. geometry.lineDistancesNeedUpdate = false;
  12090. material.attributes && clearCustomAttributes( material );
  12091. } else if ( object instanceof THREE.ParticleSystem ) {
  12092. if ( geometry instanceof THREE.BufferGeometry ) {
  12093. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12094. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12095. }
  12096. geometry.verticesNeedUpdate = false;
  12097. geometry.colorsNeedUpdate = false;
  12098. } else {
  12099. material = getBufferMaterial( object, geometry );
  12100. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12101. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12102. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12103. }
  12104. geometry.verticesNeedUpdate = false;
  12105. geometry.colorsNeedUpdate = false;
  12106. material.attributes && clearCustomAttributes( material );
  12107. }
  12108. }
  12109. };
  12110. // Objects updates - custom attributes check
  12111. function areCustomAttributesDirty ( material ) {
  12112. for ( var a in material.attributes ) {
  12113. if ( material.attributes[ a ].needsUpdate ) return true;
  12114. }
  12115. return false;
  12116. };
  12117. function clearCustomAttributes ( material ) {
  12118. for ( var a in material.attributes ) {
  12119. material.attributes[ a ].needsUpdate = false;
  12120. }
  12121. };
  12122. // Objects removal
  12123. function removeObject ( object, scene ) {
  12124. if ( object instanceof THREE.Mesh ||
  12125. object instanceof THREE.ParticleSystem ||
  12126. object instanceof THREE.Ribbon ||
  12127. object instanceof THREE.Line ) {
  12128. removeInstances( scene.__webglObjects, object );
  12129. } else if ( object instanceof THREE.Sprite ) {
  12130. removeInstancesDirect( scene.__webglSprites, object );
  12131. } else if ( object instanceof THREE.LensFlare ) {
  12132. removeInstancesDirect( scene.__webglFlares, object );
  12133. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12134. removeInstances( scene.__webglObjectsImmediate, object );
  12135. }
  12136. object.__webglActive = false;
  12137. };
  12138. function removeInstances ( objlist, object ) {
  12139. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12140. if ( objlist[ o ].object === object ) {
  12141. objlist.splice( o, 1 );
  12142. }
  12143. }
  12144. };
  12145. function removeInstancesDirect ( objlist, object ) {
  12146. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12147. if ( objlist[ o ] === object ) {
  12148. objlist.splice( o, 1 );
  12149. }
  12150. }
  12151. };
  12152. // Materials
  12153. this.initMaterial = function ( material, lights, fog, object ) {
  12154. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  12155. if ( material instanceof THREE.MeshDepthMaterial ) {
  12156. shaderID = 'depth';
  12157. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12158. shaderID = 'normal';
  12159. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12160. shaderID = 'basic';
  12161. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12162. shaderID = 'lambert';
  12163. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12164. shaderID = 'phong';
  12165. } else if ( material instanceof THREE.LineBasicMaterial ) {
  12166. shaderID = 'basic';
  12167. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12168. shaderID = 'dashed';
  12169. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12170. shaderID = 'particle_basic';
  12171. }
  12172. if ( shaderID ) {
  12173. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  12174. }
  12175. // heuristics to create shader parameters according to lights in the scene
  12176. // (not to blow over maxLights budget)
  12177. maxLightCount = allocateLights( lights );
  12178. maxShadows = allocateShadows( lights );
  12179. maxBones = allocateBones( object );
  12180. parameters = {
  12181. map: !!material.map,
  12182. envMap: !!material.envMap,
  12183. lightMap: !!material.lightMap,
  12184. bumpMap: !!material.bumpMap,
  12185. normalMap: !!material.normalMap,
  12186. specularMap: !!material.specularMap,
  12187. vertexColors: material.vertexColors,
  12188. fog: fog,
  12189. useFog: material.fog,
  12190. fogExp: fog instanceof THREE.FogExp2,
  12191. sizeAttenuation: material.sizeAttenuation,
  12192. skinning: material.skinning,
  12193. maxBones: maxBones,
  12194. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  12195. boneTextureWidth: object && object.boneTextureWidth,
  12196. boneTextureHeight: object && object.boneTextureHeight,
  12197. morphTargets: material.morphTargets,
  12198. morphNormals: material.morphNormals,
  12199. maxMorphTargets: this.maxMorphTargets,
  12200. maxMorphNormals: this.maxMorphNormals,
  12201. maxDirLights: maxLightCount.directional,
  12202. maxPointLights: maxLightCount.point,
  12203. maxSpotLights: maxLightCount.spot,
  12204. maxHemiLights: maxLightCount.hemi,
  12205. maxShadows: maxShadows,
  12206. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  12207. shadowMapSoft: this.shadowMapSoft,
  12208. shadowMapDebug: this.shadowMapDebug,
  12209. shadowMapCascade: this.shadowMapCascade,
  12210. alphaTest: material.alphaTest,
  12211. metal: material.metal,
  12212. perPixel: material.perPixel,
  12213. wrapAround: material.wrapAround,
  12214. doubleSided: material.side === THREE.DoubleSide,
  12215. flipSided: material.side === THREE.BackSide
  12216. };
  12217. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  12218. var attributes = material.program.attributes;
  12219. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  12220. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  12221. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  12222. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  12223. if ( attributes.lineDistance >= 0 ) _gl.enableVertexAttribArray( attributes.lineDistance );
  12224. if ( material.skinning &&
  12225. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12226. _gl.enableVertexAttribArray( attributes.skinIndex );
  12227. _gl.enableVertexAttribArray( attributes.skinWeight );
  12228. }
  12229. if ( material.attributes ) {
  12230. for ( a in material.attributes ) {
  12231. if ( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  12232. }
  12233. }
  12234. if ( material.morphTargets ) {
  12235. material.numSupportedMorphTargets = 0;
  12236. var id, base = "morphTarget";
  12237. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  12238. id = base + i;
  12239. if ( attributes[ id ] >= 0 ) {
  12240. _gl.enableVertexAttribArray( attributes[ id ] );
  12241. material.numSupportedMorphTargets ++;
  12242. }
  12243. }
  12244. }
  12245. if ( material.morphNormals ) {
  12246. material.numSupportedMorphNormals = 0;
  12247. var id, base = "morphNormal";
  12248. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  12249. id = base + i;
  12250. if ( attributes[ id ] >= 0 ) {
  12251. _gl.enableVertexAttribArray( attributes[ id ] );
  12252. material.numSupportedMorphNormals ++;
  12253. }
  12254. }
  12255. }
  12256. material.uniformsList = [];
  12257. for ( u in material.uniforms ) {
  12258. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  12259. }
  12260. };
  12261. function setMaterialShaders( material, shaders ) {
  12262. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  12263. material.vertexShader = shaders.vertexShader;
  12264. material.fragmentShader = shaders.fragmentShader;
  12265. };
  12266. function setProgram( camera, lights, fog, material, object ) {
  12267. _usedTextureUnits = 0;
  12268. if ( material.needsUpdate ) {
  12269. if ( material.program ) _this.deallocateMaterial( material );
  12270. _this.initMaterial( material, lights, fog, object );
  12271. material.needsUpdate = false;
  12272. }
  12273. if ( material.morphTargets ) {
  12274. if ( ! object.__webglMorphTargetInfluences ) {
  12275. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  12276. }
  12277. }
  12278. var refreshMaterial = false;
  12279. var program = material.program,
  12280. p_uniforms = program.uniforms,
  12281. m_uniforms = material.uniforms;
  12282. if ( program !== _currentProgram ) {
  12283. _gl.useProgram( program );
  12284. _currentProgram = program;
  12285. refreshMaterial = true;
  12286. }
  12287. if ( material.id !== _currentMaterialId ) {
  12288. _currentMaterialId = material.id;
  12289. refreshMaterial = true;
  12290. }
  12291. if ( refreshMaterial || camera !== _currentCamera ) {
  12292. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  12293. if ( camera !== _currentCamera ) _currentCamera = camera;
  12294. }
  12295. // skinning uniforms must be set even if material didn't change
  12296. // auto-setting of texture unit for bone texture must go before other textures
  12297. // not sure why, but otherwise weird things happen
  12298. if ( material.skinning ) {
  12299. if ( _supportsBoneTextures && object.useVertexTexture ) {
  12300. if ( p_uniforms.boneTexture !== null ) {
  12301. var textureUnit = getTextureUnit();
  12302. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12303. _this.setTexture( object.boneTexture, textureUnit );
  12304. }
  12305. } else {
  12306. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12307. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  12308. }
  12309. }
  12310. }
  12311. if ( refreshMaterial ) {
  12312. // refresh uniforms common to several materials
  12313. if ( fog && material.fog ) {
  12314. refreshUniformsFog( m_uniforms, fog );
  12315. }
  12316. if ( material instanceof THREE.MeshPhongMaterial ||
  12317. material instanceof THREE.MeshLambertMaterial ||
  12318. material.lights ) {
  12319. if ( _lightsNeedUpdate ) {
  12320. setupLights( program, lights );
  12321. _lightsNeedUpdate = false;
  12322. }
  12323. refreshUniformsLights( m_uniforms, _lights );
  12324. }
  12325. if ( material instanceof THREE.MeshBasicMaterial ||
  12326. material instanceof THREE.MeshLambertMaterial ||
  12327. material instanceof THREE.MeshPhongMaterial ) {
  12328. refreshUniformsCommon( m_uniforms, material );
  12329. }
  12330. // refresh single material specific uniforms
  12331. if ( material instanceof THREE.LineBasicMaterial ) {
  12332. refreshUniformsLine( m_uniforms, material );
  12333. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12334. refreshUniformsLine( m_uniforms, material );
  12335. refreshUniformsDash( m_uniforms, material );
  12336. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12337. refreshUniformsParticle( m_uniforms, material );
  12338. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12339. refreshUniformsPhong( m_uniforms, material );
  12340. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12341. refreshUniformsLambert( m_uniforms, material );
  12342. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12343. m_uniforms.mNear.value = camera.near;
  12344. m_uniforms.mFar.value = camera.far;
  12345. m_uniforms.opacity.value = material.opacity;
  12346. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12347. m_uniforms.opacity.value = material.opacity;
  12348. }
  12349. if ( object.receiveShadow && ! material._shadowPass ) {
  12350. refreshUniformsShadow( m_uniforms, lights );
  12351. }
  12352. // load common uniforms
  12353. loadUniformsGeneric( program, material.uniformsList );
  12354. // load material specific uniforms
  12355. // (shader material also gets them for the sake of genericity)
  12356. if ( material instanceof THREE.ShaderMaterial ||
  12357. material instanceof THREE.MeshPhongMaterial ||
  12358. material.envMap ) {
  12359. if ( p_uniforms.cameraPosition !== null ) {
  12360. var position = camera.matrixWorld.getPosition();
  12361. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  12362. }
  12363. }
  12364. if ( material instanceof THREE.MeshPhongMaterial ||
  12365. material instanceof THREE.MeshLambertMaterial ||
  12366. material instanceof THREE.ShaderMaterial ||
  12367. material.skinning ) {
  12368. if ( p_uniforms.viewMatrix !== null ) {
  12369. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  12370. }
  12371. }
  12372. }
  12373. loadUniformsMatrices( p_uniforms, object );
  12374. if ( p_uniforms.modelMatrix !== null ) {
  12375. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12376. }
  12377. return program;
  12378. };
  12379. // Uniforms (refresh uniforms objects)
  12380. function refreshUniformsCommon ( uniforms, material ) {
  12381. uniforms.opacity.value = material.opacity;
  12382. if ( _this.gammaInput ) {
  12383. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12384. } else {
  12385. uniforms.diffuse.value = material.color;
  12386. }
  12387. uniforms.map.value = material.map;
  12388. uniforms.lightMap.value = material.lightMap;
  12389. uniforms.specularMap.value = material.specularMap;
  12390. if ( material.bumpMap ) {
  12391. uniforms.bumpMap.value = material.bumpMap;
  12392. uniforms.bumpScale.value = material.bumpScale;
  12393. }
  12394. if ( material.normalMap ) {
  12395. uniforms.normalMap.value = material.normalMap;
  12396. uniforms.normalScale.value.copy( material.normalScale );
  12397. }
  12398. // uv repeat and offset setting priorities
  12399. // 1. color map
  12400. // 2. specular map
  12401. // 3. normal map
  12402. // 4. bump map
  12403. var uvScaleMap;
  12404. if ( material.map ) {
  12405. uvScaleMap = material.map;
  12406. } else if ( material.specularMap ) {
  12407. uvScaleMap = material.specularMap;
  12408. } else if ( material.normalMap ) {
  12409. uvScaleMap = material.normalMap;
  12410. } else if ( material.bumpMap ) {
  12411. uvScaleMap = material.bumpMap;
  12412. }
  12413. if ( uvScaleMap !== undefined ) {
  12414. var offset = uvScaleMap.offset;
  12415. var repeat = uvScaleMap.repeat;
  12416. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12417. }
  12418. uniforms.envMap.value = material.envMap;
  12419. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12420. if ( _this.gammaInput ) {
  12421. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12422. uniforms.reflectivity.value = material.reflectivity;
  12423. } else {
  12424. uniforms.reflectivity.value = material.reflectivity;
  12425. }
  12426. uniforms.refractionRatio.value = material.refractionRatio;
  12427. uniforms.combine.value = material.combine;
  12428. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12429. };
  12430. function refreshUniformsLine ( uniforms, material ) {
  12431. uniforms.diffuse.value = material.color;
  12432. uniforms.opacity.value = material.opacity;
  12433. };
  12434. function refreshUniformsDash ( uniforms, material ) {
  12435. uniforms.dashSize.value = material.dashSize;
  12436. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12437. uniforms.scale.value = material.scale;
  12438. };
  12439. function refreshUniformsParticle ( uniforms, material ) {
  12440. uniforms.psColor.value = material.color;
  12441. uniforms.opacity.value = material.opacity;
  12442. uniforms.size.value = material.size;
  12443. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12444. uniforms.map.value = material.map;
  12445. };
  12446. function refreshUniformsFog ( uniforms, fog ) {
  12447. uniforms.fogColor.value = fog.color;
  12448. if ( fog instanceof THREE.Fog ) {
  12449. uniforms.fogNear.value = fog.near;
  12450. uniforms.fogFar.value = fog.far;
  12451. } else if ( fog instanceof THREE.FogExp2 ) {
  12452. uniforms.fogDensity.value = fog.density;
  12453. }
  12454. };
  12455. function refreshUniformsPhong ( uniforms, material ) {
  12456. uniforms.shininess.value = material.shininess;
  12457. if ( _this.gammaInput ) {
  12458. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12459. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12460. uniforms.specular.value.copyGammaToLinear( material.specular );
  12461. } else {
  12462. uniforms.ambient.value = material.ambient;
  12463. uniforms.emissive.value = material.emissive;
  12464. uniforms.specular.value = material.specular;
  12465. }
  12466. if ( material.wrapAround ) {
  12467. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12468. }
  12469. };
  12470. function refreshUniformsLambert ( uniforms, material ) {
  12471. if ( _this.gammaInput ) {
  12472. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12473. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12474. } else {
  12475. uniforms.ambient.value = material.ambient;
  12476. uniforms.emissive.value = material.emissive;
  12477. }
  12478. if ( material.wrapAround ) {
  12479. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12480. }
  12481. };
  12482. function refreshUniformsLights ( uniforms, lights ) {
  12483. uniforms.ambientLightColor.value = lights.ambient;
  12484. uniforms.directionalLightColor.value = lights.directional.colors;
  12485. uniforms.directionalLightDirection.value = lights.directional.positions;
  12486. uniforms.pointLightColor.value = lights.point.colors;
  12487. uniforms.pointLightPosition.value = lights.point.positions;
  12488. uniforms.pointLightDistance.value = lights.point.distances;
  12489. uniforms.spotLightColor.value = lights.spot.colors;
  12490. uniforms.spotLightPosition.value = lights.spot.positions;
  12491. uniforms.spotLightDistance.value = lights.spot.distances;
  12492. uniforms.spotLightDirection.value = lights.spot.directions;
  12493. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12494. uniforms.spotLightExponent.value = lights.spot.exponents;
  12495. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12496. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12497. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12498. };
  12499. function refreshUniformsShadow ( uniforms, lights ) {
  12500. if ( uniforms.shadowMatrix ) {
  12501. var j = 0;
  12502. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12503. var light = lights[ i ];
  12504. if ( ! light.castShadow ) continue;
  12505. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12506. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12507. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12508. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12509. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12510. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12511. j ++;
  12512. }
  12513. }
  12514. }
  12515. };
  12516. // Uniforms (load to GPU)
  12517. function loadUniformsMatrices ( uniforms, object ) {
  12518. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12519. if ( uniforms.normalMatrix ) {
  12520. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12521. }
  12522. };
  12523. function getTextureUnit() {
  12524. var textureUnit = _usedTextureUnits;
  12525. if ( textureUnit >= _maxTextures ) {
  12526. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  12527. }
  12528. _usedTextureUnits += 1;
  12529. return textureUnit;
  12530. };
  12531. function loadUniformsGeneric ( program, uniforms ) {
  12532. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12533. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12534. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12535. if ( !location ) continue;
  12536. uniform = uniforms[ j ][ 0 ];
  12537. type = uniform.type;
  12538. value = uniform.value;
  12539. if ( type === "i" ) { // single integer
  12540. _gl.uniform1i( location, value );
  12541. } else if ( type === "f" ) { // single float
  12542. _gl.uniform1f( location, value );
  12543. } else if ( type === "v2" ) { // single THREE.Vector2
  12544. _gl.uniform2f( location, value.x, value.y );
  12545. } else if ( type === "v3" ) { // single THREE.Vector3
  12546. _gl.uniform3f( location, value.x, value.y, value.z );
  12547. } else if ( type === "v4" ) { // single THREE.Vector4
  12548. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12549. } else if ( type === "c" ) { // single THREE.Color
  12550. _gl.uniform3f( location, value.r, value.g, value.b );
  12551. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12552. _gl.uniform1iv( location, value );
  12553. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12554. _gl.uniform3iv( location, value );
  12555. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12556. _gl.uniform1fv( location, value );
  12557. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12558. _gl.uniform3fv( location, value );
  12559. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12560. if ( uniform._array === undefined ) {
  12561. uniform._array = new Float32Array( 2 * value.length );
  12562. }
  12563. for ( i = 0, il = value.length; i < il; i ++ ) {
  12564. offset = i * 2;
  12565. uniform._array[ offset ] = value[ i ].x;
  12566. uniform._array[ offset + 1 ] = value[ i ].y;
  12567. }
  12568. _gl.uniform2fv( location, uniform._array );
  12569. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12570. if ( uniform._array === undefined ) {
  12571. uniform._array = new Float32Array( 3 * value.length );
  12572. }
  12573. for ( i = 0, il = value.length; i < il; i ++ ) {
  12574. offset = i * 3;
  12575. uniform._array[ offset ] = value[ i ].x;
  12576. uniform._array[ offset + 1 ] = value[ i ].y;
  12577. uniform._array[ offset + 2 ] = value[ i ].z;
  12578. }
  12579. _gl.uniform3fv( location, uniform._array );
  12580. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12581. if ( uniform._array === undefined ) {
  12582. uniform._array = new Float32Array( 4 * value.length );
  12583. }
  12584. for ( i = 0, il = value.length; i < il; i ++ ) {
  12585. offset = i * 4;
  12586. uniform._array[ offset ] = value[ i ].x;
  12587. uniform._array[ offset + 1 ] = value[ i ].y;
  12588. uniform._array[ offset + 2 ] = value[ i ].z;
  12589. uniform._array[ offset + 3 ] = value[ i ].w;
  12590. }
  12591. _gl.uniform4fv( location, uniform._array );
  12592. } else if ( type === "m4") { // single THREE.Matrix4
  12593. if ( uniform._array === undefined ) {
  12594. uniform._array = new Float32Array( 16 );
  12595. }
  12596. value.flattenToArray( uniform._array );
  12597. _gl.uniformMatrix4fv( location, false, uniform._array );
  12598. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12599. if ( uniform._array === undefined ) {
  12600. uniform._array = new Float32Array( 16 * value.length );
  12601. }
  12602. for ( i = 0, il = value.length; i < il; i ++ ) {
  12603. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12604. }
  12605. _gl.uniformMatrix4fv( location, false, uniform._array );
  12606. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12607. texture = value;
  12608. textureUnit = getTextureUnit();
  12609. _gl.uniform1i( location, textureUnit );
  12610. if ( !texture ) continue;
  12611. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12612. setCubeTexture( texture, textureUnit );
  12613. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12614. setCubeTextureDynamic( texture, textureUnit );
  12615. } else {
  12616. _this.setTexture( texture, textureUnit );
  12617. }
  12618. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12619. if ( uniform._array === undefined ) {
  12620. uniform._array = [];
  12621. }
  12622. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12623. uniform._array[ i ] = getTextureUnit();
  12624. }
  12625. _gl.uniform1iv( location, uniform._array );
  12626. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12627. texture = uniform.value[ i ];
  12628. textureUnit = uniform._array[ i ];
  12629. if ( !texture ) continue;
  12630. _this.setTexture( texture, textureUnit );
  12631. }
  12632. }
  12633. }
  12634. };
  12635. function setupMatrices ( object, camera ) {
  12636. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12637. object._normalMatrix.getInverse( object._modelViewMatrix );
  12638. object._normalMatrix.transpose();
  12639. };
  12640. //
  12641. function setColorGamma( array, offset, color, intensitySq ) {
  12642. array[ offset ] = color.r * color.r * intensitySq;
  12643. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12644. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12645. };
  12646. function setColorLinear( array, offset, color, intensity ) {
  12647. array[ offset ] = color.r * intensity;
  12648. array[ offset + 1 ] = color.g * intensity;
  12649. array[ offset + 2 ] = color.b * intensity;
  12650. };
  12651. function setupLights ( program, lights ) {
  12652. var l, ll, light, n,
  12653. r = 0, g = 0, b = 0,
  12654. color, skyColor, groundColor,
  12655. intensity, intensitySq,
  12656. position,
  12657. distance,
  12658. zlights = _lights,
  12659. dirColors = zlights.directional.colors,
  12660. dirPositions = zlights.directional.positions,
  12661. pointColors = zlights.point.colors,
  12662. pointPositions = zlights.point.positions,
  12663. pointDistances = zlights.point.distances,
  12664. spotColors = zlights.spot.colors,
  12665. spotPositions = zlights.spot.positions,
  12666. spotDistances = zlights.spot.distances,
  12667. spotDirections = zlights.spot.directions,
  12668. spotAnglesCos = zlights.spot.anglesCos,
  12669. spotExponents = zlights.spot.exponents,
  12670. hemiSkyColors = zlights.hemi.skyColors,
  12671. hemiGroundColors = zlights.hemi.groundColors,
  12672. hemiPositions = zlights.hemi.positions,
  12673. dirLength = 0,
  12674. pointLength = 0,
  12675. spotLength = 0,
  12676. hemiLength = 0,
  12677. dirCount = 0,
  12678. pointCount = 0,
  12679. spotCount = 0,
  12680. hemiCount = 0,
  12681. dirOffset = 0,
  12682. pointOffset = 0,
  12683. spotOffset = 0,
  12684. hemiOffset = 0;
  12685. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12686. light = lights[ l ];
  12687. if ( light.onlyShadow ) continue;
  12688. color = light.color;
  12689. intensity = light.intensity;
  12690. distance = light.distance;
  12691. if ( light instanceof THREE.AmbientLight ) {
  12692. if ( ! light.visible ) continue;
  12693. if ( _this.gammaInput ) {
  12694. r += color.r * color.r;
  12695. g += color.g * color.g;
  12696. b += color.b * color.b;
  12697. } else {
  12698. r += color.r;
  12699. g += color.g;
  12700. b += color.b;
  12701. }
  12702. } else if ( light instanceof THREE.DirectionalLight ) {
  12703. dirCount += 1;
  12704. if ( ! light.visible ) continue;
  12705. dirOffset = dirLength * 3;
  12706. if ( _this.gammaInput ) {
  12707. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12708. } else {
  12709. setColorLinear( dirColors, dirOffset, color, intensity );
  12710. }
  12711. _direction.copy( light.matrixWorld.getPosition() );
  12712. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12713. _direction.normalize();
  12714. dirPositions[ dirOffset ] = _direction.x;
  12715. dirPositions[ dirOffset + 1 ] = _direction.y;
  12716. dirPositions[ dirOffset + 2 ] = _direction.z;
  12717. dirLength += 1;
  12718. } else if ( light instanceof THREE.PointLight ) {
  12719. pointCount += 1;
  12720. if ( ! light.visible ) continue;
  12721. pointOffset = pointLength * 3;
  12722. if ( _this.gammaInput ) {
  12723. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12724. } else {
  12725. setColorLinear( pointColors, pointOffset, color, intensity );
  12726. }
  12727. position = light.matrixWorld.getPosition();
  12728. pointPositions[ pointOffset ] = position.x;
  12729. pointPositions[ pointOffset + 1 ] = position.y;
  12730. pointPositions[ pointOffset + 2 ] = position.z;
  12731. pointDistances[ pointLength ] = distance;
  12732. pointLength += 1;
  12733. } else if ( light instanceof THREE.SpotLight ) {
  12734. spotCount += 1;
  12735. if ( ! light.visible ) continue;
  12736. spotOffset = spotLength * 3;
  12737. if ( _this.gammaInput ) {
  12738. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12739. } else {
  12740. setColorLinear( spotColors, spotOffset, color, intensity );
  12741. }
  12742. position = light.matrixWorld.getPosition();
  12743. spotPositions[ spotOffset ] = position.x;
  12744. spotPositions[ spotOffset + 1 ] = position.y;
  12745. spotPositions[ spotOffset + 2 ] = position.z;
  12746. spotDistances[ spotLength ] = distance;
  12747. _direction.copy( position );
  12748. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12749. _direction.normalize();
  12750. spotDirections[ spotOffset ] = _direction.x;
  12751. spotDirections[ spotOffset + 1 ] = _direction.y;
  12752. spotDirections[ spotOffset + 2 ] = _direction.z;
  12753. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  12754. spotExponents[ spotLength ] = light.exponent;
  12755. spotLength += 1;
  12756. } else if ( light instanceof THREE.HemisphereLight ) {
  12757. hemiCount += 1;
  12758. if ( ! light.visible ) continue;
  12759. skyColor = light.color;
  12760. groundColor = light.groundColor;
  12761. hemiOffset = hemiLength * 3;
  12762. if ( _this.gammaInput ) {
  12763. intensitySq = intensity * intensity;
  12764. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12765. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12766. } else {
  12767. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12768. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12769. }
  12770. _direction.copy( light.matrixWorld.getPosition() );
  12771. _direction.normalize();
  12772. hemiPositions[ hemiOffset ] = _direction.x;
  12773. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  12774. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  12775. hemiLength += 1;
  12776. }
  12777. }
  12778. // null eventual remains from removed lights
  12779. // (this is to avoid if in shader)
  12780. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  12781. for ( l = dirLength * 3, ll = Math.max( dirPositions.length, dirCount * 3 ); l < ll; l ++ ) dirPositions[ l ] = 0.0;
  12782. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  12783. for ( l = pointLength * 3, ll = Math.max( pointPositions.length, pointCount * 3 ); l < ll; l ++ ) pointPositions[ l ] = 0.0;
  12784. for ( l = pointLength, ll = Math.max( pointDistances.length, pointCount ); l < ll; l ++ ) pointDistances[ l ] = 0.0;
  12785. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  12786. for ( l = spotLength * 3, ll = Math.max( spotPositions.length, spotCount * 3 ); l < ll; l ++ ) spotPositions[ l ] = 0.0;
  12787. for ( l = spotLength * 3, ll = Math.max( spotDirections.length, spotCount * 3 ); l < ll; l ++ ) spotDirections[ l ] = 0.0;
  12788. for ( l = spotLength, ll = Math.max( spotAnglesCos.length, spotCount ); l < ll; l ++ ) spotAnglesCos[ l ] = 0.0;
  12789. for ( l = spotLength, ll = Math.max( spotExponents.length, spotCount ); l < ll; l ++ ) spotExponents[ l ] = 0.0;
  12790. for ( l = spotLength, ll = Math.max( spotDistances.length, spotCount ); l < ll; l ++ ) spotDistances[ l ] = 0.0;
  12791. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12792. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12793. for ( l = hemiLength * 3, ll = Math.max( hemiPositions.length, hemiCount * 3 ); l < ll; l ++ ) hemiPositions[ l ] = 0.0;
  12794. zlights.directional.length = dirLength;
  12795. zlights.point.length = pointLength;
  12796. zlights.spot.length = spotLength;
  12797. zlights.hemi.length = hemiLength;
  12798. zlights.ambient[ 0 ] = r;
  12799. zlights.ambient[ 1 ] = g;
  12800. zlights.ambient[ 2 ] = b;
  12801. };
  12802. // GL state setting
  12803. this.setFaceCulling = function ( cullFace, frontFace ) {
  12804. if ( cullFace ) {
  12805. if ( !frontFace || frontFace === "ccw" ) {
  12806. _gl.frontFace( _gl.CCW );
  12807. } else {
  12808. _gl.frontFace( _gl.CW );
  12809. }
  12810. if( cullFace === "back" ) {
  12811. _gl.cullFace( _gl.BACK );
  12812. } else if( cullFace === "front" ) {
  12813. _gl.cullFace( _gl.FRONT );
  12814. } else {
  12815. _gl.cullFace( _gl.FRONT_AND_BACK );
  12816. }
  12817. _gl.enable( _gl.CULL_FACE );
  12818. } else {
  12819. _gl.disable( _gl.CULL_FACE );
  12820. }
  12821. };
  12822. this.setMaterialFaces = function ( material ) {
  12823. var doubleSided = material.side === THREE.DoubleSide;
  12824. var flipSided = material.side === THREE.BackSide;
  12825. if ( _oldDoubleSided !== doubleSided ) {
  12826. if ( doubleSided ) {
  12827. _gl.disable( _gl.CULL_FACE );
  12828. } else {
  12829. _gl.enable( _gl.CULL_FACE );
  12830. }
  12831. _oldDoubleSided = doubleSided;
  12832. }
  12833. if ( _oldFlipSided !== flipSided ) {
  12834. if ( flipSided ) {
  12835. _gl.frontFace( _gl.CW );
  12836. } else {
  12837. _gl.frontFace( _gl.CCW );
  12838. }
  12839. _oldFlipSided = flipSided;
  12840. }
  12841. };
  12842. this.setDepthTest = function ( depthTest ) {
  12843. if ( _oldDepthTest !== depthTest ) {
  12844. if ( depthTest ) {
  12845. _gl.enable( _gl.DEPTH_TEST );
  12846. } else {
  12847. _gl.disable( _gl.DEPTH_TEST );
  12848. }
  12849. _oldDepthTest = depthTest;
  12850. }
  12851. };
  12852. this.setDepthWrite = function ( depthWrite ) {
  12853. if ( _oldDepthWrite !== depthWrite ) {
  12854. _gl.depthMask( depthWrite );
  12855. _oldDepthWrite = depthWrite;
  12856. }
  12857. };
  12858. function setLineWidth ( width ) {
  12859. if ( width !== _oldLineWidth ) {
  12860. _gl.lineWidth( width );
  12861. _oldLineWidth = width;
  12862. }
  12863. };
  12864. function setPolygonOffset ( polygonoffset, factor, units ) {
  12865. if ( _oldPolygonOffset !== polygonoffset ) {
  12866. if ( polygonoffset ) {
  12867. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12868. } else {
  12869. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12870. }
  12871. _oldPolygonOffset = polygonoffset;
  12872. }
  12873. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12874. _gl.polygonOffset( factor, units );
  12875. _oldPolygonOffsetFactor = factor;
  12876. _oldPolygonOffsetUnits = units;
  12877. }
  12878. };
  12879. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  12880. if ( blending !== _oldBlending ) {
  12881. if ( blending === THREE.NoBlending ) {
  12882. _gl.disable( _gl.BLEND );
  12883. } else if ( blending === THREE.AdditiveBlending ) {
  12884. _gl.enable( _gl.BLEND );
  12885. _gl.blendEquation( _gl.FUNC_ADD );
  12886. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12887. } else if ( blending === THREE.SubtractiveBlending ) {
  12888. // TODO: Find blendFuncSeparate() combination
  12889. _gl.enable( _gl.BLEND );
  12890. _gl.blendEquation( _gl.FUNC_ADD );
  12891. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12892. } else if ( blending === THREE.MultiplyBlending ) {
  12893. // TODO: Find blendFuncSeparate() combination
  12894. _gl.enable( _gl.BLEND );
  12895. _gl.blendEquation( _gl.FUNC_ADD );
  12896. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  12897. } else if ( blending === THREE.CustomBlending ) {
  12898. _gl.enable( _gl.BLEND );
  12899. } else {
  12900. _gl.enable( _gl.BLEND );
  12901. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  12902. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  12903. }
  12904. _oldBlending = blending;
  12905. }
  12906. if ( blending === THREE.CustomBlending ) {
  12907. if ( blendEquation !== _oldBlendEquation ) {
  12908. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  12909. _oldBlendEquation = blendEquation;
  12910. }
  12911. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  12912. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  12913. _oldBlendSrc = blendSrc;
  12914. _oldBlendDst = blendDst;
  12915. }
  12916. } else {
  12917. _oldBlendEquation = null;
  12918. _oldBlendSrc = null;
  12919. _oldBlendDst = null;
  12920. }
  12921. };
  12922. // Defines
  12923. function generateDefines ( defines ) {
  12924. var value, chunk, chunks = [];
  12925. for ( var d in defines ) {
  12926. value = defines[ d ];
  12927. if ( value === false ) continue;
  12928. chunk = "#define " + d + " " + value;
  12929. chunks.push( chunk );
  12930. }
  12931. return chunks.join( "\n" );
  12932. };
  12933. // Shaders
  12934. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  12935. var p, pl, d, program, code;
  12936. var chunks = [];
  12937. // Generate code
  12938. if ( shaderID ) {
  12939. chunks.push( shaderID );
  12940. } else {
  12941. chunks.push( fragmentShader );
  12942. chunks.push( vertexShader );
  12943. }
  12944. for ( d in defines ) {
  12945. chunks.push( d );
  12946. chunks.push( defines[ d ] );
  12947. }
  12948. for ( p in parameters ) {
  12949. chunks.push( p );
  12950. chunks.push( parameters[ p ] );
  12951. }
  12952. code = chunks.join();
  12953. // Check if code has been already compiled
  12954. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  12955. var programInfo = _programs[ p ];
  12956. if ( programInfo.code === code ) {
  12957. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  12958. programInfo.usedTimes ++;
  12959. return programInfo.program;
  12960. }
  12961. }
  12962. //console.log( "building new program " );
  12963. //
  12964. var customDefines = generateDefines( defines );
  12965. //
  12966. program = _gl.createProgram();
  12967. var prefix_vertex = [
  12968. "precision " + _precision + " float;",
  12969. customDefines,
  12970. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  12971. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12972. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12973. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12974. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12975. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12976. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12977. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  12978. "#define MAX_SHADOWS " + parameters.maxShadows,
  12979. "#define MAX_BONES " + parameters.maxBones,
  12980. parameters.map ? "#define USE_MAP" : "",
  12981. parameters.envMap ? "#define USE_ENVMAP" : "",
  12982. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12983. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12984. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  12985. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12986. parameters.vertexColors ? "#define USE_COLOR" : "",
  12987. parameters.skinning ? "#define USE_SKINNING" : "",
  12988. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  12989. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  12990. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  12991. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  12992. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  12993. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12994. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12995. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12996. parameters.flipSided ? "#define FLIP_SIDED" : "",
  12997. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12998. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12999. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13000. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13001. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13002. "uniform mat4 modelMatrix;",
  13003. "uniform mat4 modelViewMatrix;",
  13004. "uniform mat4 projectionMatrix;",
  13005. "uniform mat4 viewMatrix;",
  13006. "uniform mat3 normalMatrix;",
  13007. "uniform vec3 cameraPosition;",
  13008. "attribute vec3 position;",
  13009. "attribute vec3 normal;",
  13010. "attribute vec2 uv;",
  13011. "attribute vec2 uv2;",
  13012. "#ifdef USE_COLOR",
  13013. "attribute vec3 color;",
  13014. "#endif",
  13015. "#ifdef USE_MORPHTARGETS",
  13016. "attribute vec3 morphTarget0;",
  13017. "attribute vec3 morphTarget1;",
  13018. "attribute vec3 morphTarget2;",
  13019. "attribute vec3 morphTarget3;",
  13020. "#ifdef USE_MORPHNORMALS",
  13021. "attribute vec3 morphNormal0;",
  13022. "attribute vec3 morphNormal1;",
  13023. "attribute vec3 morphNormal2;",
  13024. "attribute vec3 morphNormal3;",
  13025. "#else",
  13026. "attribute vec3 morphTarget4;",
  13027. "attribute vec3 morphTarget5;",
  13028. "attribute vec3 morphTarget6;",
  13029. "attribute vec3 morphTarget7;",
  13030. "#endif",
  13031. "#endif",
  13032. "#ifdef USE_SKINNING",
  13033. "attribute vec4 skinIndex;",
  13034. "attribute vec4 skinWeight;",
  13035. "#endif",
  13036. ""
  13037. ].join("\n");
  13038. var prefix_fragment = [
  13039. "precision " + _precision + " float;",
  13040. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13041. customDefines,
  13042. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13043. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13044. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13045. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13046. "#define MAX_SHADOWS " + parameters.maxShadows,
  13047. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13048. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13049. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13050. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13051. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13052. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13053. parameters.map ? "#define USE_MAP" : "",
  13054. parameters.envMap ? "#define USE_ENVMAP" : "",
  13055. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13056. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13057. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13058. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13059. parameters.vertexColors ? "#define USE_COLOR" : "",
  13060. parameters.metal ? "#define METAL" : "",
  13061. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13062. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13063. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13064. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13065. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13066. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13067. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13068. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13069. "uniform mat4 viewMatrix;",
  13070. "uniform vec3 cameraPosition;",
  13071. ""
  13072. ].join("\n");
  13073. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13074. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13075. _gl.attachShader( program, glVertexShader );
  13076. _gl.attachShader( program, glFragmentShader );
  13077. _gl.linkProgram( program );
  13078. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13079. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13080. }
  13081. // clean up
  13082. _gl.deleteShader( glFragmentShader );
  13083. _gl.deleteShader( glVertexShader );
  13084. //console.log( prefix_fragment + fragmentShader );
  13085. //console.log( prefix_vertex + vertexShader );
  13086. program.uniforms = {};
  13087. program.attributes = {};
  13088. var identifiers, u, a, i;
  13089. // cache uniform locations
  13090. identifiers = [
  13091. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13092. 'morphTargetInfluences'
  13093. ];
  13094. if ( parameters.useVertexTexture ) {
  13095. identifiers.push( 'boneTexture' );
  13096. } else {
  13097. identifiers.push( 'boneGlobalMatrices' );
  13098. }
  13099. for ( u in uniforms ) {
  13100. identifiers.push( u );
  13101. }
  13102. cacheUniformLocations( program, identifiers );
  13103. // cache attributes locations
  13104. identifiers = [
  13105. "position", "normal", "uv", "uv2", "tangent", "color",
  13106. "skinIndex", "skinWeight", "lineDistance"
  13107. ];
  13108. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13109. identifiers.push( "morphTarget" + i );
  13110. }
  13111. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13112. identifiers.push( "morphNormal" + i );
  13113. }
  13114. for ( a in attributes ) {
  13115. identifiers.push( a );
  13116. }
  13117. cacheAttributeLocations( program, identifiers );
  13118. program.id = _programs_counter ++;
  13119. _programs.push( { program: program, code: code, usedTimes: 1 } );
  13120. _this.info.memory.programs = _programs.length;
  13121. return program;
  13122. };
  13123. // Shader parameters cache
  13124. function cacheUniformLocations ( program, identifiers ) {
  13125. var i, l, id;
  13126. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13127. id = identifiers[ i ];
  13128. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  13129. }
  13130. };
  13131. function cacheAttributeLocations ( program, identifiers ) {
  13132. var i, l, id;
  13133. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13134. id = identifiers[ i ];
  13135. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  13136. }
  13137. };
  13138. function addLineNumbers ( string ) {
  13139. var chunks = string.split( "\n" );
  13140. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  13141. // Chrome reports shader errors on lines
  13142. // starting counting from 1
  13143. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  13144. }
  13145. return chunks.join( "\n" );
  13146. };
  13147. function getShader ( type, string ) {
  13148. var shader;
  13149. if ( type === "fragment" ) {
  13150. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13151. } else if ( type === "vertex" ) {
  13152. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13153. }
  13154. _gl.shaderSource( shader, string );
  13155. _gl.compileShader( shader );
  13156. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13157. console.error( _gl.getShaderInfoLog( shader ) );
  13158. console.error( addLineNumbers( string ) );
  13159. return null;
  13160. }
  13161. return shader;
  13162. };
  13163. // Textures
  13164. function isPowerOfTwo ( value ) {
  13165. return ( value & ( value - 1 ) ) === 0;
  13166. };
  13167. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13168. if ( isImagePowerOfTwo ) {
  13169. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13170. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13171. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13172. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13173. } else {
  13174. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13175. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13176. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13177. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13178. }
  13179. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13180. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13181. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13182. texture.__oldAnisotropy = texture.anisotropy;
  13183. }
  13184. }
  13185. };
  13186. this.setTexture = function ( texture, slot ) {
  13187. if ( texture.needsUpdate ) {
  13188. if ( ! texture.__webglInit ) {
  13189. texture.__webglInit = true;
  13190. texture.__webglTexture = _gl.createTexture();
  13191. _this.info.memory.textures ++;
  13192. }
  13193. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13194. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13195. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13196. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13197. var image = texture.image,
  13198. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13199. glFormat = paramThreeToGL( texture.format ),
  13200. glType = paramThreeToGL( texture.type );
  13201. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13202. if ( texture instanceof THREE.CompressedTexture ) {
  13203. var mipmap, mipmaps = texture.mipmaps;
  13204. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13205. mipmap = mipmaps[ i ];
  13206. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13207. }
  13208. } else if ( texture instanceof THREE.DataTexture ) {
  13209. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13210. } else {
  13211. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13212. }
  13213. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13214. texture.needsUpdate = false;
  13215. if ( texture.onUpdate ) texture.onUpdate();
  13216. } else {
  13217. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13218. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13219. }
  13220. };
  13221. function clampToMaxSize ( image, maxSize ) {
  13222. if ( image.width <= maxSize && image.height <= maxSize ) {
  13223. return image;
  13224. }
  13225. // Warning: Scaling through the canvas will only work with images that use
  13226. // premultiplied alpha.
  13227. var maxDimension = Math.max( image.width, image.height );
  13228. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13229. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13230. var canvas = document.createElement( 'canvas' );
  13231. canvas.width = newWidth;
  13232. canvas.height = newHeight;
  13233. var ctx = canvas.getContext( "2d" );
  13234. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13235. return canvas;
  13236. }
  13237. function setCubeTexture ( texture, slot ) {
  13238. if ( texture.image.length === 6 ) {
  13239. if ( texture.needsUpdate ) {
  13240. if ( ! texture.image.__webglTextureCube ) {
  13241. texture.image.__webglTextureCube = _gl.createTexture();
  13242. }
  13243. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13244. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13245. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13246. var isCompressed = texture instanceof THREE.CompressedTexture;
  13247. var cubeImage = [];
  13248. for ( var i = 0; i < 6; i ++ ) {
  13249. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  13250. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13251. } else {
  13252. cubeImage[ i ] = texture.image[ i ];
  13253. }
  13254. }
  13255. var image = cubeImage[ 0 ],
  13256. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13257. glFormat = paramThreeToGL( texture.format ),
  13258. glType = paramThreeToGL( texture.type );
  13259. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13260. for ( var i = 0; i < 6; i ++ ) {
  13261. if ( isCompressed ) {
  13262. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13263. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13264. mipmap = mipmaps[ j ];
  13265. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13266. }
  13267. } else {
  13268. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13269. }
  13270. }
  13271. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13272. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13273. }
  13274. texture.needsUpdate = false;
  13275. if ( texture.onUpdate ) texture.onUpdate();
  13276. } else {
  13277. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13278. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13279. }
  13280. }
  13281. };
  13282. function setCubeTextureDynamic ( texture, slot ) {
  13283. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13284. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13285. };
  13286. // Render targets
  13287. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13288. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13289. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13290. };
  13291. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13292. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13293. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13294. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13295. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13296. /* For some reason this is not working. Defaulting to RGBA4.
  13297. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13298. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13299. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13300. */
  13301. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13302. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13303. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13304. } else {
  13305. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13306. }
  13307. };
  13308. this.setRenderTarget = function ( renderTarget ) {
  13309. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13310. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13311. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13312. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13313. renderTarget.__webglTexture = _gl.createTexture();
  13314. // Setup texture, create render and frame buffers
  13315. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13316. glFormat = paramThreeToGL( renderTarget.format ),
  13317. glType = paramThreeToGL( renderTarget.type );
  13318. if ( isCube ) {
  13319. renderTarget.__webglFramebuffer = [];
  13320. renderTarget.__webglRenderbuffer = [];
  13321. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13322. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13323. for ( var i = 0; i < 6; i ++ ) {
  13324. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13325. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13326. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13327. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13328. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13329. }
  13330. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13331. } else {
  13332. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13333. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13334. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13335. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13336. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13337. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13338. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13339. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13340. }
  13341. // Release everything
  13342. if ( isCube ) {
  13343. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13344. } else {
  13345. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13346. }
  13347. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13348. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  13349. }
  13350. var framebuffer, width, height, vx, vy;
  13351. if ( renderTarget ) {
  13352. if ( isCube ) {
  13353. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13354. } else {
  13355. framebuffer = renderTarget.__webglFramebuffer;
  13356. }
  13357. width = renderTarget.width;
  13358. height = renderTarget.height;
  13359. vx = 0;
  13360. vy = 0;
  13361. } else {
  13362. framebuffer = null;
  13363. width = _viewportWidth;
  13364. height = _viewportHeight;
  13365. vx = _viewportX;
  13366. vy = _viewportY;
  13367. }
  13368. if ( framebuffer !== _currentFramebuffer ) {
  13369. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13370. _gl.viewport( vx, vy, width, height );
  13371. _currentFramebuffer = framebuffer;
  13372. }
  13373. _currentWidth = width;
  13374. _currentHeight = height;
  13375. };
  13376. function updateRenderTargetMipmap ( renderTarget ) {
  13377. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13378. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13379. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13380. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13381. } else {
  13382. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13383. _gl.generateMipmap( _gl.TEXTURE_2D );
  13384. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13385. }
  13386. };
  13387. // Fallback filters for non-power-of-2 textures
  13388. function filterFallback ( f ) {
  13389. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13390. return _gl.NEAREST;
  13391. }
  13392. return _gl.LINEAR;
  13393. };
  13394. // Map three.js constants to WebGL constants
  13395. function paramThreeToGL ( p ) {
  13396. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13397. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13398. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13399. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13400. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13401. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13402. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13403. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13404. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13405. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13406. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13407. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13408. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13409. if ( p === THREE.ByteType ) return _gl.BYTE;
  13410. if ( p === THREE.ShortType ) return _gl.SHORT;
  13411. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13412. if ( p === THREE.IntType ) return _gl.INT;
  13413. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13414. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13415. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13416. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13417. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13418. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13419. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13420. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13421. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13422. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13423. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13424. if ( p === THREE.OneFactor ) return _gl.ONE;
  13425. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13426. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13427. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13428. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13429. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13430. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13431. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13432. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13433. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13434. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13435. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13436. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13437. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13438. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13439. }
  13440. return 0;
  13441. };
  13442. // Allocations
  13443. function allocateBones ( object ) {
  13444. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  13445. return 1024;
  13446. } else {
  13447. // default for when object is not specified
  13448. // ( for example when prebuilding shader
  13449. // to be used with multiple objects )
  13450. //
  13451. // - leave some extra space for other uniforms
  13452. // - limit here is ANGLE's 254 max uniform vectors
  13453. // (up to 54 should be safe)
  13454. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13455. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13456. var maxBones = nVertexMatrices;
  13457. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13458. maxBones = Math.min( object.bones.length, maxBones );
  13459. if ( maxBones < object.bones.length ) {
  13460. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  13461. }
  13462. }
  13463. return maxBones;
  13464. }
  13465. };
  13466. function allocateLights ( lights ) {
  13467. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  13468. dirLights = pointLights = spotLights = hemiLights = 0;
  13469. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13470. light = lights[ l ];
  13471. if ( light.onlyShadow ) continue;
  13472. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13473. if ( light instanceof THREE.PointLight ) pointLights ++;
  13474. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13475. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13476. }
  13477. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  13478. };
  13479. function allocateShadows ( lights ) {
  13480. var l, ll, light, maxShadows = 0;
  13481. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  13482. light = lights[ l ];
  13483. if ( ! light.castShadow ) continue;
  13484. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13485. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13486. }
  13487. return maxShadows;
  13488. };
  13489. // Initialization
  13490. function initGL () {
  13491. try {
  13492. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  13493. throw 'Error creating WebGL context.';
  13494. }
  13495. } catch ( error ) {
  13496. console.error( error );
  13497. }
  13498. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  13499. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  13500. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  13501. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  13502. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13503. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  13504. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  13505. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13506. if ( ! _glExtensionTextureFloat ) {
  13507. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  13508. }
  13509. if ( ! _glExtensionStandardDerivatives ) {
  13510. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  13511. }
  13512. if ( ! _glExtensionTextureFilterAnisotropic ) {
  13513. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  13514. }
  13515. if ( ! _glExtensionCompressedTextureS3TC ) {
  13516. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  13517. }
  13518. };
  13519. function setDefaultGLState () {
  13520. _gl.clearColor( 0, 0, 0, 1 );
  13521. _gl.clearDepth( 1 );
  13522. _gl.clearStencil( 0 );
  13523. _gl.enable( _gl.DEPTH_TEST );
  13524. _gl.depthFunc( _gl.LEQUAL );
  13525. _gl.frontFace( _gl.CCW );
  13526. _gl.cullFace( _gl.BACK );
  13527. _gl.enable( _gl.CULL_FACE );
  13528. _gl.enable( _gl.BLEND );
  13529. _gl.blendEquation( _gl.FUNC_ADD );
  13530. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  13531. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  13532. };
  13533. // default plugins (order is important)
  13534. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  13535. this.addPrePlugin( this.shadowMapPlugin );
  13536. this.addPostPlugin( new THREE.SpritePlugin() );
  13537. this.addPostPlugin( new THREE.LensFlarePlugin() );
  13538. };
  13539. /**
  13540. * @author szimek / https://github.com/szimek/
  13541. * @author alteredq / http://alteredqualia.com/
  13542. */
  13543. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13544. this.width = width;
  13545. this.height = height;
  13546. options = options || {};
  13547. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13548. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13549. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13550. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13551. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13552. this.offset = new THREE.Vector2( 0, 0 );
  13553. this.repeat = new THREE.Vector2( 1, 1 );
  13554. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13555. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13556. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13557. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13558. this.generateMipmaps = true;
  13559. };
  13560. THREE.WebGLRenderTarget.prototype.clone = function() {
  13561. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13562. tmp.wrapS = this.wrapS;
  13563. tmp.wrapT = this.wrapT;
  13564. tmp.magFilter = this.magFilter;
  13565. tmp.anisotropy = this.anisotropy;
  13566. tmp.minFilter = this.minFilter;
  13567. tmp.offset.copy( this.offset );
  13568. tmp.repeat.copy( this.repeat );
  13569. tmp.format = this.format;
  13570. tmp.type = this.type;
  13571. tmp.depthBuffer = this.depthBuffer;
  13572. tmp.stencilBuffer = this.stencilBuffer;
  13573. tmp.generateMipmaps = this.generateMipmaps;
  13574. return tmp;
  13575. };
  13576. /**
  13577. * @author alteredq / http://alteredqualia.com
  13578. */
  13579. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13580. THREE.WebGLRenderTarget.call( this, width, height, options );
  13581. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13582. };
  13583. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13584. /**
  13585. * @author mrdoob / http://mrdoob.com/
  13586. */
  13587. THREE.RenderableVertex = function () {
  13588. this.positionWorld = new THREE.Vector3();
  13589. this.positionScreen = new THREE.Vector4();
  13590. this.visible = true;
  13591. };
  13592. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  13593. this.positionWorld.copy( vertex.positionWorld );
  13594. this.positionScreen.copy( vertex.positionScreen );
  13595. }
  13596. /**
  13597. * @author mrdoob / http://mrdoob.com/
  13598. */
  13599. THREE.RenderableFace3 = function () {
  13600. this.v1 = new THREE.RenderableVertex();
  13601. this.v2 = new THREE.RenderableVertex();
  13602. this.v3 = new THREE.RenderableVertex();
  13603. this.centroidWorld = new THREE.Vector3();
  13604. this.centroidScreen = new THREE.Vector3();
  13605. this.normalWorld = new THREE.Vector3();
  13606. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13607. this.vertexNormalsLength = 0;
  13608. this.color = null;
  13609. this.material = null;
  13610. this.uvs = [[]];
  13611. this.z = null;
  13612. };
  13613. /**
  13614. * @author mrdoob / http://mrdoob.com/
  13615. */
  13616. THREE.RenderableFace4 = function () {
  13617. this.v1 = new THREE.RenderableVertex();
  13618. this.v2 = new THREE.RenderableVertex();
  13619. this.v3 = new THREE.RenderableVertex();
  13620. this.v4 = new THREE.RenderableVertex();
  13621. this.centroidWorld = new THREE.Vector3();
  13622. this.centroidScreen = new THREE.Vector3();
  13623. this.normalWorld = new THREE.Vector3();
  13624. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13625. this.vertexNormalsLength = 0;
  13626. this.color = null;
  13627. this.material = null;
  13628. this.uvs = [[]];
  13629. this.z = null;
  13630. };
  13631. /**
  13632. * @author mrdoob / http://mrdoob.com/
  13633. */
  13634. THREE.RenderableObject = function () {
  13635. this.object = null;
  13636. this.z = null;
  13637. };
  13638. /**
  13639. * @author mrdoob / http://mrdoob.com/
  13640. */
  13641. THREE.RenderableParticle = function () {
  13642. this.object = null;
  13643. this.x = null;
  13644. this.y = null;
  13645. this.z = null;
  13646. this.rotation = null;
  13647. this.scale = new THREE.Vector2();
  13648. this.material = null;
  13649. };
  13650. /**
  13651. * @author mrdoob / http://mrdoob.com/
  13652. */
  13653. THREE.RenderableLine = function () {
  13654. this.z = null;
  13655. this.v1 = new THREE.RenderableVertex();
  13656. this.v2 = new THREE.RenderableVertex();
  13657. this.material = null;
  13658. };
  13659. /**
  13660. * @author alteredq / http://alteredqualia.com/
  13661. */
  13662. THREE.ColorUtils = {
  13663. adjustHSV : function ( color, h, s, v ) {
  13664. var hsv = THREE.ColorUtils.__hsv;
  13665. color.getHSV( hsv );
  13666. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  13667. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  13668. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  13669. color.setHSV( hsv.h, hsv.s, hsv.v );
  13670. }
  13671. };
  13672. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  13673. * @author mrdoob / http://mrdoob.com/
  13674. * @author alteredq / http://alteredqualia.com/
  13675. */
  13676. THREE.GeometryUtils = {
  13677. // Merge two geometries or geometry and geometry from object (using object's transform)
  13678. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  13679. var matrix, matrixRotation,
  13680. vertexOffset = geometry1.vertices.length,
  13681. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  13682. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  13683. vertices1 = geometry1.vertices,
  13684. vertices2 = geometry2.vertices,
  13685. faces1 = geometry1.faces,
  13686. faces2 = geometry2.faces,
  13687. uvs1 = geometry1.faceVertexUvs[ 0 ],
  13688. uvs2 = geometry2.faceVertexUvs[ 0 ];
  13689. if ( object2 instanceof THREE.Mesh ) {
  13690. object2.matrixAutoUpdate && object2.updateMatrix();
  13691. matrix = object2.matrix;
  13692. matrixRotation = new THREE.Matrix4();
  13693. matrixRotation.extractRotation( matrix, object2.scale );
  13694. }
  13695. // vertices
  13696. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13697. var vertex = vertices2[ i ];
  13698. var vertexCopy = vertex.clone();
  13699. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13700. vertices1.push( vertexCopy );
  13701. }
  13702. // faces
  13703. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13704. var face = faces2[ i ], faceCopy, normal, color,
  13705. faceVertexNormals = face.vertexNormals,
  13706. faceVertexColors = face.vertexColors;
  13707. if ( face instanceof THREE.Face3 ) {
  13708. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13709. } else if ( face instanceof THREE.Face4 ) {
  13710. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13711. }
  13712. faceCopy.normal.copy( face.normal );
  13713. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13714. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13715. normal = faceVertexNormals[ j ].clone();
  13716. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13717. faceCopy.vertexNormals.push( normal );
  13718. }
  13719. faceCopy.color.copy( face.color );
  13720. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13721. color = faceVertexColors[ j ];
  13722. faceCopy.vertexColors.push( color.clone() );
  13723. }
  13724. faceCopy.materialIndex = face.materialIndex;
  13725. faceCopy.centroid.copy( face.centroid );
  13726. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13727. faces1.push( faceCopy );
  13728. }
  13729. // uvs
  13730. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13731. var uv = uvs2[ i ], uvCopy = [];
  13732. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13733. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13734. }
  13735. uvs1.push( uvCopy );
  13736. }
  13737. },
  13738. removeMaterials: function ( geometry, materialIndexArray ) {
  13739. var materialIndexMap = {};
  13740. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  13741. materialIndexMap[ materialIndexArray[i] ] = true;
  13742. }
  13743. var face, newFaces = [];
  13744. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13745. face = geometry.faces[ i ];
  13746. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  13747. }
  13748. geometry.faces = newFaces;
  13749. },
  13750. // Get random point in triangle (via barycentric coordinates)
  13751. // (uniform distribution)
  13752. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13753. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13754. var a, b, c,
  13755. point = new THREE.Vector3(),
  13756. tmp = THREE.GeometryUtils.__v1;
  13757. a = THREE.GeometryUtils.random();
  13758. b = THREE.GeometryUtils.random();
  13759. if ( ( a + b ) > 1 ) {
  13760. a = 1 - a;
  13761. b = 1 - b;
  13762. }
  13763. c = 1 - a - b;
  13764. point.copy( vectorA );
  13765. point.multiplyScalar( a );
  13766. tmp.copy( vectorB );
  13767. tmp.multiplyScalar( b );
  13768. point.addSelf( tmp );
  13769. tmp.copy( vectorC );
  13770. tmp.multiplyScalar( c );
  13771. point.addSelf( tmp );
  13772. return point;
  13773. },
  13774. // Get random point in face (triangle / quad)
  13775. // (uniform distribution)
  13776. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13777. var vA, vB, vC, vD;
  13778. if ( face instanceof THREE.Face3 ) {
  13779. vA = geometry.vertices[ face.a ];
  13780. vB = geometry.vertices[ face.b ];
  13781. vC = geometry.vertices[ face.c ];
  13782. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13783. } else if ( face instanceof THREE.Face4 ) {
  13784. vA = geometry.vertices[ face.a ];
  13785. vB = geometry.vertices[ face.b ];
  13786. vC = geometry.vertices[ face.c ];
  13787. vD = geometry.vertices[ face.d ];
  13788. var area1, area2;
  13789. if ( useCachedAreas ) {
  13790. if ( face._area1 && face._area2 ) {
  13791. area1 = face._area1;
  13792. area2 = face._area2;
  13793. } else {
  13794. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13795. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13796. face._area1 = area1;
  13797. face._area2 = area2;
  13798. }
  13799. } else {
  13800. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  13801. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13802. }
  13803. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  13804. if ( r < area1 ) {
  13805. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  13806. } else {
  13807. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  13808. }
  13809. }
  13810. },
  13811. // Get uniformly distributed random points in mesh
  13812. // - create array with cumulative sums of face areas
  13813. // - pick random number from 0 to total area
  13814. // - find corresponding place in area array by binary search
  13815. // - get random point in face
  13816. randomPointsInGeometry: function ( geometry, n ) {
  13817. var face, i,
  13818. faces = geometry.faces,
  13819. vertices = geometry.vertices,
  13820. il = faces.length,
  13821. totalArea = 0,
  13822. cumulativeAreas = [],
  13823. vA, vB, vC, vD;
  13824. // precompute face areas
  13825. for ( i = 0; i < il; i ++ ) {
  13826. face = faces[ i ];
  13827. if ( face instanceof THREE.Face3 ) {
  13828. vA = vertices[ face.a ];
  13829. vB = vertices[ face.b ];
  13830. vC = vertices[ face.c ];
  13831. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  13832. } else if ( face instanceof THREE.Face4 ) {
  13833. vA = vertices[ face.a ];
  13834. vB = vertices[ face.b ];
  13835. vC = vertices[ face.c ];
  13836. vD = vertices[ face.d ];
  13837. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13838. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13839. face._area = face._area1 + face._area2;
  13840. }
  13841. totalArea += face._area;
  13842. cumulativeAreas[ i ] = totalArea;
  13843. }
  13844. // binary search cumulative areas array
  13845. function binarySearchIndices( value ) {
  13846. function binarySearch( start, end ) {
  13847. // return closest larger index
  13848. // if exact number is not found
  13849. if ( end < start )
  13850. return start;
  13851. var mid = start + Math.floor( ( end - start ) / 2 );
  13852. if ( cumulativeAreas[ mid ] > value ) {
  13853. return binarySearch( start, mid - 1 );
  13854. } else if ( cumulativeAreas[ mid ] < value ) {
  13855. return binarySearch( mid + 1, end );
  13856. } else {
  13857. return mid;
  13858. }
  13859. }
  13860. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  13861. return result;
  13862. }
  13863. // pick random face weighted by face area
  13864. var r, index,
  13865. result = [];
  13866. var stats = {};
  13867. for ( i = 0; i < n; i ++ ) {
  13868. r = THREE.GeometryUtils.random() * totalArea;
  13869. index = binarySearchIndices( r );
  13870. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  13871. if ( ! stats[ index ] ) {
  13872. stats[ index ] = 1;
  13873. } else {
  13874. stats[ index ] += 1;
  13875. }
  13876. }
  13877. return result;
  13878. },
  13879. // Get triangle area (by Heron's formula)
  13880. // http://en.wikipedia.org/wiki/Heron%27s_formula
  13881. triangleArea: function ( vectorA, vectorB, vectorC ) {
  13882. var s, a, b, c,
  13883. tmp = THREE.GeometryUtils.__v1;
  13884. tmp.sub( vectorA, vectorB );
  13885. a = tmp.length();
  13886. tmp.sub( vectorA, vectorC );
  13887. b = tmp.length();
  13888. tmp.sub( vectorB, vectorC );
  13889. c = tmp.length();
  13890. s = 0.5 * ( a + b + c );
  13891. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  13892. },
  13893. // Center geometry so that 0,0,0 is in center of bounding box
  13894. center: function ( geometry ) {
  13895. geometry.computeBoundingBox();
  13896. var bb = geometry.boundingBox;
  13897. var offset = new THREE.Vector3();
  13898. offset.add( bb.min, bb.max );
  13899. offset.multiplyScalar( -0.5 );
  13900. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  13901. geometry.computeBoundingBox();
  13902. return offset;
  13903. },
  13904. // Normalize UVs to be from <0,1>
  13905. // (for now just the first set of UVs)
  13906. normalizeUVs: function ( geometry ) {
  13907. var uvSet = geometry.faceVertexUvs[ 0 ];
  13908. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  13909. var uvs = uvSet[ i ];
  13910. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  13911. // texture repeat
  13912. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  13913. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  13914. }
  13915. }
  13916. },
  13917. triangulateQuads: function ( geometry ) {
  13918. var i, il, j, jl;
  13919. var faces = [];
  13920. var faceUvs = [];
  13921. var faceVertexUvs = [];
  13922. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  13923. faceUvs[ i ] = [];
  13924. }
  13925. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13926. faceVertexUvs[ i ] = [];
  13927. }
  13928. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13929. var face = geometry.faces[ i ];
  13930. if ( face instanceof THREE.Face4 ) {
  13931. var a = face.a;
  13932. var b = face.b;
  13933. var c = face.c;
  13934. var d = face.d;
  13935. var triA = new THREE.Face3();
  13936. var triB = new THREE.Face3();
  13937. triA.color.copy( face.color );
  13938. triB.color.copy( face.color );
  13939. triA.materialIndex = face.materialIndex;
  13940. triB.materialIndex = face.materialIndex;
  13941. triA.a = a;
  13942. triA.b = b;
  13943. triA.c = d;
  13944. triB.a = b;
  13945. triB.b = c;
  13946. triB.c = d;
  13947. if ( face.vertexColors.length === 4 ) {
  13948. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  13949. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  13950. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13951. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  13952. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  13953. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13954. }
  13955. faces.push( triA, triB );
  13956. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13957. if ( geometry.faceVertexUvs[ j ].length ) {
  13958. var uvs = geometry.faceVertexUvs[ j ][ i ];
  13959. var uvA = uvs[ 0 ];
  13960. var uvB = uvs[ 1 ];
  13961. var uvC = uvs[ 2 ];
  13962. var uvD = uvs[ 3 ];
  13963. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  13964. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  13965. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13966. }
  13967. }
  13968. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13969. if ( geometry.faceUvs[ j ].length ) {
  13970. var faceUv = geometry.faceUvs[ j ][ i ];
  13971. faceUvs[ j ].push( faceUv, faceUv );
  13972. }
  13973. }
  13974. } else {
  13975. faces.push( face );
  13976. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13977. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  13978. }
  13979. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13980. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13981. }
  13982. }
  13983. }
  13984. geometry.faces = faces;
  13985. geometry.faceUvs = faceUvs;
  13986. geometry.faceVertexUvs = faceVertexUvs;
  13987. geometry.computeCentroids();
  13988. geometry.computeFaceNormals();
  13989. geometry.computeVertexNormals();
  13990. if ( geometry.hasTangents ) geometry.computeTangents();
  13991. },
  13992. // Make all faces use unique vertices
  13993. // so that each face can be separated from others
  13994. explode: function( geometry ) {
  13995. var vertices = [];
  13996. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13997. var n = vertices.length;
  13998. var face = geometry.faces[ i ];
  13999. if ( face instanceof THREE.Face4 ) {
  14000. var a = face.a;
  14001. var b = face.b;
  14002. var c = face.c;
  14003. var d = face.d;
  14004. var va = geometry.vertices[ a ];
  14005. var vb = geometry.vertices[ b ];
  14006. var vc = geometry.vertices[ c ];
  14007. var vd = geometry.vertices[ d ];
  14008. vertices.push( va.clone() );
  14009. vertices.push( vb.clone() );
  14010. vertices.push( vc.clone() );
  14011. vertices.push( vd.clone() );
  14012. face.a = n;
  14013. face.b = n + 1;
  14014. face.c = n + 2;
  14015. face.d = n + 3;
  14016. } else {
  14017. var a = face.a;
  14018. var b = face.b;
  14019. var c = face.c;
  14020. var va = geometry.vertices[ a ];
  14021. var vb = geometry.vertices[ b ];
  14022. var vc = geometry.vertices[ c ];
  14023. vertices.push( va.clone() );
  14024. vertices.push( vb.clone() );
  14025. vertices.push( vc.clone() );
  14026. face.a = n;
  14027. face.b = n + 1;
  14028. face.c = n + 2;
  14029. }
  14030. }
  14031. geometry.vertices = vertices;
  14032. delete geometry.__tmpVertices;
  14033. },
  14034. // Break faces with edges longer than maxEdgeLength
  14035. // - not recursive
  14036. tessellate: function ( geometry, maxEdgeLength ) {
  14037. var i, il, face,
  14038. a, b, c, d,
  14039. va, vb, vc, vd,
  14040. dab, dbc, dac, dcd, dad,
  14041. m, m1, m2,
  14042. vm, vm1, vm2,
  14043. vnm, vnm1, vnm2,
  14044. vcm, vcm1, vcm2,
  14045. triA, triB,
  14046. quadA, quadB,
  14047. edge;
  14048. var faces = [];
  14049. var faceVertexUvs = [];
  14050. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14051. faceVertexUvs[ i ] = [];
  14052. }
  14053. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14054. face = geometry.faces[ i ];
  14055. if ( face instanceof THREE.Face3 ) {
  14056. a = face.a;
  14057. b = face.b;
  14058. c = face.c;
  14059. va = geometry.vertices[ a ];
  14060. vb = geometry.vertices[ b ];
  14061. vc = geometry.vertices[ c ];
  14062. dab = va.distanceTo( vb );
  14063. dbc = vb.distanceTo( vc );
  14064. dac = va.distanceTo( vc );
  14065. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  14066. m = geometry.vertices.length;
  14067. triA = face.clone();
  14068. triB = face.clone();
  14069. if ( dab >= dbc && dab >= dac ) {
  14070. vm = va.clone();
  14071. vm.lerpSelf( vb, 0.5 );
  14072. triA.a = a;
  14073. triA.b = m;
  14074. triA.c = c;
  14075. triB.a = m;
  14076. triB.b = b;
  14077. triB.c = c;
  14078. if ( face.vertexNormals.length === 3 ) {
  14079. vnm = face.vertexNormals[ 0 ].clone();
  14080. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14081. triA.vertexNormals[ 1 ].copy( vnm );
  14082. triB.vertexNormals[ 0 ].copy( vnm );
  14083. }
  14084. if ( face.vertexColors.length === 3 ) {
  14085. vcm = face.vertexColors[ 0 ].clone();
  14086. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14087. triA.vertexColors[ 1 ].copy( vcm );
  14088. triB.vertexColors[ 0 ].copy( vcm );
  14089. }
  14090. edge = 0;
  14091. } else if ( dbc >= dab && dbc >= dac ) {
  14092. vm = vb.clone();
  14093. vm.lerpSelf( vc, 0.5 );
  14094. triA.a = a;
  14095. triA.b = b;
  14096. triA.c = m;
  14097. triB.a = m;
  14098. triB.b = c;
  14099. triB.c = a;
  14100. if ( face.vertexNormals.length === 3 ) {
  14101. vnm = face.vertexNormals[ 1 ].clone();
  14102. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14103. triA.vertexNormals[ 2 ].copy( vnm );
  14104. triB.vertexNormals[ 0 ].copy( vnm );
  14105. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  14106. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  14107. }
  14108. if ( face.vertexColors.length === 3 ) {
  14109. vcm = face.vertexColors[ 1 ].clone();
  14110. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14111. triA.vertexColors[ 2 ].copy( vcm );
  14112. triB.vertexColors[ 0 ].copy( vcm );
  14113. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  14114. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  14115. }
  14116. edge = 1;
  14117. } else {
  14118. vm = va.clone();
  14119. vm.lerpSelf( vc, 0.5 );
  14120. triA.a = a;
  14121. triA.b = b;
  14122. triA.c = m;
  14123. triB.a = m;
  14124. triB.b = b;
  14125. triB.c = c;
  14126. if ( face.vertexNormals.length === 3 ) {
  14127. vnm = face.vertexNormals[ 0 ].clone();
  14128. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14129. triA.vertexNormals[ 2 ].copy( vnm );
  14130. triB.vertexNormals[ 0 ].copy( vnm );
  14131. }
  14132. if ( face.vertexColors.length === 3 ) {
  14133. vcm = face.vertexColors[ 0 ].clone();
  14134. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14135. triA.vertexColors[ 2 ].copy( vcm );
  14136. triB.vertexColors[ 0 ].copy( vcm );
  14137. }
  14138. edge = 2;
  14139. }
  14140. faces.push( triA, triB );
  14141. geometry.vertices.push( vm );
  14142. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  14143. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14144. if ( geometry.faceVertexUvs[ j ].length ) {
  14145. uvs = geometry.faceVertexUvs[ j ][ i ];
  14146. uvA = uvs[ 0 ];
  14147. uvB = uvs[ 1 ];
  14148. uvC = uvs[ 2 ];
  14149. // AB
  14150. if ( edge === 0 ) {
  14151. uvM = uvA.clone();
  14152. uvM.lerpSelf( uvB, 0.5 );
  14153. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  14154. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14155. // BC
  14156. } else if ( edge === 1 ) {
  14157. uvM = uvB.clone();
  14158. uvM.lerpSelf( uvC, 0.5 );
  14159. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14160. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  14161. // AC
  14162. } else {
  14163. uvM = uvA.clone();
  14164. uvM.lerpSelf( uvC, 0.5 );
  14165. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14166. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14167. }
  14168. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14169. }
  14170. }
  14171. } else {
  14172. faces.push( face );
  14173. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14174. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14175. }
  14176. }
  14177. } else {
  14178. a = face.a;
  14179. b = face.b;
  14180. c = face.c;
  14181. d = face.d;
  14182. va = geometry.vertices[ a ];
  14183. vb = geometry.vertices[ b ];
  14184. vc = geometry.vertices[ c ];
  14185. vd = geometry.vertices[ d ];
  14186. dab = va.distanceTo( vb );
  14187. dbc = vb.distanceTo( vc );
  14188. dcd = vc.distanceTo( vd );
  14189. dad = va.distanceTo( vd );
  14190. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  14191. m1 = geometry.vertices.length;
  14192. m2 = geometry.vertices.length + 1;
  14193. quadA = face.clone();
  14194. quadB = face.clone();
  14195. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  14196. vm1 = va.clone();
  14197. vm1.lerpSelf( vb, 0.5 );
  14198. vm2 = vc.clone();
  14199. vm2.lerpSelf( vd, 0.5 );
  14200. quadA.a = a;
  14201. quadA.b = m1;
  14202. quadA.c = m2;
  14203. quadA.d = d;
  14204. quadB.a = m1;
  14205. quadB.b = b;
  14206. quadB.c = c;
  14207. quadB.d = m2;
  14208. if ( face.vertexNormals.length === 4 ) {
  14209. vnm1 = face.vertexNormals[ 0 ].clone();
  14210. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14211. vnm2 = face.vertexNormals[ 2 ].clone();
  14212. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  14213. quadA.vertexNormals[ 1 ].copy( vnm1 );
  14214. quadA.vertexNormals[ 2 ].copy( vnm2 );
  14215. quadB.vertexNormals[ 0 ].copy( vnm1 );
  14216. quadB.vertexNormals[ 3 ].copy( vnm2 );
  14217. }
  14218. if ( face.vertexColors.length === 4 ) {
  14219. vcm1 = face.vertexColors[ 0 ].clone();
  14220. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14221. vcm2 = face.vertexColors[ 2 ].clone();
  14222. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  14223. quadA.vertexColors[ 1 ].copy( vcm1 );
  14224. quadA.vertexColors[ 2 ].copy( vcm2 );
  14225. quadB.vertexColors[ 0 ].copy( vcm1 );
  14226. quadB.vertexColors[ 3 ].copy( vcm2 );
  14227. }
  14228. edge = 0;
  14229. } else {
  14230. vm1 = vb.clone();
  14231. vm1.lerpSelf( vc, 0.5 );
  14232. vm2 = vd.clone();
  14233. vm2.lerpSelf( va, 0.5 );
  14234. quadA.a = a;
  14235. quadA.b = b;
  14236. quadA.c = m1;
  14237. quadA.d = m2;
  14238. quadB.a = m2;
  14239. quadB.b = m1;
  14240. quadB.c = c;
  14241. quadB.d = d;
  14242. if ( face.vertexNormals.length === 4 ) {
  14243. vnm1 = face.vertexNormals[ 1 ].clone();
  14244. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14245. vnm2 = face.vertexNormals[ 3 ].clone();
  14246. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  14247. quadA.vertexNormals[ 2 ].copy( vnm1 );
  14248. quadA.vertexNormals[ 3 ].copy( vnm2 );
  14249. quadB.vertexNormals[ 0 ].copy( vnm2 );
  14250. quadB.vertexNormals[ 1 ].copy( vnm1 );
  14251. }
  14252. if ( face.vertexColors.length === 4 ) {
  14253. vcm1 = face.vertexColors[ 1 ].clone();
  14254. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14255. vcm2 = face.vertexColors[ 3 ].clone();
  14256. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  14257. quadA.vertexColors[ 2 ].copy( vcm1 );
  14258. quadA.vertexColors[ 3 ].copy( vcm2 );
  14259. quadB.vertexColors[ 0 ].copy( vcm2 );
  14260. quadB.vertexColors[ 1 ].copy( vcm1 );
  14261. }
  14262. edge = 1;
  14263. }
  14264. faces.push( quadA, quadB );
  14265. geometry.vertices.push( vm1, vm2 );
  14266. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  14267. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14268. if ( geometry.faceVertexUvs[ j ].length ) {
  14269. uvs = geometry.faceVertexUvs[ j ][ i ];
  14270. uvA = uvs[ 0 ];
  14271. uvB = uvs[ 1 ];
  14272. uvC = uvs[ 2 ];
  14273. uvD = uvs[ 3 ];
  14274. // AB + CD
  14275. if ( edge === 0 ) {
  14276. uvM1 = uvA.clone();
  14277. uvM1.lerpSelf( uvB, 0.5 );
  14278. uvM2 = uvC.clone();
  14279. uvM2.lerpSelf( uvD, 0.5 );
  14280. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  14281. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  14282. // BC + AD
  14283. } else {
  14284. uvM1 = uvB.clone();
  14285. uvM1.lerpSelf( uvC, 0.5 );
  14286. uvM2 = uvD.clone();
  14287. uvM2.lerpSelf( uvA, 0.5 );
  14288. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  14289. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  14290. }
  14291. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  14292. }
  14293. }
  14294. } else {
  14295. faces.push( face );
  14296. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14297. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14298. }
  14299. }
  14300. }
  14301. }
  14302. geometry.faces = faces;
  14303. geometry.faceVertexUvs = faceVertexUvs;
  14304. }
  14305. };
  14306. THREE.GeometryUtils.random = THREE.Math.random16;
  14307. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14308. /**
  14309. * @author alteredq / http://alteredqualia.com/
  14310. * @author mrdoob / http://mrdoob.com/
  14311. */
  14312. THREE.ImageUtils = {
  14313. crossOrigin: 'anonymous',
  14314. loadTexture: function ( url, mapping, onLoad, onError ) {
  14315. var image = new Image();
  14316. var texture = new THREE.Texture( image, mapping );
  14317. var loader = new THREE.ImageLoader();
  14318. loader.addEventListener( 'load', function ( event ) {
  14319. texture.image = event.content;
  14320. texture.needsUpdate = true;
  14321. if ( onLoad ) onLoad( texture );
  14322. } );
  14323. loader.addEventListener( 'error', function ( event ) {
  14324. if ( onError ) onError( event.message );
  14325. } );
  14326. loader.crossOrigin = this.crossOrigin;
  14327. loader.load( url, image );
  14328. texture.sourceFile = url;
  14329. return texture;
  14330. },
  14331. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14332. var texture = new THREE.CompressedTexture();
  14333. texture.mapping = mapping;
  14334. var request = new XMLHttpRequest();
  14335. request.onload = function () {
  14336. var buffer = request.response;
  14337. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14338. texture.format = dds.format;
  14339. texture.mipmaps = dds.mipmaps;
  14340. texture.image.width = dds.width;
  14341. texture.image.height = dds.height;
  14342. // gl.generateMipmap fails for compressed textures
  14343. // mipmaps must be embedded in the DDS file
  14344. // or texture filters must not use mipmapping
  14345. texture.generateMipmaps = false;
  14346. texture.needsUpdate = true;
  14347. if ( onLoad ) onLoad( texture );
  14348. }
  14349. request.onerror = onError;
  14350. request.open( 'GET', url, true );
  14351. request.responseType = "arraybuffer";
  14352. request.send( null );
  14353. return texture;
  14354. },
  14355. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14356. var images = [];
  14357. images.loadCount = 0;
  14358. var texture = new THREE.Texture();
  14359. texture.image = images;
  14360. if ( mapping !== undefined ) texture.mapping = mapping;
  14361. // no flipping needed for cube textures
  14362. texture.flipY = false;
  14363. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14364. var cubeImage = new Image();
  14365. images[ i ] = cubeImage;
  14366. cubeImage.onload = function () {
  14367. images.loadCount += 1;
  14368. if ( images.loadCount === 6 ) {
  14369. texture.needsUpdate = true;
  14370. if ( onLoad ) onLoad();
  14371. }
  14372. };
  14373. cubeImage.onerror = onError;
  14374. cubeImage.crossOrigin = this.crossOrigin;
  14375. cubeImage.src = array[ i ];
  14376. }
  14377. return texture;
  14378. },
  14379. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14380. var images = [];
  14381. images.loadCount = 0;
  14382. var texture = new THREE.CompressedTexture();
  14383. texture.image = images;
  14384. if ( mapping !== undefined ) texture.mapping = mapping;
  14385. // no flipping for cube textures
  14386. // (also flipping doesn't work for compressed textures )
  14387. texture.flipY = false;
  14388. // can't generate mipmaps for compressed textures
  14389. // mips must be embedded in DDS files
  14390. texture.generateMipmaps = false;
  14391. var generateCubeFaceCallback = function ( rq, img ) {
  14392. return function () {
  14393. var buffer = rq.response;
  14394. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14395. img.format = dds.format;
  14396. img.mipmaps = dds.mipmaps;
  14397. img.width = dds.width;
  14398. img.height = dds.height;
  14399. images.loadCount += 1;
  14400. if ( images.loadCount === 6 ) {
  14401. texture.format = dds.format;
  14402. texture.needsUpdate = true;
  14403. if ( onLoad ) onLoad();
  14404. }
  14405. }
  14406. }
  14407. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14408. var cubeImage = {};
  14409. images[ i ] = cubeImage;
  14410. var request = new XMLHttpRequest();
  14411. request.onload = generateCubeFaceCallback( request, cubeImage );
  14412. request.onerror = onError;
  14413. var url = array[ i ];
  14414. request.open( 'GET', url, true );
  14415. request.responseType = "arraybuffer";
  14416. request.send( null );
  14417. }
  14418. return texture;
  14419. },
  14420. parseDDS: function ( buffer, loadMipmaps ) {
  14421. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  14422. // Adapted from @toji's DDS utils
  14423. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  14424. // All values and structures referenced from:
  14425. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  14426. var DDS_MAGIC = 0x20534444;
  14427. var DDSD_CAPS = 0x1,
  14428. DDSD_HEIGHT = 0x2,
  14429. DDSD_WIDTH = 0x4,
  14430. DDSD_PITCH = 0x8,
  14431. DDSD_PIXELFORMAT = 0x1000,
  14432. DDSD_MIPMAPCOUNT = 0x20000,
  14433. DDSD_LINEARSIZE = 0x80000,
  14434. DDSD_DEPTH = 0x800000;
  14435. var DDSCAPS_COMPLEX = 0x8,
  14436. DDSCAPS_MIPMAP = 0x400000,
  14437. DDSCAPS_TEXTURE = 0x1000;
  14438. var DDSCAPS2_CUBEMAP = 0x200,
  14439. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  14440. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  14441. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  14442. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  14443. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  14444. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  14445. DDSCAPS2_VOLUME = 0x200000;
  14446. var DDPF_ALPHAPIXELS = 0x1,
  14447. DDPF_ALPHA = 0x2,
  14448. DDPF_FOURCC = 0x4,
  14449. DDPF_RGB = 0x40,
  14450. DDPF_YUV = 0x200,
  14451. DDPF_LUMINANCE = 0x20000;
  14452. function fourCCToInt32( value ) {
  14453. return value.charCodeAt(0) +
  14454. (value.charCodeAt(1) << 8) +
  14455. (value.charCodeAt(2) << 16) +
  14456. (value.charCodeAt(3) << 24);
  14457. }
  14458. function int32ToFourCC( value ) {
  14459. return String.fromCharCode(
  14460. value & 0xff,
  14461. (value >> 8) & 0xff,
  14462. (value >> 16) & 0xff,
  14463. (value >> 24) & 0xff
  14464. );
  14465. }
  14466. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  14467. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  14468. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  14469. var headerLengthInt = 31; // The header length in 32 bit ints
  14470. // Offsets into the header array
  14471. var off_magic = 0;
  14472. var off_size = 1;
  14473. var off_flags = 2;
  14474. var off_height = 3;
  14475. var off_width = 4;
  14476. var off_mipmapCount = 7;
  14477. var off_pfFlags = 20;
  14478. var off_pfFourCC = 21;
  14479. // Parse header
  14480. var header = new Int32Array( buffer, 0, headerLengthInt );
  14481. if ( header[ off_magic ] !== DDS_MAGIC ) {
  14482. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  14483. return dds;
  14484. }
  14485. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  14486. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  14487. return dds;
  14488. }
  14489. var blockBytes;
  14490. var fourCC = header[ off_pfFourCC ];
  14491. switch ( fourCC ) {
  14492. case FOURCC_DXT1:
  14493. blockBytes = 8;
  14494. dds.format = THREE.RGB_S3TC_DXT1_Format;
  14495. break;
  14496. case FOURCC_DXT3:
  14497. blockBytes = 16;
  14498. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  14499. break;
  14500. case FOURCC_DXT5:
  14501. blockBytes = 16;
  14502. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  14503. break;
  14504. default:
  14505. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  14506. return dds;
  14507. }
  14508. dds.mipmapCount = 1;
  14509. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  14510. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  14511. }
  14512. dds.width = header[ off_width ];
  14513. dds.height = header[ off_height ];
  14514. var dataOffset = header[ off_size ] + 4;
  14515. // Extract mipmaps buffers
  14516. var width = dds.width;
  14517. var height = dds.height;
  14518. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14519. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  14520. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  14521. var mipmap = { "data": byteArray, "width": width, "height": height };
  14522. dds.mipmaps.push( mipmap );
  14523. dataOffset += dataLength;
  14524. width = Math.max( width * 0.5, 1 );
  14525. height = Math.max( height * 0.5, 1 );
  14526. }
  14527. return dds;
  14528. },
  14529. getNormalMap: function ( image, depth ) {
  14530. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  14531. var cross = function ( a, b ) {
  14532. 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 ] ];
  14533. }
  14534. var subtract = function ( a, b ) {
  14535. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  14536. }
  14537. var normalize = function ( a ) {
  14538. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  14539. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  14540. }
  14541. depth = depth | 1;
  14542. var width = image.width;
  14543. var height = image.height;
  14544. var canvas = document.createElement( 'canvas' );
  14545. canvas.width = width;
  14546. canvas.height = height;
  14547. var context = canvas.getContext( '2d' );
  14548. context.drawImage( image, 0, 0 );
  14549. var data = context.getImageData( 0, 0, width, height ).data;
  14550. var imageData = context.createImageData( width, height );
  14551. var output = imageData.data;
  14552. for ( var x = 0; x < width; x ++ ) {
  14553. for ( var y = 0; y < height; y ++ ) {
  14554. var ly = y - 1 < 0 ? 0 : y - 1;
  14555. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  14556. var lx = x - 1 < 0 ? 0 : x - 1;
  14557. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  14558. var points = [];
  14559. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  14560. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  14561. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  14562. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  14563. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  14564. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  14565. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  14566. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  14567. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  14568. var normals = [];
  14569. var num_points = points.length;
  14570. for ( var i = 0; i < num_points; i ++ ) {
  14571. var v1 = points[ i ];
  14572. var v2 = points[ ( i + 1 ) % num_points ];
  14573. v1 = subtract( v1, origin );
  14574. v2 = subtract( v2, origin );
  14575. normals.push( normalize( cross( v1, v2 ) ) );
  14576. }
  14577. var normal = [ 0, 0, 0 ];
  14578. for ( var i = 0; i < normals.length; i ++ ) {
  14579. normal[ 0 ] += normals[ i ][ 0 ];
  14580. normal[ 1 ] += normals[ i ][ 1 ];
  14581. normal[ 2 ] += normals[ i ][ 2 ];
  14582. }
  14583. normal[ 0 ] /= normals.length;
  14584. normal[ 1 ] /= normals.length;
  14585. normal[ 2 ] /= normals.length;
  14586. var idx = ( y * width + x ) * 4;
  14587. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14588. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14589. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  14590. output[ idx + 3 ] = 255;
  14591. }
  14592. }
  14593. context.putImageData( imageData, 0, 0 );
  14594. return canvas;
  14595. },
  14596. generateDataTexture: function ( width, height, color ) {
  14597. var size = width * height;
  14598. var data = new Uint8Array( 3 * size );
  14599. var r = Math.floor( color.r * 255 );
  14600. var g = Math.floor( color.g * 255 );
  14601. var b = Math.floor( color.b * 255 );
  14602. for ( var i = 0; i < size; i ++ ) {
  14603. data[ i * 3 ] = r;
  14604. data[ i * 3 + 1 ] = g;
  14605. data[ i * 3 + 2 ] = b;
  14606. }
  14607. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  14608. texture.needsUpdate = true;
  14609. return texture;
  14610. }
  14611. };
  14612. /**
  14613. * @author alteredq / http://alteredqualia.com/
  14614. */
  14615. THREE.SceneUtils = {
  14616. createMultiMaterialObject: function ( geometry, materials ) {
  14617. var group = new THREE.Object3D();
  14618. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14619. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  14620. }
  14621. return group;
  14622. },
  14623. detach : function ( child, parent, scene ) {
  14624. child.applyMatrix( parent.matrixWorld );
  14625. parent.remove( child );
  14626. scene.add( child );
  14627. },
  14628. attach: function ( child, scene, parent ) {
  14629. var matrixWorldInverse = new THREE.Matrix4();
  14630. matrixWorldInverse.getInverse( parent.matrixWorld );
  14631. child.applyMatrix( matrixWorldInverse );
  14632. scene.remove( child );
  14633. parent.add( child );
  14634. }
  14635. };
  14636. /**
  14637. * @author alteredq / http://alteredqualia.com/
  14638. * @author mrdoob / http://mrdoob.com/
  14639. *
  14640. * ShaderUtils currently contains:
  14641. *
  14642. * fresnel
  14643. * normal
  14644. * cube
  14645. *
  14646. */
  14647. THREE.ShaderUtils = {
  14648. lib: {
  14649. /* -------------------------------------------------------------------------
  14650. // Fresnel shader
  14651. // - based on Nvidia Cg tutorial
  14652. ------------------------------------------------------------------------- */
  14653. 'fresnel': {
  14654. uniforms: {
  14655. "mRefractionRatio": { type: "f", value: 1.02 },
  14656. "mFresnelBias": { type: "f", value: 0.1 },
  14657. "mFresnelPower": { type: "f", value: 2.0 },
  14658. "mFresnelScale": { type: "f", value: 1.0 },
  14659. "tCube": { type: "t", value: null }
  14660. },
  14661. fragmentShader: [
  14662. "uniform samplerCube tCube;",
  14663. "varying vec3 vReflect;",
  14664. "varying vec3 vRefract[3];",
  14665. "varying float vReflectionFactor;",
  14666. "void main() {",
  14667. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14668. "vec4 refractedColor = vec4( 1.0 );",
  14669. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  14670. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  14671. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  14672. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  14673. "}"
  14674. ].join("\n"),
  14675. vertexShader: [
  14676. "uniform float mRefractionRatio;",
  14677. "uniform float mFresnelBias;",
  14678. "uniform float mFresnelScale;",
  14679. "uniform float mFresnelPower;",
  14680. "varying vec3 vReflect;",
  14681. "varying vec3 vRefract[3];",
  14682. "varying float vReflectionFactor;",
  14683. "void main() {",
  14684. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14685. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  14686. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  14687. "vec3 I = worldPosition.xyz - cameraPosition;",
  14688. "vReflect = reflect( I, worldNormal );",
  14689. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  14690. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  14691. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  14692. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  14693. "gl_Position = projectionMatrix * mvPosition;",
  14694. "}"
  14695. ].join("\n")
  14696. },
  14697. /* -------------------------------------------------------------------------
  14698. // Normal map shader
  14699. // - Blinn-Phong
  14700. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  14701. // - point and directional lights (use with "lights: true" material option)
  14702. ------------------------------------------------------------------------- */
  14703. 'normal' : {
  14704. uniforms: THREE.UniformsUtils.merge( [
  14705. THREE.UniformsLib[ "fog" ],
  14706. THREE.UniformsLib[ "lights" ],
  14707. THREE.UniformsLib[ "shadowmap" ],
  14708. {
  14709. "enableAO" : { type: "i", value: 0 },
  14710. "enableDiffuse" : { type: "i", value: 0 },
  14711. "enableSpecular" : { type: "i", value: 0 },
  14712. "enableReflection": { type: "i", value: 0 },
  14713. "enableDisplacement": { type: "i", value: 0 },
  14714. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  14715. "tDiffuse" : { type: "t", value: null },
  14716. "tCube" : { type: "t", value: null },
  14717. "tNormal" : { type: "t", value: null },
  14718. "tSpecular" : { type: "t", value: null },
  14719. "tAO" : { type: "t", value: null },
  14720. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14721. "uDisplacementBias": { type: "f", value: 0.0 },
  14722. "uDisplacementScale": { type: "f", value: 1.0 },
  14723. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14724. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  14725. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14726. "uShininess": { type: "f", value: 30 },
  14727. "uOpacity": { type: "f", value: 1 },
  14728. "useRefract": { type: "i", value: 0 },
  14729. "uRefractionRatio": { type: "f", value: 0.98 },
  14730. "uReflectivity": { type: "f", value: 0.5 },
  14731. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  14732. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14733. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  14734. }
  14735. ] ),
  14736. fragmentShader: [
  14737. "uniform vec3 uAmbientColor;",
  14738. "uniform vec3 uDiffuseColor;",
  14739. "uniform vec3 uSpecularColor;",
  14740. "uniform float uShininess;",
  14741. "uniform float uOpacity;",
  14742. "uniform bool enableDiffuse;",
  14743. "uniform bool enableSpecular;",
  14744. "uniform bool enableAO;",
  14745. "uniform bool enableReflection;",
  14746. "uniform sampler2D tDiffuse;",
  14747. "uniform sampler2D tNormal;",
  14748. "uniform sampler2D tSpecular;",
  14749. "uniform sampler2D tAO;",
  14750. "uniform samplerCube tCube;",
  14751. "uniform vec2 uNormalScale;",
  14752. "uniform bool useRefract;",
  14753. "uniform float uRefractionRatio;",
  14754. "uniform float uReflectivity;",
  14755. "varying vec3 vTangent;",
  14756. "varying vec3 vBinormal;",
  14757. "varying vec3 vNormal;",
  14758. "varying vec2 vUv;",
  14759. "uniform vec3 ambientLightColor;",
  14760. "#if MAX_DIR_LIGHTS > 0",
  14761. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  14762. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  14763. "#endif",
  14764. "#if MAX_HEMI_LIGHTS > 0",
  14765. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  14766. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  14767. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  14768. "#endif",
  14769. "#if MAX_POINT_LIGHTS > 0",
  14770. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  14771. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  14772. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  14773. "#endif",
  14774. "#if MAX_SPOT_LIGHTS > 0",
  14775. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  14776. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  14777. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  14778. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  14779. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  14780. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  14781. "#endif",
  14782. "#ifdef WRAP_AROUND",
  14783. "uniform vec3 wrapRGB;",
  14784. "#endif",
  14785. "varying vec3 vWorldPosition;",
  14786. "varying vec3 vViewPosition;",
  14787. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14788. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14789. "void main() {",
  14790. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  14791. "vec3 specularTex = vec3( 1.0 );",
  14792. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  14793. "normalTex.xy *= uNormalScale;",
  14794. "normalTex = normalize( normalTex );",
  14795. "if( enableDiffuse ) {",
  14796. "#ifdef GAMMA_INPUT",
  14797. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  14798. "texelColor.xyz *= texelColor.xyz;",
  14799. "gl_FragColor = gl_FragColor * texelColor;",
  14800. "#else",
  14801. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  14802. "#endif",
  14803. "}",
  14804. "if( enableAO ) {",
  14805. "#ifdef GAMMA_INPUT",
  14806. "vec4 aoColor = texture2D( tAO, vUv );",
  14807. "aoColor.xyz *= aoColor.xyz;",
  14808. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  14809. "#else",
  14810. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  14811. "#endif",
  14812. "}",
  14813. "if( enableSpecular )",
  14814. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  14815. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  14816. "vec3 finalNormal = tsb * normalTex;",
  14817. "#ifdef FLIP_SIDED",
  14818. "finalNormal = -finalNormal;",
  14819. "#endif",
  14820. "vec3 normal = normalize( finalNormal );",
  14821. "vec3 viewPosition = normalize( vViewPosition );",
  14822. // point lights
  14823. "#if MAX_POINT_LIGHTS > 0",
  14824. "vec3 pointDiffuse = vec3( 0.0 );",
  14825. "vec3 pointSpecular = vec3( 0.0 );",
  14826. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  14827. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  14828. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  14829. "float pointDistance = 1.0;",
  14830. "if ( pointLightDistance[ i ] > 0.0 )",
  14831. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  14832. "pointVector = normalize( pointVector );",
  14833. // diffuse
  14834. "#ifdef WRAP_AROUND",
  14835. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  14836. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  14837. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  14838. "#else",
  14839. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  14840. "#endif",
  14841. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  14842. // specular
  14843. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  14844. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  14845. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  14846. "#ifdef PHYSICALLY_BASED_SHADING",
  14847. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14848. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14849. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  14850. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  14851. "#else",
  14852. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  14853. "#endif",
  14854. "}",
  14855. "#endif",
  14856. // spot lights
  14857. "#if MAX_SPOT_LIGHTS > 0",
  14858. "vec3 spotDiffuse = vec3( 0.0 );",
  14859. "vec3 spotSpecular = vec3( 0.0 );",
  14860. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  14861. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  14862. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  14863. "float spotDistance = 1.0;",
  14864. "if ( spotLightDistance[ i ] > 0.0 )",
  14865. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  14866. "spotVector = normalize( spotVector );",
  14867. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  14868. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  14869. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  14870. // diffuse
  14871. "#ifdef WRAP_AROUND",
  14872. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  14873. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  14874. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  14875. "#else",
  14876. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  14877. "#endif",
  14878. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  14879. // specular
  14880. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  14881. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  14882. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  14883. "#ifdef PHYSICALLY_BASED_SHADING",
  14884. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14885. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14886. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  14887. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  14888. "#else",
  14889. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  14890. "#endif",
  14891. "}",
  14892. "}",
  14893. "#endif",
  14894. // directional lights
  14895. "#if MAX_DIR_LIGHTS > 0",
  14896. "vec3 dirDiffuse = vec3( 0.0 );",
  14897. "vec3 dirSpecular = vec3( 0.0 );",
  14898. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  14899. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  14900. "vec3 dirVector = normalize( lDirection.xyz );",
  14901. // diffuse
  14902. "#ifdef WRAP_AROUND",
  14903. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  14904. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  14905. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  14906. "#else",
  14907. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  14908. "#endif",
  14909. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  14910. // specular
  14911. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  14912. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  14913. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  14914. "#ifdef PHYSICALLY_BASED_SHADING",
  14915. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14916. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14917. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  14918. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  14919. "#else",
  14920. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  14921. "#endif",
  14922. "}",
  14923. "#endif",
  14924. // hemisphere lights
  14925. "#if MAX_HEMI_LIGHTS > 0",
  14926. "vec3 hemiDiffuse = vec3( 0.0 );",
  14927. "vec3 hemiSpecular = vec3( 0.0 );" ,
  14928. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  14929. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  14930. "vec3 lVector = normalize( lDirection.xyz );",
  14931. // diffuse
  14932. "float dotProduct = dot( normal, lVector );",
  14933. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  14934. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  14935. "hemiDiffuse += uDiffuseColor * hemiColor;",
  14936. // specular (sky light)
  14937. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  14938. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  14939. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  14940. // specular (ground light)
  14941. "vec3 lVectorGround = -lVector;",
  14942. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  14943. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  14944. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  14945. "#ifdef PHYSICALLY_BASED_SHADING",
  14946. "float dotProductGround = dot( normal, lVectorGround );",
  14947. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14948. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14949. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  14950. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  14951. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  14952. "#else",
  14953. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  14954. "#endif",
  14955. "}",
  14956. "#endif",
  14957. // all lights contribution summation
  14958. "vec3 totalDiffuse = vec3( 0.0 );",
  14959. "vec3 totalSpecular = vec3( 0.0 );",
  14960. "#if MAX_DIR_LIGHTS > 0",
  14961. "totalDiffuse += dirDiffuse;",
  14962. "totalSpecular += dirSpecular;",
  14963. "#endif",
  14964. "#if MAX_HEMI_LIGHTS > 0",
  14965. "totalDiffuse += hemiDiffuse;",
  14966. "totalSpecular += hemiSpecular;",
  14967. "#endif",
  14968. "#if MAX_POINT_LIGHTS > 0",
  14969. "totalDiffuse += pointDiffuse;",
  14970. "totalSpecular += pointSpecular;",
  14971. "#endif",
  14972. "#if MAX_SPOT_LIGHTS > 0",
  14973. "totalDiffuse += spotDiffuse;",
  14974. "totalSpecular += spotSpecular;",
  14975. "#endif",
  14976. "#ifdef METAL",
  14977. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  14978. "#else",
  14979. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  14980. "#endif",
  14981. "if ( enableReflection ) {",
  14982. "vec3 vReflect;",
  14983. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  14984. "if ( useRefract ) {",
  14985. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  14986. "} else {",
  14987. "vReflect = reflect( cameraToVertex, normal );",
  14988. "}",
  14989. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14990. "#ifdef GAMMA_INPUT",
  14991. "cubeColor.xyz *= cubeColor.xyz;",
  14992. "#endif",
  14993. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  14994. "}",
  14995. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14996. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14997. THREE.ShaderChunk[ "fog_fragment" ],
  14998. "}"
  14999. ].join("\n"),
  15000. vertexShader: [
  15001. "attribute vec4 tangent;",
  15002. "uniform vec2 uOffset;",
  15003. "uniform vec2 uRepeat;",
  15004. "uniform bool enableDisplacement;",
  15005. "#ifdef VERTEX_TEXTURES",
  15006. "uniform sampler2D tDisplacement;",
  15007. "uniform float uDisplacementScale;",
  15008. "uniform float uDisplacementBias;",
  15009. "#endif",
  15010. "varying vec3 vTangent;",
  15011. "varying vec3 vBinormal;",
  15012. "varying vec3 vNormal;",
  15013. "varying vec2 vUv;",
  15014. "varying vec3 vWorldPosition;",
  15015. "varying vec3 vViewPosition;",
  15016. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15017. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15018. "void main() {",
  15019. THREE.ShaderChunk[ "skinbase_vertex" ],
  15020. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15021. // normal, tangent and binormal vectors
  15022. "#ifdef USE_SKINNING",
  15023. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15024. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15025. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15026. "#else",
  15027. "vNormal = normalize( normalMatrix * normal );",
  15028. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15029. "#endif",
  15030. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15031. "vUv = uv * uRepeat + uOffset;",
  15032. // displacement mapping
  15033. "vec3 displacedPosition;",
  15034. "#ifdef VERTEX_TEXTURES",
  15035. "if ( enableDisplacement ) {",
  15036. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15037. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15038. "displacedPosition = position + normalize( normal ) * df;",
  15039. "} else {",
  15040. "#ifdef USE_SKINNING",
  15041. "vec4 skinVertex = vec4( position, 1.0 );",
  15042. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15043. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15044. "displacedPosition = skinned.xyz;",
  15045. "#else",
  15046. "displacedPosition = position;",
  15047. "#endif",
  15048. "}",
  15049. "#else",
  15050. "#ifdef USE_SKINNING",
  15051. "vec4 skinVertex = vec4( position, 1.0 );",
  15052. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15053. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15054. "displacedPosition = skinned.xyz;",
  15055. "#else",
  15056. "displacedPosition = position;",
  15057. "#endif",
  15058. "#endif",
  15059. //
  15060. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15061. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15062. "gl_Position = projectionMatrix * mvPosition;",
  15063. //
  15064. "vWorldPosition = worldPosition.xyz;",
  15065. "vViewPosition = -mvPosition.xyz;",
  15066. // shadows
  15067. "#ifdef USE_SHADOWMAP",
  15068. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15069. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15070. "}",
  15071. "#endif",
  15072. "}"
  15073. ].join("\n")
  15074. },
  15075. /* -------------------------------------------------------------------------
  15076. // Cube map shader
  15077. ------------------------------------------------------------------------- */
  15078. 'cube': {
  15079. uniforms: { "tCube": { type: "t", value: null },
  15080. "tFlip": { type: "f", value: -1 } },
  15081. vertexShader: [
  15082. "varying vec3 vWorldPosition;",
  15083. "void main() {",
  15084. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15085. "vWorldPosition = worldPosition.xyz;",
  15086. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15087. "}"
  15088. ].join("\n"),
  15089. fragmentShader: [
  15090. "uniform samplerCube tCube;",
  15091. "uniform float tFlip;",
  15092. "varying vec3 vWorldPosition;",
  15093. "void main() {",
  15094. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15095. "}"
  15096. ].join("\n")
  15097. }
  15098. }
  15099. };
  15100. /**
  15101. * @author zz85 / http://www.lab4games.net/zz85/blog
  15102. * @author alteredq / http://alteredqualia.com/
  15103. *
  15104. * For Text operations in three.js (See TextGeometry)
  15105. *
  15106. * It uses techniques used in:
  15107. *
  15108. * typeface.js and canvastext
  15109. * For converting fonts and rendering with javascript
  15110. * http://typeface.neocracy.org
  15111. *
  15112. * Triangulation ported from AS3
  15113. * Simple Polygon Triangulation
  15114. * http://actionsnippet.com/?p=1462
  15115. *
  15116. * A Method to triangulate shapes with holes
  15117. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15118. *
  15119. */
  15120. THREE.FontUtils = {
  15121. faces : {},
  15122. // Just for now. face[weight][style]
  15123. face : "helvetiker",
  15124. weight: "normal",
  15125. style : "normal",
  15126. size : 150,
  15127. divisions : 10,
  15128. getFace : function() {
  15129. return this.faces[ this.face ][ this.weight ][ this.style ];
  15130. },
  15131. loadFace : function( data ) {
  15132. var family = data.familyName.toLowerCase();
  15133. var ThreeFont = this;
  15134. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15135. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15136. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15137. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15138. return data;
  15139. },
  15140. drawText : function( text ) {
  15141. var characterPts = [], allPts = [];
  15142. // RenderText
  15143. var i, p,
  15144. face = this.getFace(),
  15145. scale = this.size / face.resolution,
  15146. offset = 0,
  15147. chars = String( text ).split( '' ),
  15148. length = chars.length;
  15149. var fontPaths = [];
  15150. for ( i = 0; i < length; i ++ ) {
  15151. var path = new THREE.Path();
  15152. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15153. offset += ret.offset;
  15154. fontPaths.push( ret.path );
  15155. }
  15156. // get the width
  15157. var width = offset / 2;
  15158. //
  15159. // for ( p = 0; p < allPts.length; p++ ) {
  15160. //
  15161. // allPts[ p ].x -= width;
  15162. //
  15163. // }
  15164. //var extract = this.extractPoints( allPts, characterPts );
  15165. //extract.contour = allPts;
  15166. //extract.paths = fontPaths;
  15167. //extract.offset = width;
  15168. return { paths : fontPaths, offset : width };
  15169. },
  15170. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15171. var pts = [];
  15172. var i, i2, divisions,
  15173. outline, action, length,
  15174. scaleX, scaleY,
  15175. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15176. laste,
  15177. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15178. if ( !glyph ) return;
  15179. if ( glyph.o ) {
  15180. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15181. length = outline.length;
  15182. scaleX = scale;
  15183. scaleY = scale;
  15184. for ( i = 0; i < length; ) {
  15185. action = outline[ i ++ ];
  15186. //console.log( action );
  15187. switch( action ) {
  15188. case 'm':
  15189. // Move To
  15190. x = outline[ i++ ] * scaleX + offset;
  15191. y = outline[ i++ ] * scaleY;
  15192. path.moveTo( x, y );
  15193. break;
  15194. case 'l':
  15195. // Line To
  15196. x = outline[ i++ ] * scaleX + offset;
  15197. y = outline[ i++ ] * scaleY;
  15198. path.lineTo(x,y);
  15199. break;
  15200. case 'q':
  15201. // QuadraticCurveTo
  15202. cpx = outline[ i++ ] * scaleX + offset;
  15203. cpy = outline[ i++ ] * scaleY;
  15204. cpx1 = outline[ i++ ] * scaleX + offset;
  15205. cpy1 = outline[ i++ ] * scaleY;
  15206. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15207. laste = pts[ pts.length - 1 ];
  15208. if ( laste ) {
  15209. cpx0 = laste.x;
  15210. cpy0 = laste.y;
  15211. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15212. var t = i2 / divisions;
  15213. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15214. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15215. }
  15216. }
  15217. break;
  15218. case 'b':
  15219. // Cubic Bezier Curve
  15220. cpx = outline[ i++ ] * scaleX + offset;
  15221. cpy = outline[ i++ ] * scaleY;
  15222. cpx1 = outline[ i++ ] * scaleX + offset;
  15223. cpy1 = outline[ i++ ] * -scaleY;
  15224. cpx2 = outline[ i++ ] * scaleX + offset;
  15225. cpy2 = outline[ i++ ] * -scaleY;
  15226. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15227. laste = pts[ pts.length - 1 ];
  15228. if ( laste ) {
  15229. cpx0 = laste.x;
  15230. cpy0 = laste.y;
  15231. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15232. var t = i2 / divisions;
  15233. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15234. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15235. }
  15236. }
  15237. break;
  15238. }
  15239. }
  15240. }
  15241. return { offset: glyph.ha*scale, path:path};
  15242. }
  15243. };
  15244. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15245. // Parameters
  15246. parameters = parameters || {};
  15247. var size = parameters.size !== undefined ? parameters.size : 100;
  15248. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15249. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15250. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15251. var style = parameters.style !== undefined ? parameters.style : "normal";
  15252. THREE.FontUtils.size = size;
  15253. THREE.FontUtils.divisions = curveSegments;
  15254. THREE.FontUtils.face = font;
  15255. THREE.FontUtils.weight = weight;
  15256. THREE.FontUtils.style = style;
  15257. // Get a Font data json object
  15258. var data = THREE.FontUtils.drawText( text );
  15259. var paths = data.paths;
  15260. var shapes = [];
  15261. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15262. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15263. }
  15264. return shapes;
  15265. };
  15266. /**
  15267. * This code is a quick port of code written in C++ which was submitted to
  15268. * flipcode.com by John W. Ratcliff // July 22, 2000
  15269. * See original code and more information here:
  15270. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15271. *
  15272. * ported to actionscript by Zevan Rosser
  15273. * www.actionsnippet.com
  15274. *
  15275. * ported to javascript by Joshua Koo
  15276. * http://www.lab4games.net/zz85/blog
  15277. *
  15278. */
  15279. ( function( namespace ) {
  15280. var EPSILON = 0.0000000001;
  15281. // takes in an contour array and returns
  15282. var process = function( contour, indices ) {
  15283. var n = contour.length;
  15284. if ( n < 3 ) return null;
  15285. var result = [],
  15286. verts = [],
  15287. vertIndices = [];
  15288. /* we want a counter-clockwise polygon in verts */
  15289. var u, v, w;
  15290. if ( area( contour ) > 0.0 ) {
  15291. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15292. } else {
  15293. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15294. }
  15295. var nv = n;
  15296. /* remove nv - 2 vertices, creating 1 triangle every time */
  15297. var count = 2 * nv; /* error detection */
  15298. for( v = nv - 1; nv > 2; ) {
  15299. /* if we loop, it is probably a non-simple polygon */
  15300. if ( ( count-- ) <= 0 ) {
  15301. //** Triangulate: ERROR - probable bad polygon!
  15302. //throw ( "Warning, unable to triangulate polygon!" );
  15303. //return null;
  15304. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15305. console.log( "Warning, unable to triangulate polygon!" );
  15306. if ( indices ) return vertIndices;
  15307. return result;
  15308. }
  15309. /* three consecutive vertices in current polygon, <u,v,w> */
  15310. u = v; if ( nv <= u ) u = 0; /* previous */
  15311. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15312. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15313. if ( snip( contour, u, v, w, nv, verts ) ) {
  15314. var a, b, c, s, t;
  15315. /* true names of the vertices */
  15316. a = verts[ u ];
  15317. b = verts[ v ];
  15318. c = verts[ w ];
  15319. /* output Triangle */
  15320. /*
  15321. result.push( contour[ a ] );
  15322. result.push( contour[ b ] );
  15323. result.push( contour[ c ] );
  15324. */
  15325. result.push( [ contour[ a ],
  15326. contour[ b ],
  15327. contour[ c ] ] );
  15328. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15329. /* remove v from the remaining polygon */
  15330. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15331. verts[ s ] = verts[ t ];
  15332. }
  15333. nv--;
  15334. /* reset error detection counter */
  15335. count = 2 * nv;
  15336. }
  15337. }
  15338. if ( indices ) return vertIndices;
  15339. return result;
  15340. };
  15341. // calculate area of the contour polygon
  15342. var area = function ( contour ) {
  15343. var n = contour.length;
  15344. var a = 0.0;
  15345. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15346. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15347. }
  15348. return a * 0.5;
  15349. };
  15350. // see if p is inside triangle abc
  15351. var insideTriangle = function( ax, ay,
  15352. bx, by,
  15353. cx, cy,
  15354. px, py ) {
  15355. var aX, aY, bX, bY;
  15356. var cX, cY, apx, apy;
  15357. var bpx, bpy, cpx, cpy;
  15358. var cCROSSap, bCROSScp, aCROSSbp;
  15359. aX = cx - bx; aY = cy - by;
  15360. bX = ax - cx; bY = ay - cy;
  15361. cX = bx - ax; cY = by - ay;
  15362. apx= px -ax; apy= py - ay;
  15363. bpx= px - bx; bpy= py - by;
  15364. cpx= px - cx; cpy= py - cy;
  15365. aCROSSbp = aX*bpy - aY*bpx;
  15366. cCROSSap = cX*apy - cY*apx;
  15367. bCROSScp = bX*cpy - bY*cpx;
  15368. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15369. };
  15370. var snip = function ( contour, u, v, w, n, verts ) {
  15371. var p;
  15372. var ax, ay, bx, by;
  15373. var cx, cy, px, py;
  15374. ax = contour[ verts[ u ] ].x;
  15375. ay = contour[ verts[ u ] ].y;
  15376. bx = contour[ verts[ v ] ].x;
  15377. by = contour[ verts[ v ] ].y;
  15378. cx = contour[ verts[ w ] ].x;
  15379. cy = contour[ verts[ w ] ].y;
  15380. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15381. for ( p = 0; p < n; p++ ) {
  15382. if( (p == u) || (p == v) || (p == w) ) continue;
  15383. px = contour[ verts[ p ] ].x
  15384. py = contour[ verts[ p ] ].y
  15385. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15386. }
  15387. return true;
  15388. };
  15389. namespace.Triangulate = process;
  15390. namespace.Triangulate.area = area;
  15391. return namespace;
  15392. })(THREE.FontUtils);
  15393. // To use the typeface.js face files, hook up the API
  15394. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  15395. * @author zz85 / http://www.lab4games.net/zz85/blog
  15396. * Extensible curve object
  15397. *
  15398. * Some common of Curve methods
  15399. * .getPoint(t), getTangent(t)
  15400. * .getPointAt(u), getTagentAt(u)
  15401. * .getPoints(), .getSpacedPoints()
  15402. * .getLength()
  15403. * .updateArcLengths()
  15404. *
  15405. * This file contains following classes:
  15406. *
  15407. * -- 2d classes --
  15408. * THREE.Curve
  15409. * THREE.LineCurve
  15410. * THREE.QuadraticBezierCurve
  15411. * THREE.CubicBezierCurve
  15412. * THREE.SplineCurve
  15413. * THREE.ArcCurve
  15414. * THREE.EllipseCurve
  15415. *
  15416. * -- 3d classes --
  15417. * THREE.LineCurve3
  15418. * THREE.QuadraticBezierCurve3
  15419. * THREE.CubicBezierCurve3
  15420. * THREE.SplineCurve3
  15421. * THREE.ClosedSplineCurve3
  15422. *
  15423. * A series of curves can be represented as a THREE.CurvePath
  15424. *
  15425. **/
  15426. /**************************************************************
  15427. * Abstract Curve base class
  15428. **************************************************************/
  15429. THREE.Curve = function () {
  15430. };
  15431. // Virtual base class method to overwrite and implement in subclasses
  15432. // - t [0 .. 1]
  15433. THREE.Curve.prototype.getPoint = function ( t ) {
  15434. console.log( "Warning, getPoint() not implemented!" );
  15435. return null;
  15436. };
  15437. // Get point at relative position in curve according to arc length
  15438. // - u [0 .. 1]
  15439. THREE.Curve.prototype.getPointAt = function ( u ) {
  15440. var t = this.getUtoTmapping( u );
  15441. return this.getPoint( t );
  15442. };
  15443. // Get sequence of points using getPoint( t )
  15444. THREE.Curve.prototype.getPoints = function ( divisions ) {
  15445. if ( !divisions ) divisions = 5;
  15446. var d, pts = [];
  15447. for ( d = 0; d <= divisions; d ++ ) {
  15448. pts.push( this.getPoint( d / divisions ) );
  15449. }
  15450. return pts;
  15451. };
  15452. // Get sequence of points using getPointAt( u )
  15453. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  15454. if ( !divisions ) divisions = 5;
  15455. var d, pts = [];
  15456. for ( d = 0; d <= divisions; d ++ ) {
  15457. pts.push( this.getPointAt( d / divisions ) );
  15458. }
  15459. return pts;
  15460. };
  15461. // Get total curve arc length
  15462. THREE.Curve.prototype.getLength = function () {
  15463. var lengths = this.getLengths();
  15464. return lengths[ lengths.length - 1 ];
  15465. };
  15466. // Get list of cumulative segment lengths
  15467. THREE.Curve.prototype.getLengths = function ( divisions ) {
  15468. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  15469. if ( this.cacheArcLengths
  15470. && ( this.cacheArcLengths.length == divisions + 1 )
  15471. && !this.needsUpdate) {
  15472. //console.log( "cached", this.cacheArcLengths );
  15473. return this.cacheArcLengths;
  15474. }
  15475. this.needsUpdate = false;
  15476. var cache = [];
  15477. var current, last = this.getPoint( 0 );
  15478. var p, sum = 0;
  15479. cache.push( 0 );
  15480. for ( p = 1; p <= divisions; p ++ ) {
  15481. current = this.getPoint ( p / divisions );
  15482. sum += current.distanceTo( last );
  15483. cache.push( sum );
  15484. last = current;
  15485. }
  15486. this.cacheArcLengths = cache;
  15487. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  15488. };
  15489. THREE.Curve.prototype.updateArcLengths = function() {
  15490. this.needsUpdate = true;
  15491. this.getLengths();
  15492. };
  15493. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  15494. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  15495. var arcLengths = this.getLengths();
  15496. var i = 0, il = arcLengths.length;
  15497. var targetArcLength; // The targeted u distance value to get
  15498. if ( distance ) {
  15499. targetArcLength = distance;
  15500. } else {
  15501. targetArcLength = u * arcLengths[ il - 1 ];
  15502. }
  15503. //var time = Date.now();
  15504. // binary search for the index with largest value smaller than target u distance
  15505. var low = 0, high = il - 1, comparison;
  15506. while ( low <= high ) {
  15507. 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
  15508. comparison = arcLengths[ i ] - targetArcLength;
  15509. if ( comparison < 0 ) {
  15510. low = i + 1;
  15511. continue;
  15512. } else if ( comparison > 0 ) {
  15513. high = i - 1;
  15514. continue;
  15515. } else {
  15516. high = i;
  15517. break;
  15518. // DONE
  15519. }
  15520. }
  15521. i = high;
  15522. //console.log('b' , i, low, high, Date.now()- time);
  15523. if ( arcLengths[ i ] == targetArcLength ) {
  15524. var t = i / ( il - 1 );
  15525. return t;
  15526. }
  15527. // we could get finer grain at lengths, or use simple interpolatation between two points
  15528. var lengthBefore = arcLengths[ i ];
  15529. var lengthAfter = arcLengths[ i + 1 ];
  15530. var segmentLength = lengthAfter - lengthBefore;
  15531. // determine where we are between the 'before' and 'after' points
  15532. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  15533. // add that fractional amount to t
  15534. var t = ( i + segmentFraction ) / ( il -1 );
  15535. return t;
  15536. };
  15537. // In 2D space, there are actually 2 normal vectors,
  15538. // and in 3D space, infinte
  15539. // TODO this should be depreciated.
  15540. THREE.Curve.prototype.getNormalVector = function( t ) {
  15541. var vec = this.getTangent( t );
  15542. return new THREE.Vector2( -vec.y , vec.x );
  15543. };
  15544. // Returns a unit vector tangent at t
  15545. // In case any sub curve does not implement its tangent / normal finding,
  15546. // we get 2 points with a small delta and find a gradient of the 2 points
  15547. // which seems to make a reasonable approximation
  15548. THREE.Curve.prototype.getTangent = function( t ) {
  15549. var delta = 0.0001;
  15550. var t1 = t - delta;
  15551. var t2 = t + delta;
  15552. // Capping in case of danger
  15553. if ( t1 < 0 ) t1 = 0;
  15554. if ( t2 > 1 ) t2 = 1;
  15555. var pt1 = this.getPoint( t1 );
  15556. var pt2 = this.getPoint( t2 );
  15557. var vec = pt2.clone().subSelf(pt1);
  15558. return vec.normalize();
  15559. };
  15560. THREE.Curve.prototype.getTangentAt = function ( u ) {
  15561. var t = this.getUtoTmapping( u );
  15562. return this.getTangent( t );
  15563. };
  15564. /**************************************************************
  15565. * Line
  15566. **************************************************************/
  15567. THREE.LineCurve = function ( v1, v2 ) {
  15568. this.v1 = v1;
  15569. this.v2 = v2;
  15570. };
  15571. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  15572. THREE.LineCurve.prototype.getPoint = function ( t ) {
  15573. var point = this.v2.clone().subSelf(this.v1);
  15574. point.multiplyScalar( t ).addSelf( this.v1 );
  15575. return point;
  15576. };
  15577. // Line curve is linear, so we can overwrite default getPointAt
  15578. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  15579. return this.getPoint( u );
  15580. };
  15581. THREE.LineCurve.prototype.getTangent = function( t ) {
  15582. var tangent = this.v2.clone().subSelf(this.v1);
  15583. return tangent.normalize();
  15584. };
  15585. /**************************************************************
  15586. * Quadratic Bezier curve
  15587. **************************************************************/
  15588. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  15589. this.v0 = v0;
  15590. this.v1 = v1;
  15591. this.v2 = v2;
  15592. };
  15593. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15594. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  15595. var tx, ty;
  15596. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15597. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15598. return new THREE.Vector2( tx, ty );
  15599. };
  15600. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  15601. var tx, ty;
  15602. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  15603. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  15604. // returns unit vector
  15605. var tangent = new THREE.Vector2( tx, ty );
  15606. tangent.normalize();
  15607. return tangent;
  15608. };
  15609. /**************************************************************
  15610. * Cubic Bezier curve
  15611. **************************************************************/
  15612. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  15613. this.v0 = v0;
  15614. this.v1 = v1;
  15615. this.v2 = v2;
  15616. this.v3 = v3;
  15617. };
  15618. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15619. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  15620. var tx, ty;
  15621. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15622. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15623. return new THREE.Vector2( tx, ty );
  15624. };
  15625. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  15626. var tx, ty;
  15627. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15628. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15629. var tangent = new THREE.Vector2( tx, ty );
  15630. tangent.normalize();
  15631. return tangent;
  15632. };
  15633. /**************************************************************
  15634. * Spline curve
  15635. **************************************************************/
  15636. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  15637. this.points = (points == undefined) ? [] : points;
  15638. };
  15639. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  15640. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  15641. var v = new THREE.Vector2();
  15642. var c = [];
  15643. var points = this.points, point, intPoint, weight;
  15644. point = ( points.length - 1 ) * t;
  15645. intPoint = Math.floor( point );
  15646. weight = point - intPoint;
  15647. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15648. c[ 1 ] = intPoint;
  15649. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  15650. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  15651. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15652. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15653. return v;
  15654. };
  15655. /**************************************************************
  15656. * Ellipse curve
  15657. **************************************************************/
  15658. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  15659. aStartAngle, aEndAngle,
  15660. aClockwise ) {
  15661. this.aX = aX;
  15662. this.aY = aY;
  15663. this.xRadius = xRadius;
  15664. this.yRadius = yRadius;
  15665. this.aStartAngle = aStartAngle;
  15666. this.aEndAngle = aEndAngle;
  15667. this.aClockwise = aClockwise;
  15668. };
  15669. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  15670. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  15671. var deltaAngle = this.aEndAngle - this.aStartAngle;
  15672. if ( !this.aClockwise ) {
  15673. t = 1 - t;
  15674. }
  15675. var angle = this.aStartAngle + t * deltaAngle;
  15676. var tx = this.aX + this.xRadius * Math.cos( angle );
  15677. var ty = this.aY + this.yRadius * Math.sin( angle );
  15678. return new THREE.Vector2( tx, ty );
  15679. };
  15680. /**************************************************************
  15681. * Arc curve
  15682. **************************************************************/
  15683. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  15684. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  15685. };
  15686. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  15687. /**************************************************************
  15688. * Utils
  15689. **************************************************************/
  15690. THREE.Curve.Utils = {
  15691. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  15692. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  15693. },
  15694. // Puay Bing, thanks for helping with this derivative!
  15695. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  15696. return -3 * p0 * (1 - t) * (1 - t) +
  15697. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  15698. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  15699. 3 * t * t * p3;
  15700. },
  15701. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  15702. // To check if my formulas are correct
  15703. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  15704. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  15705. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  15706. var h11 = 3 * t * t - 2 * t; // t3 − t2
  15707. return h00 + h10 + h01 + h11;
  15708. },
  15709. // Catmull-Rom
  15710. interpolate: function( p0, p1, p2, p3, t ) {
  15711. var v0 = ( p2 - p0 ) * 0.5;
  15712. var v1 = ( p3 - p1 ) * 0.5;
  15713. var t2 = t * t;
  15714. var t3 = t * t2;
  15715. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  15716. }
  15717. };
  15718. // TODO: Transformation for Curves?
  15719. /**************************************************************
  15720. * 3D Curves
  15721. **************************************************************/
  15722. // A Factory method for creating new curve subclasses
  15723. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15724. constructor.prototype = Object.create( THREE.Curve.prototype );
  15725. constructor.prototype.getPoint = getPointFunc;
  15726. return constructor;
  15727. };
  15728. /**************************************************************
  15729. * Line3D
  15730. **************************************************************/
  15731. THREE.LineCurve3 = THREE.Curve.create(
  15732. function ( v1, v2 ) {
  15733. this.v1 = v1;
  15734. this.v2 = v2;
  15735. },
  15736. function ( t ) {
  15737. var r = new THREE.Vector3();
  15738. r.sub( this.v2, this.v1 ); // diff
  15739. r.multiplyScalar( t );
  15740. r.addSelf( this.v1 );
  15741. return r;
  15742. }
  15743. );
  15744. /**************************************************************
  15745. * Quadratic Bezier 3D curve
  15746. **************************************************************/
  15747. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  15748. function ( v0, v1, v2 ) {
  15749. this.v0 = v0;
  15750. this.v1 = v1;
  15751. this.v2 = v2;
  15752. },
  15753. function ( t ) {
  15754. var tx, ty, tz;
  15755. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15756. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15757. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  15758. return new THREE.Vector3( tx, ty, tz );
  15759. }
  15760. );
  15761. /**************************************************************
  15762. * Cubic Bezier 3D curve
  15763. **************************************************************/
  15764. THREE.CubicBezierCurve3 = THREE.Curve.create(
  15765. function ( v0, v1, v2, v3 ) {
  15766. this.v0 = v0;
  15767. this.v1 = v1;
  15768. this.v2 = v2;
  15769. this.v3 = v3;
  15770. },
  15771. function ( t ) {
  15772. var tx, ty, tz;
  15773. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15774. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15775. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  15776. return new THREE.Vector3( tx, ty, tz );
  15777. }
  15778. );
  15779. /**************************************************************
  15780. * Spline 3D curve
  15781. **************************************************************/
  15782. THREE.SplineCurve3 = THREE.Curve.create(
  15783. function ( points /* array of Vector3 */) {
  15784. this.points = (points == undefined) ? [] : points;
  15785. },
  15786. function ( t ) {
  15787. var v = new THREE.Vector3();
  15788. var c = [];
  15789. var points = this.points, point, intPoint, weight;
  15790. point = ( points.length - 1 ) * t;
  15791. intPoint = Math.floor( point );
  15792. weight = point - intPoint;
  15793. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15794. c[ 1 ] = intPoint;
  15795. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15796. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15797. var pt0 = points[ c[0] ],
  15798. pt1 = points[ c[1] ],
  15799. pt2 = points[ c[2] ],
  15800. pt3 = points[ c[3] ];
  15801. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  15802. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  15803. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  15804. return v;
  15805. }
  15806. );
  15807. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  15808. // var v = new THREE.Vector3();
  15809. // var c = [];
  15810. // var points = this.points, point, intPoint, weight;
  15811. // point = ( points.length - 1 ) * t;
  15812. // intPoint = Math.floor( point );
  15813. // weight = point - intPoint;
  15814. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15815. // c[ 1 ] = intPoint;
  15816. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15817. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15818. // var pt0 = points[ c[0] ],
  15819. // pt1 = points[ c[1] ],
  15820. // pt2 = points[ c[2] ],
  15821. // pt3 = points[ c[3] ];
  15822. // // t = weight;
  15823. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  15824. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  15825. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  15826. // return v;
  15827. // }
  15828. /**************************************************************
  15829. * Closed Spline 3D curve
  15830. **************************************************************/
  15831. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  15832. function ( points /* array of Vector3 */) {
  15833. this.points = (points == undefined) ? [] : points;
  15834. },
  15835. function ( t ) {
  15836. var v = new THREE.Vector3();
  15837. var c = [];
  15838. var points = this.points, point, intPoint, weight;
  15839. point = ( points.length - 0 ) * t;
  15840. // This needs to be from 0-length +1
  15841. intPoint = Math.floor( point );
  15842. weight = point - intPoint;
  15843. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  15844. c[ 0 ] = ( intPoint - 1 ) % points.length;
  15845. c[ 1 ] = ( intPoint ) % points.length;
  15846. c[ 2 ] = ( intPoint + 1 ) % points.length;
  15847. c[ 3 ] = ( intPoint + 2 ) % points.length;
  15848. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15849. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15850. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  15851. return v;
  15852. }
  15853. );
  15854. /**
  15855. * @author zz85 / http://www.lab4games.net/zz85/blog
  15856. *
  15857. **/
  15858. /**************************************************************
  15859. * Curved Path - a curve path is simply a array of connected
  15860. * curves, but retains the api of a curve
  15861. **************************************************************/
  15862. THREE.CurvePath = function () {
  15863. this.curves = [];
  15864. this.bends = [];
  15865. this.autoClose = false; // Automatically closes the path
  15866. };
  15867. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15868. THREE.CurvePath.prototype.add = function ( curve ) {
  15869. this.curves.push( curve );
  15870. };
  15871. THREE.CurvePath.prototype.checkConnection = function() {
  15872. // TODO
  15873. // If the ending of curve is not connected to the starting
  15874. // or the next curve, then, this is not a real path
  15875. };
  15876. THREE.CurvePath.prototype.closePath = function() {
  15877. // TODO Test
  15878. // and verify for vector3 (needs to implement equals)
  15879. // Add a line curve if start and end of lines are not connected
  15880. var startPoint = this.curves[0].getPoint(0);
  15881. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  15882. if (!startPoint.equals(endPoint)) {
  15883. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  15884. }
  15885. };
  15886. // To get accurate point with reference to
  15887. // entire path distance at time t,
  15888. // following has to be done:
  15889. // 1. Length of each sub path have to be known
  15890. // 2. Locate and identify type of curve
  15891. // 3. Get t for the curve
  15892. // 4. Return curve.getPointAt(t')
  15893. THREE.CurvePath.prototype.getPoint = function( t ) {
  15894. var d = t * this.getLength();
  15895. var curveLengths = this.getCurveLengths();
  15896. var i = 0, diff, curve;
  15897. // To think about boundaries points.
  15898. while ( i < curveLengths.length ) {
  15899. if ( curveLengths[ i ] >= d ) {
  15900. diff = curveLengths[ i ] - d;
  15901. curve = this.curves[ i ];
  15902. var u = 1 - diff / curve.getLength();
  15903. return curve.getPointAt( u );
  15904. break;
  15905. }
  15906. i ++;
  15907. }
  15908. return null;
  15909. // loop where sum != 0, sum > d , sum+1 <d
  15910. };
  15911. /*
  15912. THREE.CurvePath.prototype.getTangent = function( t ) {
  15913. };*/
  15914. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  15915. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  15916. // getPoint() depends on getLength
  15917. THREE.CurvePath.prototype.getLength = function() {
  15918. var lens = this.getCurveLengths();
  15919. return lens[ lens.length - 1 ];
  15920. };
  15921. // Compute lengths and cache them
  15922. // We cannot overwrite getLengths() because UtoT mapping uses it.
  15923. THREE.CurvePath.prototype.getCurveLengths = function() {
  15924. // We use cache values if curves and cache array are same length
  15925. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  15926. return this.cacheLengths;
  15927. };
  15928. // Get length of subsurve
  15929. // Push sums into cached array
  15930. var lengths = [], sums = 0;
  15931. var i, il = this.curves.length;
  15932. for ( i = 0; i < il; i ++ ) {
  15933. sums += this.curves[ i ].getLength();
  15934. lengths.push( sums );
  15935. }
  15936. this.cacheLengths = lengths;
  15937. return lengths;
  15938. };
  15939. // Returns min and max coordinates, as well as centroid
  15940. THREE.CurvePath.prototype.getBoundingBox = function () {
  15941. var points = this.getPoints();
  15942. var maxX, maxY, maxZ;
  15943. var minX, minY, minZ;
  15944. maxX = maxY = Number.NEGATIVE_INFINITY;
  15945. minX = minY = Number.POSITIVE_INFINITY;
  15946. var p, i, il, sum;
  15947. var v3 = points[0] instanceof THREE.Vector3;
  15948. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  15949. for ( i = 0, il = points.length; i < il; i ++ ) {
  15950. p = points[ i ];
  15951. if ( p.x > maxX ) maxX = p.x;
  15952. else if ( p.x < minX ) minX = p.x;
  15953. if ( p.y > maxY ) maxY = p.y;
  15954. else if ( p.y < minY ) minY = p.y;
  15955. if (v3) {
  15956. if ( p.z > maxZ ) maxZ = p.z;
  15957. else if ( p.z < minZ ) minZ = p.z;
  15958. }
  15959. sum.addSelf( p );
  15960. }
  15961. var ret = {
  15962. minX: minX,
  15963. minY: minY,
  15964. maxX: maxX,
  15965. maxY: maxY,
  15966. centroid: sum.divideScalar( il )
  15967. };
  15968. if (v3) {
  15969. ret.maxZ = maxZ;
  15970. ret.minZ = minZ;
  15971. }
  15972. return ret;
  15973. };
  15974. /**************************************************************
  15975. * Create Geometries Helpers
  15976. **************************************************************/
  15977. /// Generate geometry from path points (for Line or ParticleSystem objects)
  15978. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  15979. var pts = this.getPoints( divisions, true );
  15980. return this.createGeometry( pts );
  15981. };
  15982. // Generate geometry from equidistance sampling along the path
  15983. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  15984. var pts = this.getSpacedPoints( divisions, true );
  15985. return this.createGeometry( pts );
  15986. };
  15987. THREE.CurvePath.prototype.createGeometry = function( points ) {
  15988. var geometry = new THREE.Geometry();
  15989. for ( var i = 0; i < points.length; i ++ ) {
  15990. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  15991. }
  15992. return geometry;
  15993. };
  15994. /**************************************************************
  15995. * Bend / Wrap Helper Methods
  15996. **************************************************************/
  15997. // Wrap path / Bend modifiers?
  15998. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  15999. this.bends.push( bendpath );
  16000. };
  16001. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16002. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16003. var i, il;
  16004. if ( !bends ) {
  16005. bends = this.bends;
  16006. }
  16007. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16008. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16009. }
  16010. return oldPts;
  16011. };
  16012. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16013. var oldPts = this.getSpacedPoints( segments );
  16014. var i, il;
  16015. if ( !bends ) {
  16016. bends = this.bends;
  16017. }
  16018. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16019. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16020. }
  16021. return oldPts;
  16022. };
  16023. // This returns getPoints() bend/wrapped around the contour of a path.
  16024. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16025. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16026. var bounds = this.getBoundingBox();
  16027. var i, il, p, oldX, oldY, xNorm;
  16028. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16029. p = oldPts[ i ];
  16030. oldX = p.x;
  16031. oldY = p.y;
  16032. xNorm = oldX / bounds.maxX;
  16033. // If using actual distance, for length > path, requires line extrusions
  16034. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16035. xNorm = path.getUtoTmapping( xNorm, oldX );
  16036. // check for out of bounds?
  16037. var pathPt = path.getPoint( xNorm );
  16038. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16039. p.x = pathPt.x + normal.x;
  16040. p.y = pathPt.y + normal.y;
  16041. }
  16042. return oldPts;
  16043. };
  16044. /**
  16045. * @author alteredq / http://alteredqualia.com/
  16046. */
  16047. THREE.Gyroscope = function () {
  16048. THREE.Object3D.call( this );
  16049. };
  16050. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16051. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16052. this.matrixAutoUpdate && this.updateMatrix();
  16053. // update matrixWorld
  16054. if ( this.matrixWorldNeedsUpdate || force ) {
  16055. if ( this.parent ) {
  16056. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  16057. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16058. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16059. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16060. } else {
  16061. this.matrixWorld.copy( this.matrix );
  16062. }
  16063. this.matrixWorldNeedsUpdate = false;
  16064. force = true;
  16065. }
  16066. // update children
  16067. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16068. this.children[ i ].updateMatrixWorld( force );
  16069. }
  16070. };
  16071. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16072. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16073. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16074. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16075. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16076. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16077. /**
  16078. * @author zz85 / http://www.lab4games.net/zz85/blog
  16079. * Creates free form 2d path using series of points, lines or curves.
  16080. *
  16081. **/
  16082. THREE.Path = function ( points ) {
  16083. THREE.CurvePath.call(this);
  16084. this.actions = [];
  16085. if ( points ) {
  16086. this.fromPoints( points );
  16087. }
  16088. };
  16089. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16090. THREE.PathActions = {
  16091. MOVE_TO: 'moveTo',
  16092. LINE_TO: 'lineTo',
  16093. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16094. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16095. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16096. ARC: 'arc', // Circle
  16097. ELLIPSE: 'ellipse'
  16098. };
  16099. // TODO Clean up PATH API
  16100. // Create path using straight lines to connect all points
  16101. // - vectors: array of Vector2
  16102. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16103. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16104. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16105. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16106. };
  16107. };
  16108. // startPath() endPath()?
  16109. THREE.Path.prototype.moveTo = function ( x, y ) {
  16110. var args = Array.prototype.slice.call( arguments );
  16111. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16112. };
  16113. THREE.Path.prototype.lineTo = function ( x, y ) {
  16114. var args = Array.prototype.slice.call( arguments );
  16115. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16116. var x0 = lastargs[ lastargs.length - 2 ];
  16117. var y0 = lastargs[ lastargs.length - 1 ];
  16118. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16119. this.curves.push( curve );
  16120. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16121. };
  16122. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16123. var args = Array.prototype.slice.call( arguments );
  16124. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16125. var x0 = lastargs[ lastargs.length - 2 ];
  16126. var y0 = lastargs[ lastargs.length - 1 ];
  16127. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16128. new THREE.Vector2( aCPx, aCPy ),
  16129. new THREE.Vector2( aX, aY ) );
  16130. this.curves.push( curve );
  16131. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16132. };
  16133. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16134. aCP2x, aCP2y,
  16135. aX, aY ) {
  16136. var args = Array.prototype.slice.call( arguments );
  16137. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16138. var x0 = lastargs[ lastargs.length - 2 ];
  16139. var y0 = lastargs[ lastargs.length - 1 ];
  16140. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16141. new THREE.Vector2( aCP1x, aCP1y ),
  16142. new THREE.Vector2( aCP2x, aCP2y ),
  16143. new THREE.Vector2( aX, aY ) );
  16144. this.curves.push( curve );
  16145. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16146. };
  16147. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16148. var args = Array.prototype.slice.call( arguments );
  16149. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16150. var x0 = lastargs[ lastargs.length - 2 ];
  16151. var y0 = lastargs[ lastargs.length - 1 ];
  16152. //---
  16153. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16154. Array.prototype.push.apply( npts, pts );
  16155. var curve = new THREE.SplineCurve( npts );
  16156. this.curves.push( curve );
  16157. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16158. };
  16159. // FUTURE: Change the API or follow canvas API?
  16160. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16161. aStartAngle, aEndAngle, aClockwise ) {
  16162. var lastargs = this.actions[ this.actions.length - 1].args;
  16163. var x0 = lastargs[ lastargs.length - 2 ];
  16164. var y0 = lastargs[ lastargs.length - 1 ];
  16165. this.absarc(aX + x0, aY + y0, aRadius,
  16166. aStartAngle, aEndAngle, aClockwise );
  16167. };
  16168. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16169. aStartAngle, aEndAngle, aClockwise ) {
  16170. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16171. };
  16172. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16173. aStartAngle, aEndAngle, aClockwise ) {
  16174. var lastargs = this.actions[ this.actions.length - 1].args;
  16175. var x0 = lastargs[ lastargs.length - 2 ];
  16176. var y0 = lastargs[ lastargs.length - 1 ];
  16177. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16178. aStartAngle, aEndAngle, aClockwise );
  16179. };
  16180. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16181. aStartAngle, aEndAngle, aClockwise ) {
  16182. var args = Array.prototype.slice.call( arguments );
  16183. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16184. aStartAngle, aEndAngle, aClockwise );
  16185. this.curves.push( curve );
  16186. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16187. args.push(lastPoint.x);
  16188. args.push(lastPoint.y);
  16189. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16190. };
  16191. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16192. if ( ! divisions ) divisions = 40;
  16193. var points = [];
  16194. for ( var i = 0; i < divisions; i ++ ) {
  16195. points.push( this.getPoint( i / divisions ) );
  16196. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16197. }
  16198. // if ( closedPath ) {
  16199. //
  16200. // points.push( points[ 0 ] );
  16201. //
  16202. // }
  16203. return points;
  16204. };
  16205. /* Return an array of vectors based on contour of the path */
  16206. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16207. if (this.useSpacedPoints) {
  16208. console.log('tata');
  16209. return this.getSpacedPoints( divisions, closedPath );
  16210. }
  16211. divisions = divisions || 12;
  16212. var points = [];
  16213. var i, il, item, action, args;
  16214. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16215. laste, j,
  16216. t, tx, ty;
  16217. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16218. item = this.actions[ i ];
  16219. action = item.action;
  16220. args = item.args;
  16221. switch( action ) {
  16222. case THREE.PathActions.MOVE_TO:
  16223. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16224. break;
  16225. case THREE.PathActions.LINE_TO:
  16226. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16227. break;
  16228. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16229. cpx = args[ 2 ];
  16230. cpy = args[ 3 ];
  16231. cpx1 = args[ 0 ];
  16232. cpy1 = args[ 1 ];
  16233. if ( points.length > 0 ) {
  16234. laste = points[ points.length - 1 ];
  16235. cpx0 = laste.x;
  16236. cpy0 = laste.y;
  16237. } else {
  16238. laste = this.actions[ i - 1 ].args;
  16239. cpx0 = laste[ laste.length - 2 ];
  16240. cpy0 = laste[ laste.length - 1 ];
  16241. }
  16242. for ( j = 1; j <= divisions; j ++ ) {
  16243. t = j / divisions;
  16244. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16245. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16246. points.push( new THREE.Vector2( tx, ty ) );
  16247. }
  16248. break;
  16249. case THREE.PathActions.BEZIER_CURVE_TO:
  16250. cpx = args[ 4 ];
  16251. cpy = args[ 5 ];
  16252. cpx1 = args[ 0 ];
  16253. cpy1 = args[ 1 ];
  16254. cpx2 = args[ 2 ];
  16255. cpy2 = args[ 3 ];
  16256. if ( points.length > 0 ) {
  16257. laste = points[ points.length - 1 ];
  16258. cpx0 = laste.x;
  16259. cpy0 = laste.y;
  16260. } else {
  16261. laste = this.actions[ i - 1 ].args;
  16262. cpx0 = laste[ laste.length - 2 ];
  16263. cpy0 = laste[ laste.length - 1 ];
  16264. }
  16265. for ( j = 1; j <= divisions; j ++ ) {
  16266. t = j / divisions;
  16267. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16268. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16269. points.push( new THREE.Vector2( tx, ty ) );
  16270. }
  16271. break;
  16272. case THREE.PathActions.CSPLINE_THRU:
  16273. laste = this.actions[ i - 1 ].args;
  16274. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16275. var spts = [ last ];
  16276. var n = divisions * args[ 0 ].length;
  16277. spts = spts.concat( args[ 0 ] );
  16278. var spline = new THREE.SplineCurve( spts );
  16279. for ( j = 1; j <= n; j ++ ) {
  16280. points.push( spline.getPointAt( j / n ) ) ;
  16281. }
  16282. break;
  16283. case THREE.PathActions.ARC:
  16284. var aX = args[ 0 ], aY = args[ 1 ],
  16285. aRadius = args[ 2 ],
  16286. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16287. aClockwise = !!args[ 5 ];
  16288. var deltaAngle = aEndAngle - aStartAngle;
  16289. var angle;
  16290. var tdivisions = divisions * 2;
  16291. for ( j = 1; j <= tdivisions; j ++ ) {
  16292. t = j / tdivisions;
  16293. if ( ! aClockwise ) {
  16294. t = 1 - t;
  16295. }
  16296. angle = aStartAngle + t * deltaAngle;
  16297. tx = aX + aRadius * Math.cos( angle );
  16298. ty = aY + aRadius * Math.sin( angle );
  16299. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16300. points.push( new THREE.Vector2( tx, ty ) );
  16301. }
  16302. //console.log(points);
  16303. break;
  16304. case THREE.PathActions.ELLIPSE:
  16305. var aX = args[ 0 ], aY = args[ 1 ],
  16306. xRadius = args[ 2 ],
  16307. yRadius = args[ 3 ],
  16308. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16309. aClockwise = !!args[ 6 ];
  16310. var deltaAngle = aEndAngle - aStartAngle;
  16311. var angle;
  16312. var tdivisions = divisions * 2;
  16313. for ( j = 1; j <= tdivisions; j ++ ) {
  16314. t = j / tdivisions;
  16315. if ( ! aClockwise ) {
  16316. t = 1 - t;
  16317. }
  16318. angle = aStartAngle + t * deltaAngle;
  16319. tx = aX + xRadius * Math.cos( angle );
  16320. ty = aY + yRadius * Math.sin( angle );
  16321. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16322. points.push( new THREE.Vector2( tx, ty ) );
  16323. }
  16324. //console.log(points);
  16325. break;
  16326. } // end switch
  16327. }
  16328. // Normalize to remove the closing point by default.
  16329. var lastPoint = points[ points.length - 1];
  16330. var EPSILON = 0.0000000001;
  16331. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16332. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16333. points.splice( points.length - 1, 1);
  16334. if ( closedPath ) {
  16335. points.push( points[ 0 ] );
  16336. }
  16337. return points;
  16338. };
  16339. // Breaks path into shapes
  16340. THREE.Path.prototype.toShapes = function() {
  16341. var i, il, item, action, args;
  16342. var subPaths = [], lastPath = new THREE.Path();
  16343. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16344. item = this.actions[ i ];
  16345. args = item.args;
  16346. action = item.action;
  16347. if ( action == THREE.PathActions.MOVE_TO ) {
  16348. if ( lastPath.actions.length != 0 ) {
  16349. subPaths.push( lastPath );
  16350. lastPath = new THREE.Path();
  16351. }
  16352. }
  16353. lastPath[ action ].apply( lastPath, args );
  16354. }
  16355. if ( lastPath.actions.length != 0 ) {
  16356. subPaths.push( lastPath );
  16357. }
  16358. // console.log(subPaths);
  16359. if ( subPaths.length == 0 ) return [];
  16360. var tmpPath, tmpShape, shapes = [];
  16361. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16362. // console.log("Holes first", holesFirst);
  16363. if ( subPaths.length == 1) {
  16364. tmpPath = subPaths[0];
  16365. tmpShape = new THREE.Shape();
  16366. tmpShape.actions = tmpPath.actions;
  16367. tmpShape.curves = tmpPath.curves;
  16368. shapes.push( tmpShape );
  16369. return shapes;
  16370. };
  16371. if ( holesFirst ) {
  16372. tmpShape = new THREE.Shape();
  16373. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16374. tmpPath = subPaths[ i ];
  16375. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16376. tmpShape.actions = tmpPath.actions;
  16377. tmpShape.curves = tmpPath.curves;
  16378. shapes.push( tmpShape );
  16379. tmpShape = new THREE.Shape();
  16380. //console.log('cw', i);
  16381. } else {
  16382. tmpShape.holes.push( tmpPath );
  16383. //console.log('ccw', i);
  16384. }
  16385. }
  16386. } else {
  16387. // Shapes first
  16388. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16389. tmpPath = subPaths[ i ];
  16390. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16391. if ( tmpShape ) shapes.push( tmpShape );
  16392. tmpShape = new THREE.Shape();
  16393. tmpShape.actions = tmpPath.actions;
  16394. tmpShape.curves = tmpPath.curves;
  16395. } else {
  16396. tmpShape.holes.push( tmpPath );
  16397. }
  16398. }
  16399. shapes.push( tmpShape );
  16400. }
  16401. //console.log("shape", shapes);
  16402. return shapes;
  16403. };
  16404. /**
  16405. * @author zz85 / http://www.lab4games.net/zz85/blog
  16406. * Defines a 2d shape plane using paths.
  16407. **/
  16408. // STEP 1 Create a path.
  16409. // STEP 2 Turn path into shape.
  16410. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16411. // STEP 3a - Extract points from each shape, turn to vertices
  16412. // STEP 3b - Triangulate each shape, add faces.
  16413. THREE.Shape = function ( ) {
  16414. THREE.Path.apply( this, arguments );
  16415. this.holes = [];
  16416. };
  16417. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16418. // Convenience method to return ExtrudeGeometry
  16419. THREE.Shape.prototype.extrude = function ( options ) {
  16420. var extruded = new THREE.ExtrudeGeometry( this, options );
  16421. return extruded;
  16422. };
  16423. // Convenience method to return ShapeGeometry
  16424. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16425. var geometry = new THREE.ShapeGeometry( this, options );
  16426. return geometry;
  16427. };
  16428. // Get points of holes
  16429. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16430. var i, il = this.holes.length, holesPts = [];
  16431. for ( i = 0; i < il; i ++ ) {
  16432. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16433. }
  16434. return holesPts;
  16435. };
  16436. // Get points of holes (spaced by regular distance)
  16437. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16438. var i, il = this.holes.length, holesPts = [];
  16439. for ( i = 0; i < il; i ++ ) {
  16440. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16441. }
  16442. return holesPts;
  16443. };
  16444. // Get points of shape and holes (keypoints based on segments parameter)
  16445. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16446. return {
  16447. shape: this.getTransformedPoints( divisions ),
  16448. holes: this.getPointsHoles( divisions )
  16449. };
  16450. };
  16451. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16452. if (this.useSpacedPoints) {
  16453. return this.extractAllSpacedPoints(divisions);
  16454. }
  16455. return this.extractAllPoints(divisions);
  16456. };
  16457. //
  16458. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16459. //
  16460. // return {
  16461. //
  16462. // shape: this.transform( bend, divisions ),
  16463. // holes: this.getPointsHoles( divisions, bend )
  16464. //
  16465. // };
  16466. //
  16467. // };
  16468. // Get points of shape and holes (spaced by regular distance)
  16469. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16470. return {
  16471. shape: this.getTransformedSpacedPoints( divisions ),
  16472. holes: this.getSpacedPointsHoles( divisions )
  16473. };
  16474. };
  16475. /**************************************************************
  16476. * Utils
  16477. **************************************************************/
  16478. THREE.Shape.Utils = {
  16479. /*
  16480. contour - array of vector2 for contour
  16481. holes - array of array of vector2
  16482. */
  16483. removeHoles: function ( contour, holes ) {
  16484. var shape = contour.concat(); // work on this shape
  16485. var allpoints = shape.concat();
  16486. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  16487. var prevShapeVert, nextShapeVert,
  16488. prevHoleVert, nextHoleVert,
  16489. holeIndex, shapeIndex,
  16490. shapeId, shapeGroup,
  16491. h, h2,
  16492. hole, shortest, d,
  16493. p, pts1, pts2,
  16494. tmpShape1, tmpShape2,
  16495. tmpHole1, tmpHole2,
  16496. verts = [];
  16497. for ( h = 0; h < holes.length; h ++ ) {
  16498. hole = holes[ h ];
  16499. /*
  16500. shapeholes[ h ].concat(); // preserves original
  16501. holes.push( hole );
  16502. */
  16503. Array.prototype.push.apply( allpoints, hole );
  16504. shortest = Number.POSITIVE_INFINITY;
  16505. // Find the shortest pair of pts between shape and hole
  16506. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  16507. // Using distanceToSquared() intead of distanceTo() should speed a little
  16508. // since running square roots operations are reduced.
  16509. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  16510. pts1 = hole[ h2 ];
  16511. var dist = [];
  16512. for ( p = 0; p < shape.length; p++ ) {
  16513. pts2 = shape[ p ];
  16514. d = pts1.distanceToSquared( pts2 );
  16515. dist.push( d );
  16516. if ( d < shortest ) {
  16517. shortest = d;
  16518. holeIndex = h2;
  16519. shapeIndex = p;
  16520. }
  16521. }
  16522. }
  16523. //console.log("shortest", shortest, dist);
  16524. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16525. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16526. var areaapts = [
  16527. hole[ holeIndex ],
  16528. shape[ shapeIndex ],
  16529. shape[ prevShapeVert ]
  16530. ];
  16531. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  16532. var areabpts = [
  16533. hole[ holeIndex ],
  16534. hole[ prevHoleVert ],
  16535. shape[ shapeIndex ]
  16536. ];
  16537. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  16538. var shapeOffset = 1;
  16539. var holeOffset = -1;
  16540. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  16541. shapeIndex += shapeOffset;
  16542. holeIndex += holeOffset;
  16543. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16544. shapeIndex %= shape.length;
  16545. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16546. holeIndex %= hole.length;
  16547. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16548. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16549. areaapts = [
  16550. hole[ holeIndex ],
  16551. shape[ shapeIndex ],
  16552. shape[ prevShapeVert ]
  16553. ];
  16554. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  16555. areabpts = [
  16556. hole[ holeIndex ],
  16557. hole[ prevHoleVert ],
  16558. shape[ shapeIndex ]
  16559. ];
  16560. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  16561. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  16562. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  16563. // In case areas are not correct.
  16564. //console.log("USE THIS");
  16565. shapeIndex = oldShapeIndex;
  16566. holeIndex = oldHoleIndex ;
  16567. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16568. shapeIndex %= shape.length;
  16569. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16570. holeIndex %= hole.length;
  16571. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16572. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16573. } else {
  16574. //console.log("USE THAT ")
  16575. }
  16576. tmpShape1 = shape.slice( 0, shapeIndex );
  16577. tmpShape2 = shape.slice( shapeIndex );
  16578. tmpHole1 = hole.slice( holeIndex );
  16579. tmpHole2 = hole.slice( 0, holeIndex );
  16580. // Should check orders here again?
  16581. var trianglea = [
  16582. hole[ holeIndex ],
  16583. shape[ shapeIndex ],
  16584. shape[ prevShapeVert ]
  16585. ];
  16586. var triangleb = [
  16587. hole[ holeIndex ] ,
  16588. hole[ prevHoleVert ],
  16589. shape[ shapeIndex ]
  16590. ];
  16591. verts.push( trianglea );
  16592. verts.push( triangleb );
  16593. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16594. }
  16595. return {
  16596. shape:shape, /* shape with no holes */
  16597. isolatedPts: verts, /* isolated faces */
  16598. allpoints: allpoints
  16599. }
  16600. },
  16601. triangulateShape: function ( contour, holes ) {
  16602. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  16603. var shape = shapeWithoutHoles.shape,
  16604. allpoints = shapeWithoutHoles.allpoints,
  16605. isolatedPts = shapeWithoutHoles.isolatedPts;
  16606. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  16607. // 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.
  16608. //console.log( "triangles",triangles, triangles.length );
  16609. //console.log( "allpoints",allpoints, allpoints.length );
  16610. var i, il, f, face,
  16611. key, index,
  16612. allPointsMap = {},
  16613. isolatedPointsMap = {};
  16614. // prepare all points map
  16615. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16616. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  16617. if ( allPointsMap[ key ] !== undefined ) {
  16618. console.log( "Duplicate point", key );
  16619. }
  16620. allPointsMap[ key ] = i;
  16621. }
  16622. // check all face vertices against all points map
  16623. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  16624. face = triangles[ i ];
  16625. for ( f = 0; f < 3; f ++ ) {
  16626. key = face[ f ].x + ":" + face[ f ].y;
  16627. index = allPointsMap[ key ];
  16628. if ( index !== undefined ) {
  16629. face[ f ] = index;
  16630. }
  16631. }
  16632. }
  16633. // check isolated points vertices against all points map
  16634. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  16635. face = isolatedPts[ i ];
  16636. for ( f = 0; f < 3; f ++ ) {
  16637. key = face[ f ].x + ":" + face[ f ].y;
  16638. index = allPointsMap[ key ];
  16639. if ( index !== undefined ) {
  16640. face[ f ] = index;
  16641. }
  16642. }
  16643. }
  16644. return triangles.concat( isolatedPts );
  16645. }, // end triangulate shapes
  16646. /*
  16647. triangulate2 : function( pts, holes ) {
  16648. // For use with Poly2Tri.js
  16649. var allpts = pts.concat();
  16650. var shape = [];
  16651. for (var p in pts) {
  16652. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  16653. }
  16654. var swctx = new js.poly2tri.SweepContext(shape);
  16655. for (var h in holes) {
  16656. var aHole = holes[h];
  16657. var newHole = []
  16658. for (i in aHole) {
  16659. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  16660. allpts.push(aHole[i]);
  16661. }
  16662. swctx.AddHole(newHole);
  16663. }
  16664. var find;
  16665. var findIndexForPt = function (pt) {
  16666. find = new THREE.Vector2(pt.x, pt.y);
  16667. var p;
  16668. for (p=0, pl = allpts.length; p<pl; p++) {
  16669. if (allpts[p].equals(find)) return p;
  16670. }
  16671. return -1;
  16672. };
  16673. // triangulate
  16674. js.poly2tri.sweep.Triangulate(swctx);
  16675. var triangles = swctx.GetTriangles();
  16676. var tr ;
  16677. var facesPts = [];
  16678. for (var t in triangles) {
  16679. tr = triangles[t];
  16680. facesPts.push([
  16681. findIndexForPt(tr.GetPoint(0)),
  16682. findIndexForPt(tr.GetPoint(1)),
  16683. findIndexForPt(tr.GetPoint(2))
  16684. ]);
  16685. }
  16686. // console.log(facesPts);
  16687. // console.log("triangles", triangles.length, triangles);
  16688. // Returns array of faces with 3 element each
  16689. return facesPts;
  16690. },
  16691. */
  16692. isClockWise: function ( pts ) {
  16693. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  16694. },
  16695. // Bezier Curves formulas obtained from
  16696. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  16697. // Quad Bezier Functions
  16698. b2p0: function ( t, p ) {
  16699. var k = 1 - t;
  16700. return k * k * p;
  16701. },
  16702. b2p1: function ( t, p ) {
  16703. return 2 * ( 1 - t ) * t * p;
  16704. },
  16705. b2p2: function ( t, p ) {
  16706. return t * t * p;
  16707. },
  16708. b2: function ( t, p0, p1, p2 ) {
  16709. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  16710. },
  16711. // Cubic Bezier Functions
  16712. b3p0: function ( t, p ) {
  16713. var k = 1 - t;
  16714. return k * k * k * p;
  16715. },
  16716. b3p1: function ( t, p ) {
  16717. var k = 1 - t;
  16718. return 3 * k * k * t * p;
  16719. },
  16720. b3p2: function ( t, p ) {
  16721. var k = 1 - t;
  16722. return 3 * k * t * t * p;
  16723. },
  16724. b3p3: function ( t, p ) {
  16725. return t * t * t * p;
  16726. },
  16727. b3: function ( t, p0, p1, p2, p3 ) {
  16728. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  16729. }
  16730. };
  16731. /**
  16732. * @author mikael emtinger / http://gomo.se/
  16733. */
  16734. THREE.AnimationHandler = (function() {
  16735. var playing = [];
  16736. var library = {};
  16737. var that = {};
  16738. //--- update ---
  16739. that.update = function( deltaTimeMS ) {
  16740. for( var i = 0; i < playing.length; i ++ )
  16741. playing[ i ].update( deltaTimeMS );
  16742. };
  16743. //--- add ---
  16744. that.addToUpdate = function( animation ) {
  16745. if ( playing.indexOf( animation ) === -1 )
  16746. playing.push( animation );
  16747. };
  16748. //--- remove ---
  16749. that.removeFromUpdate = function( animation ) {
  16750. var index = playing.indexOf( animation );
  16751. if( index !== -1 )
  16752. playing.splice( index, 1 );
  16753. };
  16754. //--- add ---
  16755. that.add = function( data ) {
  16756. if ( library[ data.name ] !== undefined )
  16757. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  16758. library[ data.name ] = data;
  16759. initData( data );
  16760. };
  16761. //--- get ---
  16762. that.get = function( name ) {
  16763. if ( typeof name === "string" ) {
  16764. if ( library[ name ] ) {
  16765. return library[ name ];
  16766. } else {
  16767. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  16768. return null;
  16769. }
  16770. } else {
  16771. // todo: add simple tween library
  16772. }
  16773. };
  16774. //--- parse ---
  16775. that.parse = function( root ) {
  16776. // setup hierarchy
  16777. var hierarchy = [];
  16778. if ( root instanceof THREE.SkinnedMesh ) {
  16779. for( var b = 0; b < root.bones.length; b++ ) {
  16780. hierarchy.push( root.bones[ b ] );
  16781. }
  16782. } else {
  16783. parseRecurseHierarchy( root, hierarchy );
  16784. }
  16785. return hierarchy;
  16786. };
  16787. var parseRecurseHierarchy = function( root, hierarchy ) {
  16788. hierarchy.push( root );
  16789. for( var c = 0; c < root.children.length; c++ )
  16790. parseRecurseHierarchy( root.children[ c ], hierarchy );
  16791. }
  16792. //--- init data ---
  16793. var initData = function( data ) {
  16794. if( data.initialized === true )
  16795. return;
  16796. // loop through all keys
  16797. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  16798. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16799. // remove minus times
  16800. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  16801. data.hierarchy[ h ].keys[ k ].time = 0;
  16802. // create quaternions
  16803. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  16804. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  16805. var quat = data.hierarchy[ h ].keys[ k ].rot;
  16806. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  16807. }
  16808. }
  16809. // prepare morph target keys
  16810. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  16811. // get all used
  16812. var usedMorphTargets = {};
  16813. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16814. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16815. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  16816. usedMorphTargets[ morphTargetName ] = -1;
  16817. }
  16818. }
  16819. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  16820. // set all used on all frames
  16821. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16822. var influences = {};
  16823. for ( var morphTargetName in usedMorphTargets ) {
  16824. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16825. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  16826. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  16827. break;
  16828. }
  16829. }
  16830. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  16831. influences[ morphTargetName ] = 0;
  16832. }
  16833. }
  16834. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  16835. }
  16836. }
  16837. // remove all keys that are on the same time
  16838. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16839. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  16840. data.hierarchy[ h ].keys.splice( k, 1 );
  16841. k --;
  16842. }
  16843. }
  16844. // set index
  16845. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16846. data.hierarchy[ h ].keys[ k ].index = k;
  16847. }
  16848. }
  16849. // JIT
  16850. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  16851. data.JIT = {};
  16852. data.JIT.hierarchy = [];
  16853. for( var h = 0; h < data.hierarchy.length; h ++ )
  16854. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  16855. // done
  16856. data.initialized = true;
  16857. };
  16858. // interpolation types
  16859. that.LINEAR = 0;
  16860. that.CATMULLROM = 1;
  16861. that.CATMULLROM_FORWARD = 2;
  16862. return that;
  16863. }());
  16864. /**
  16865. * @author mikael emtinger / http://gomo.se/
  16866. * @author mrdoob / http://mrdoob.com/
  16867. * @author alteredq / http://alteredqualia.com/
  16868. */
  16869. THREE.Animation = function ( root, name, interpolationType ) {
  16870. this.root = root;
  16871. this.data = THREE.AnimationHandler.get( name );
  16872. this.hierarchy = THREE.AnimationHandler.parse( root );
  16873. this.currentTime = 0;
  16874. this.timeScale = 1;
  16875. this.isPlaying = false;
  16876. this.isPaused = true;
  16877. this.loop = true;
  16878. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  16879. this.points = [];
  16880. this.target = new THREE.Vector3();
  16881. };
  16882. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  16883. if ( this.isPlaying === false ) {
  16884. this.isPlaying = true;
  16885. this.loop = loop !== undefined ? loop : true;
  16886. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16887. // reset key cache
  16888. var h, hl = this.hierarchy.length,
  16889. object;
  16890. for ( h = 0; h < hl; h ++ ) {
  16891. object = this.hierarchy[ h ];
  16892. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16893. object.useQuaternion = true;
  16894. }
  16895. object.matrixAutoUpdate = true;
  16896. if ( object.animationCache === undefined ) {
  16897. object.animationCache = {};
  16898. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  16899. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  16900. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16901. }
  16902. var prevKey = object.animationCache.prevKey;
  16903. var nextKey = object.animationCache.nextKey;
  16904. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  16905. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  16906. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  16907. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  16908. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  16909. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  16910. }
  16911. this.update( 0 );
  16912. }
  16913. this.isPaused = false;
  16914. THREE.AnimationHandler.addToUpdate( this );
  16915. };
  16916. THREE.Animation.prototype.pause = function() {
  16917. if ( this.isPaused === true ) {
  16918. THREE.AnimationHandler.addToUpdate( this );
  16919. } else {
  16920. THREE.AnimationHandler.removeFromUpdate( this );
  16921. }
  16922. this.isPaused = !this.isPaused;
  16923. };
  16924. THREE.Animation.prototype.stop = function() {
  16925. this.isPlaying = false;
  16926. this.isPaused = false;
  16927. THREE.AnimationHandler.removeFromUpdate( this );
  16928. };
  16929. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  16930. // early out
  16931. if ( this.isPlaying === false ) return;
  16932. // vars
  16933. var types = [ "pos", "rot", "scl" ];
  16934. var type;
  16935. var scale;
  16936. var vector;
  16937. var prevXYZ, nextXYZ;
  16938. var prevKey, nextKey;
  16939. var object;
  16940. var animationCache;
  16941. var frame;
  16942. var JIThierarchy = this.data.JIT.hierarchy;
  16943. var currentTime, unloopedCurrentTime;
  16944. var currentPoint, forwardPoint, angle;
  16945. this.currentTime += deltaTimeMS * this.timeScale;
  16946. unloopedCurrentTime = this.currentTime;
  16947. currentTime = this.currentTime = this.currentTime % this.data.length;
  16948. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16949. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  16950. object = this.hierarchy[ h ];
  16951. animationCache = object.animationCache;
  16952. // loop through pos/rot/scl
  16953. for ( var t = 0; t < 3; t ++ ) {
  16954. // get keys
  16955. type = types[ t ];
  16956. prevKey = animationCache.prevKey[ type ];
  16957. nextKey = animationCache.nextKey[ type ];
  16958. // switch keys?
  16959. if ( nextKey.time <= unloopedCurrentTime ) {
  16960. // did we loop?
  16961. if ( currentTime < unloopedCurrentTime ) {
  16962. if ( this.loop ) {
  16963. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  16964. nextKey = this.getNextKeyWith( type, h, 1 );
  16965. while( nextKey.time < currentTime ) {
  16966. prevKey = nextKey;
  16967. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16968. }
  16969. } else {
  16970. this.stop();
  16971. return;
  16972. }
  16973. } else {
  16974. do {
  16975. prevKey = nextKey;
  16976. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16977. } while( nextKey.time < currentTime )
  16978. }
  16979. animationCache.prevKey[ type ] = prevKey;
  16980. animationCache.nextKey[ type ] = nextKey;
  16981. }
  16982. object.matrixAutoUpdate = true;
  16983. object.matrixWorldNeedsUpdate = true;
  16984. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  16985. prevXYZ = prevKey[ type ];
  16986. nextXYZ = nextKey[ type ];
  16987. // check scale error
  16988. if ( scale < 0 || scale > 1 ) {
  16989. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  16990. scale = scale < 0 ? 0 : 1;
  16991. }
  16992. // interpolate
  16993. if ( type === "pos" ) {
  16994. vector = object.position;
  16995. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  16996. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16997. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16998. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16999. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17000. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17001. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17002. this.points[ 1 ] = prevXYZ;
  17003. this.points[ 2 ] = nextXYZ;
  17004. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17005. scale = scale * 0.33 + 0.33;
  17006. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17007. vector.x = currentPoint[ 0 ];
  17008. vector.y = currentPoint[ 1 ];
  17009. vector.z = currentPoint[ 2 ];
  17010. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17011. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17012. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17013. this.target.subSelf( vector );
  17014. this.target.y = 0;
  17015. this.target.normalize();
  17016. angle = Math.atan2( this.target.x, this.target.z );
  17017. object.rotation.set( 0, angle, 0 );
  17018. }
  17019. }
  17020. } else if ( type === "rot" ) {
  17021. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17022. } else if ( type === "scl" ) {
  17023. vector = object.scale;
  17024. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17025. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17026. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17027. }
  17028. }
  17029. }
  17030. };
  17031. // Catmull-Rom spline
  17032. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17033. var c = [], v3 = [],
  17034. point, intPoint, weight, w2, w3,
  17035. pa, pb, pc, pd;
  17036. point = ( points.length - 1 ) * scale;
  17037. intPoint = Math.floor( point );
  17038. weight = point - intPoint;
  17039. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17040. c[ 1 ] = intPoint;
  17041. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17042. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17043. pa = points[ c[ 0 ] ];
  17044. pb = points[ c[ 1 ] ];
  17045. pc = points[ c[ 2 ] ];
  17046. pd = points[ c[ 3 ] ];
  17047. w2 = weight * weight;
  17048. w3 = weight * w2;
  17049. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17050. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17051. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17052. return v3;
  17053. };
  17054. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17055. var v0 = ( p2 - p0 ) * 0.5,
  17056. v1 = ( p3 - p1 ) * 0.5;
  17057. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17058. };
  17059. // Get next key with
  17060. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17061. var keys = this.data.hierarchy[ h ].keys;
  17062. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17063. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17064. key = key < keys.length - 1 ? key : keys.length - 1;
  17065. } else {
  17066. key = key % keys.length;
  17067. }
  17068. for ( ; key < keys.length; key++ ) {
  17069. if ( keys[ key ][ type ] !== undefined ) {
  17070. return keys[ key ];
  17071. }
  17072. }
  17073. return this.data.hierarchy[ h ].keys[ 0 ];
  17074. };
  17075. // Get previous key with
  17076. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17077. var keys = this.data.hierarchy[ h ].keys;
  17078. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17079. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17080. key = key > 0 ? key : 0;
  17081. } else {
  17082. key = key >= 0 ? key : key + keys.length;
  17083. }
  17084. for ( ; key >= 0; key -- ) {
  17085. if ( keys[ key ][ type ] !== undefined ) {
  17086. return keys[ key ];
  17087. }
  17088. }
  17089. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17090. };
  17091. /**
  17092. * @author mikael emtinger / http://gomo.se/
  17093. * @author mrdoob / http://mrdoob.com/
  17094. * @author alteredq / http://alteredqualia.com/
  17095. * @author khang duong
  17096. * @author erik kitson
  17097. */
  17098. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17099. this.root = root;
  17100. this.data = THREE.AnimationHandler.get( data );
  17101. this.hierarchy = THREE.AnimationHandler.parse( root );
  17102. this.currentTime = 0;
  17103. this.timeScale = 0.001;
  17104. this.isPlaying = false;
  17105. this.isPaused = true;
  17106. this.loop = true;
  17107. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17108. // initialize to first keyframes
  17109. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17110. var keys = this.data.hierarchy[h].keys,
  17111. sids = this.data.hierarchy[h].sids,
  17112. obj = this.hierarchy[h];
  17113. if ( keys.length && sids ) {
  17114. for ( var s = 0; s < sids.length; s++ ) {
  17115. var sid = sids[ s ],
  17116. next = this.getNextKeyWith( sid, h, 0 );
  17117. if ( next ) {
  17118. next.apply( sid );
  17119. }
  17120. }
  17121. obj.matrixAutoUpdate = false;
  17122. this.data.hierarchy[h].node.updateMatrix();
  17123. obj.matrixWorldNeedsUpdate = true;
  17124. }
  17125. }
  17126. };
  17127. // Play
  17128. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17129. if( !this.isPlaying ) {
  17130. this.isPlaying = true;
  17131. this.loop = loop !== undefined ? loop : true;
  17132. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17133. this.startTimeMs = startTimeMS;
  17134. this.startTime = 10000000;
  17135. this.endTime = -this.startTime;
  17136. // reset key cache
  17137. var h, hl = this.hierarchy.length,
  17138. object,
  17139. node;
  17140. for ( h = 0; h < hl; h++ ) {
  17141. object = this.hierarchy[ h ];
  17142. node = this.data.hierarchy[ h ];
  17143. object.useQuaternion = true;
  17144. if ( node.animationCache === undefined ) {
  17145. node.animationCache = {};
  17146. node.animationCache.prevKey = null;
  17147. node.animationCache.nextKey = null;
  17148. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17149. }
  17150. var keys = this.data.hierarchy[h].keys;
  17151. if (keys.length) {
  17152. node.animationCache.prevKey = keys[ 0 ];
  17153. node.animationCache.nextKey = keys[ 1 ];
  17154. this.startTime = Math.min( keys[0].time, this.startTime );
  17155. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17156. }
  17157. }
  17158. this.update( 0 );
  17159. }
  17160. this.isPaused = false;
  17161. THREE.AnimationHandler.addToUpdate( this );
  17162. };
  17163. // Pause
  17164. THREE.KeyFrameAnimation.prototype.pause = function() {
  17165. if( this.isPaused ) {
  17166. THREE.AnimationHandler.addToUpdate( this );
  17167. } else {
  17168. THREE.AnimationHandler.removeFromUpdate( this );
  17169. }
  17170. this.isPaused = !this.isPaused;
  17171. };
  17172. // Stop
  17173. THREE.KeyFrameAnimation.prototype.stop = function() {
  17174. this.isPlaying = false;
  17175. this.isPaused = false;
  17176. THREE.AnimationHandler.removeFromUpdate( this );
  17177. // reset JIT matrix and remove cache
  17178. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17179. var obj = this.hierarchy[ h ];
  17180. var node = this.data.hierarchy[ h ];
  17181. if ( node.animationCache !== undefined ) {
  17182. var original = node.animationCache.originalMatrix;
  17183. if( obj instanceof THREE.Bone ) {
  17184. original.copy( obj.skinMatrix );
  17185. obj.skinMatrix = original;
  17186. } else {
  17187. original.copy( obj.matrix );
  17188. obj.matrix = original;
  17189. }
  17190. delete node.animationCache;
  17191. }
  17192. }
  17193. };
  17194. // Update
  17195. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17196. // early out
  17197. if( !this.isPlaying ) return;
  17198. // vars
  17199. var prevKey, nextKey;
  17200. var object;
  17201. var node;
  17202. var frame;
  17203. var JIThierarchy = this.data.JIT.hierarchy;
  17204. var currentTime, unloopedCurrentTime;
  17205. var looped;
  17206. // update
  17207. this.currentTime += deltaTimeMS * this.timeScale;
  17208. unloopedCurrentTime = this.currentTime;
  17209. currentTime = this.currentTime = this.currentTime % this.data.length;
  17210. // if looped around, the current time should be based on the startTime
  17211. if ( currentTime < this.startTimeMs ) {
  17212. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17213. }
  17214. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17215. looped = currentTime < unloopedCurrentTime;
  17216. if ( looped && !this.loop ) {
  17217. // Set the animation to the last keyframes and stop
  17218. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17219. var keys = this.data.hierarchy[h].keys,
  17220. sids = this.data.hierarchy[h].sids,
  17221. end = keys.length-1,
  17222. obj = this.hierarchy[h];
  17223. if ( keys.length ) {
  17224. for ( var s = 0; s < sids.length; s++ ) {
  17225. var sid = sids[ s ],
  17226. prev = this.getPrevKeyWith( sid, h, end );
  17227. if ( prev ) {
  17228. prev.apply( sid );
  17229. }
  17230. }
  17231. this.data.hierarchy[h].node.updateMatrix();
  17232. obj.matrixWorldNeedsUpdate = true;
  17233. }
  17234. }
  17235. this.stop();
  17236. return;
  17237. }
  17238. // check pre-infinity
  17239. if ( currentTime < this.startTime ) {
  17240. return;
  17241. }
  17242. // update
  17243. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17244. object = this.hierarchy[ h ];
  17245. node = this.data.hierarchy[ h ];
  17246. var keys = node.keys,
  17247. animationCache = node.animationCache;
  17248. // use JIT?
  17249. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17250. if( object instanceof THREE.Bone ) {
  17251. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17252. object.matrixWorldNeedsUpdate = false;
  17253. } else {
  17254. object.matrix = JIThierarchy[ h ][ frame ];
  17255. object.matrixWorldNeedsUpdate = true;
  17256. }
  17257. // use interpolation
  17258. } else if ( keys.length ) {
  17259. // make sure so original matrix and not JIT matrix is set
  17260. if ( this.JITCompile && animationCache ) {
  17261. if( object instanceof THREE.Bone ) {
  17262. object.skinMatrix = animationCache.originalMatrix;
  17263. } else {
  17264. object.matrix = animationCache.originalMatrix;
  17265. }
  17266. }
  17267. prevKey = animationCache.prevKey;
  17268. nextKey = animationCache.nextKey;
  17269. if ( prevKey && nextKey ) {
  17270. // switch keys?
  17271. if ( nextKey.time <= unloopedCurrentTime ) {
  17272. // did we loop?
  17273. if ( looped && this.loop ) {
  17274. prevKey = keys[ 0 ];
  17275. nextKey = keys[ 1 ];
  17276. while ( nextKey.time < currentTime ) {
  17277. prevKey = nextKey;
  17278. nextKey = keys[ prevKey.index + 1 ];
  17279. }
  17280. } else if ( !looped ) {
  17281. var lastIndex = keys.length - 1;
  17282. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17283. prevKey = nextKey;
  17284. nextKey = keys[ prevKey.index + 1 ];
  17285. }
  17286. }
  17287. animationCache.prevKey = prevKey;
  17288. animationCache.nextKey = nextKey;
  17289. }
  17290. if(nextKey.time >= currentTime)
  17291. prevKey.interpolate( nextKey, currentTime );
  17292. else
  17293. prevKey.interpolate( nextKey, nextKey.time);
  17294. }
  17295. this.data.hierarchy[h].node.updateMatrix();
  17296. object.matrixWorldNeedsUpdate = true;
  17297. }
  17298. }
  17299. // update JIT?
  17300. if ( this.JITCompile ) {
  17301. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17302. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17303. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17304. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17305. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17306. } else {
  17307. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17308. }
  17309. }
  17310. }
  17311. }
  17312. };
  17313. // Get next key with
  17314. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17315. var keys = this.data.hierarchy[ h ].keys;
  17316. key = key % keys.length;
  17317. for ( ; key < keys.length; key++ ) {
  17318. if ( keys[ key ].hasTarget( sid ) ) {
  17319. return keys[ key ];
  17320. }
  17321. }
  17322. return keys[ 0 ];
  17323. };
  17324. // Get previous key with
  17325. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17326. var keys = this.data.hierarchy[ h ].keys;
  17327. key = key >= 0 ? key : key + keys.length;
  17328. for ( ; key >= 0; key-- ) {
  17329. if ( keys[ key ].hasTarget( sid ) ) {
  17330. return keys[ key ];
  17331. }
  17332. }
  17333. return keys[ keys.length - 1 ];
  17334. };
  17335. /**
  17336. * Camera for rendering cube maps
  17337. * - renders scene into axis-aligned cube
  17338. *
  17339. * @author alteredq / http://alteredqualia.com/
  17340. */
  17341. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17342. THREE.Object3D.call( this );
  17343. var fov = 90, aspect = 1;
  17344. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17345. cameraPX.up.set( 0, -1, 0 );
  17346. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17347. this.add( cameraPX );
  17348. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17349. cameraNX.up.set( 0, -1, 0 );
  17350. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17351. this.add( cameraNX );
  17352. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17353. cameraPY.up.set( 0, 0, 1 );
  17354. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17355. this.add( cameraPY );
  17356. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17357. cameraNY.up.set( 0, 0, -1 );
  17358. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17359. this.add( cameraNY );
  17360. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17361. cameraPZ.up.set( 0, -1, 0 );
  17362. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  17363. this.add( cameraPZ );
  17364. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17365. cameraNZ.up.set( 0, -1, 0 );
  17366. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  17367. this.add( cameraNZ );
  17368. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  17369. this.updateCubeMap = function ( renderer, scene ) {
  17370. var renderTarget = this.renderTarget;
  17371. var generateMipmaps = renderTarget.generateMipmaps;
  17372. renderTarget.generateMipmaps = false;
  17373. renderTarget.activeCubeFace = 0;
  17374. renderer.render( scene, cameraPX, renderTarget );
  17375. renderTarget.activeCubeFace = 1;
  17376. renderer.render( scene, cameraNX, renderTarget );
  17377. renderTarget.activeCubeFace = 2;
  17378. renderer.render( scene, cameraPY, renderTarget );
  17379. renderTarget.activeCubeFace = 3;
  17380. renderer.render( scene, cameraNY, renderTarget );
  17381. renderTarget.activeCubeFace = 4;
  17382. renderer.render( scene, cameraPZ, renderTarget );
  17383. renderTarget.generateMipmaps = generateMipmaps;
  17384. renderTarget.activeCubeFace = 5;
  17385. renderer.render( scene, cameraNZ, renderTarget );
  17386. };
  17387. };
  17388. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  17389. /*
  17390. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  17391. *
  17392. * A general perpose camera, for setting FOV, Lens Focal Length,
  17393. * and switching between perspective and orthographic views easily.
  17394. * Use this only if you do not wish to manage
  17395. * both a Orthographic and Perspective Camera
  17396. *
  17397. */
  17398. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  17399. THREE.Camera.call( this );
  17400. this.fov = fov;
  17401. this.left = -width / 2;
  17402. this.right = width / 2
  17403. this.top = height / 2;
  17404. this.bottom = -height / 2;
  17405. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  17406. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  17407. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  17408. this.zoom = 1;
  17409. this.toPerspective();
  17410. var aspect = width/height;
  17411. };
  17412. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  17413. THREE.CombinedCamera.prototype.toPerspective = function () {
  17414. // Switches to the Perspective Camera
  17415. this.near = this.cameraP.near;
  17416. this.far = this.cameraP.far;
  17417. this.cameraP.fov = this.fov / this.zoom ;
  17418. this.cameraP.updateProjectionMatrix();
  17419. this.projectionMatrix = this.cameraP.projectionMatrix;
  17420. this.inPerspectiveMode = true;
  17421. this.inOrthographicMode = false;
  17422. };
  17423. THREE.CombinedCamera.prototype.toOrthographic = function () {
  17424. // Switches to the Orthographic camera estimating viewport from Perspective
  17425. var fov = this.fov;
  17426. var aspect = this.cameraP.aspect;
  17427. var near = this.cameraP.near;
  17428. var far = this.cameraP.far;
  17429. // The size that we set is the mid plane of the viewing frustum
  17430. var hyperfocus = ( near + far ) / 2;
  17431. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  17432. var planeHeight = 2 * halfHeight;
  17433. var planeWidth = planeHeight * aspect;
  17434. var halfWidth = planeWidth / 2;
  17435. halfHeight /= this.zoom;
  17436. halfWidth /= this.zoom;
  17437. this.cameraO.left = -halfWidth;
  17438. this.cameraO.right = halfWidth;
  17439. this.cameraO.top = halfHeight;
  17440. this.cameraO.bottom = -halfHeight;
  17441. // this.cameraO.left = -farHalfWidth;
  17442. // this.cameraO.right = farHalfWidth;
  17443. // this.cameraO.top = farHalfHeight;
  17444. // this.cameraO.bottom = -farHalfHeight;
  17445. // this.cameraO.left = this.left / this.zoom;
  17446. // this.cameraO.right = this.right / this.zoom;
  17447. // this.cameraO.top = this.top / this.zoom;
  17448. // this.cameraO.bottom = this.bottom / this.zoom;
  17449. this.cameraO.updateProjectionMatrix();
  17450. this.near = this.cameraO.near;
  17451. this.far = this.cameraO.far;
  17452. this.projectionMatrix = this.cameraO.projectionMatrix;
  17453. this.inPerspectiveMode = false;
  17454. this.inOrthographicMode = true;
  17455. };
  17456. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  17457. this.cameraP.aspect = width / height;
  17458. this.left = -width / 2;
  17459. this.right = width / 2
  17460. this.top = height / 2;
  17461. this.bottom = -height / 2;
  17462. };
  17463. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  17464. this.fov = fov;
  17465. if ( this.inPerspectiveMode ) {
  17466. this.toPerspective();
  17467. } else {
  17468. this.toOrthographic();
  17469. }
  17470. };
  17471. // For mantaining similar API with PerspectiveCamera
  17472. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  17473. if ( this.inPerspectiveMode ) {
  17474. this.toPerspective();
  17475. } else {
  17476. this.toPerspective();
  17477. this.toOrthographic();
  17478. }
  17479. };
  17480. /*
  17481. * Uses Focal Length (in mm) to estimate and set FOV
  17482. * 35mm (fullframe) camera is used if frame size is not specified;
  17483. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  17484. */
  17485. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  17486. if ( frameHeight === undefined ) frameHeight = 24;
  17487. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  17488. this.setFov( fov );
  17489. return fov;
  17490. };
  17491. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  17492. this.zoom = zoom;
  17493. if ( this.inPerspectiveMode ) {
  17494. this.toPerspective();
  17495. } else {
  17496. this.toOrthographic();
  17497. }
  17498. };
  17499. THREE.CombinedCamera.prototype.toFrontView = function() {
  17500. this.rotation.x = 0;
  17501. this.rotation.y = 0;
  17502. this.rotation.z = 0;
  17503. // should we be modifing the matrix instead?
  17504. this.rotationAutoUpdate = false;
  17505. };
  17506. THREE.CombinedCamera.prototype.toBackView = function() {
  17507. this.rotation.x = 0;
  17508. this.rotation.y = Math.PI;
  17509. this.rotation.z = 0;
  17510. this.rotationAutoUpdate = false;
  17511. };
  17512. THREE.CombinedCamera.prototype.toLeftView = function() {
  17513. this.rotation.x = 0;
  17514. this.rotation.y = - Math.PI / 2;
  17515. this.rotation.z = 0;
  17516. this.rotationAutoUpdate = false;
  17517. };
  17518. THREE.CombinedCamera.prototype.toRightView = function() {
  17519. this.rotation.x = 0;
  17520. this.rotation.y = Math.PI / 2;
  17521. this.rotation.z = 0;
  17522. this.rotationAutoUpdate = false;
  17523. };
  17524. THREE.CombinedCamera.prototype.toTopView = function() {
  17525. this.rotation.x = - Math.PI / 2;
  17526. this.rotation.y = 0;
  17527. this.rotation.z = 0;
  17528. this.rotationAutoUpdate = false;
  17529. };
  17530. THREE.CombinedCamera.prototype.toBottomView = function() {
  17531. this.rotation.x = Math.PI / 2;
  17532. this.rotation.y = 0;
  17533. this.rotation.z = 0;
  17534. this.rotationAutoUpdate = false;
  17535. };
  17536. /**
  17537. * @author alteredq / http://alteredqualia.com/
  17538. *
  17539. * - 3d asterisk shape (for line pieces THREE.Line)
  17540. */
  17541. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  17542. THREE.Geometry.call( this );
  17543. var sd = innerRadius;
  17544. var ed = outerRadius;
  17545. var sd2 = 0.707 * sd;
  17546. var ed2 = 0.707 * ed;
  17547. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  17548. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  17549. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  17550. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  17551. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  17552. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  17553. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  17554. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  17555. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  17556. ];
  17557. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  17558. var x = rays[ i ][ 0 ];
  17559. var y = rays[ i ][ 1 ];
  17560. var z = rays[ i ][ 2 ];
  17561. this.vertices.push( new THREE.Vector3( x, y, z ) );
  17562. }
  17563. };
  17564. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  17565. * @author hughes
  17566. */
  17567. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17568. THREE.Geometry.call( this );
  17569. radius = radius || 50;
  17570. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17571. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17572. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17573. var i, uvs = [],
  17574. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17575. this.vertices.push(center);
  17576. uvs.push( centerUV );
  17577. for ( i = 0; i <= segments; i ++ ) {
  17578. var vertex = new THREE.Vector3();
  17579. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17580. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17581. this.vertices.push( vertex );
  17582. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17583. }
  17584. var n = new THREE.Vector3( 0, 0, -1 );
  17585. for ( i = 1; i <= segments; i ++ ) {
  17586. var v1 = i;
  17587. var v2 = i + 1 ;
  17588. var v3 = 0;
  17589. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17590. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17591. }
  17592. this.computeCentroids();
  17593. this.computeFaceNormals();
  17594. this.boundingSphere = { radius: radius };
  17595. };
  17596. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17597. /**
  17598. * @author mrdoob / http://mrdoob.com/
  17599. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17600. */
  17601. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17602. THREE.Geometry.call( this );
  17603. var scope = this;
  17604. this.width = width;
  17605. this.height = height;
  17606. this.depth = depth;
  17607. this.widthSegments = widthSegments || 1;
  17608. this.heightSegments = heightSegments || 1;
  17609. this.depthSegments = depthSegments || 1;
  17610. var width_half = this.width / 2;
  17611. var height_half = this.height / 2;
  17612. var depth_half = this.depth / 2;
  17613. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  17614. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  17615. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  17616. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  17617. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  17618. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  17619. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  17620. var w, ix, iy,
  17621. gridX = scope.widthSegments,
  17622. gridY = scope.heightSegments,
  17623. width_half = width / 2,
  17624. height_half = height / 2,
  17625. offset = scope.vertices.length;
  17626. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17627. w = 'z';
  17628. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17629. w = 'y';
  17630. gridY = scope.depthSegments;
  17631. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17632. w = 'x';
  17633. gridX = scope.depthSegments;
  17634. }
  17635. var gridX1 = gridX + 1,
  17636. gridY1 = gridY + 1,
  17637. segment_width = width / gridX,
  17638. segment_height = height / gridY,
  17639. normal = new THREE.Vector3();
  17640. normal[ w ] = depth > 0 ? 1 : - 1;
  17641. for ( iy = 0; iy < gridY1; iy ++ ) {
  17642. for ( ix = 0; ix < gridX1; ix ++ ) {
  17643. var vector = new THREE.Vector3();
  17644. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  17645. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  17646. vector[ w ] = depth;
  17647. scope.vertices.push( vector );
  17648. }
  17649. }
  17650. for ( iy = 0; iy < gridY; iy++ ) {
  17651. for ( ix = 0; ix < gridX; ix++ ) {
  17652. var a = ix + gridX1 * iy;
  17653. var b = ix + gridX1 * ( iy + 1 );
  17654. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  17655. var d = ( ix + 1 ) + gridX1 * iy;
  17656. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  17657. face.normal.copy( normal );
  17658. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  17659. face.materialIndex = materialIndex;
  17660. scope.faces.push( face );
  17661. scope.faceVertexUvs[ 0 ].push( [
  17662. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  17663. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  17664. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  17665. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  17666. ] );
  17667. }
  17668. }
  17669. }
  17670. this.computeCentroids();
  17671. this.mergeVertices();
  17672. };
  17673. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17674. /**
  17675. * @author mrdoob / http://mrdoob.com/
  17676. */
  17677. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  17678. THREE.Geometry.call( this );
  17679. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17680. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17681. height = height !== undefined ? height : 100;
  17682. var heightHalf = height / 2;
  17683. var segmentsX = radiusSegments || 8;
  17684. var segmentsY = heightSegments || 1;
  17685. var x, y, vertices = [], uvs = [];
  17686. for ( y = 0; y <= segmentsY; y ++ ) {
  17687. var verticesRow = [];
  17688. var uvsRow = [];
  17689. var v = y / segmentsY;
  17690. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17691. for ( x = 0; x <= segmentsX; x ++ ) {
  17692. var u = x / segmentsX;
  17693. var vertex = new THREE.Vector3();
  17694. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  17695. vertex.y = - v * height + heightHalf;
  17696. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  17697. this.vertices.push( vertex );
  17698. verticesRow.push( this.vertices.length - 1 );
  17699. uvsRow.push( new THREE.UV( u, 1 - v ) );
  17700. }
  17701. vertices.push( verticesRow );
  17702. uvs.push( uvsRow );
  17703. }
  17704. var tanTheta = ( radiusBottom - radiusTop ) / height;
  17705. var na, nb;
  17706. for ( x = 0; x < segmentsX; x ++ ) {
  17707. if ( radiusTop !== 0 ) {
  17708. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  17709. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  17710. } else {
  17711. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  17712. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  17713. }
  17714. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  17715. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  17716. for ( y = 0; y < segmentsY; y ++ ) {
  17717. var v1 = vertices[ y ][ x ];
  17718. var v2 = vertices[ y + 1 ][ x ];
  17719. var v3 = vertices[ y + 1 ][ x + 1 ];
  17720. var v4 = vertices[ y ][ x + 1 ];
  17721. var n1 = na.clone();
  17722. var n2 = na.clone();
  17723. var n3 = nb.clone();
  17724. var n4 = nb.clone();
  17725. var uv1 = uvs[ y ][ x ].clone();
  17726. var uv2 = uvs[ y + 1 ][ x ].clone();
  17727. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  17728. var uv4 = uvs[ y ][ x + 1 ].clone();
  17729. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  17730. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  17731. }
  17732. }
  17733. // top cap
  17734. if ( !openEnded && radiusTop > 0 ) {
  17735. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  17736. for ( x = 0; x < segmentsX; x ++ ) {
  17737. var v1 = vertices[ 0 ][ x ];
  17738. var v2 = vertices[ 0 ][ x + 1 ];
  17739. var v3 = this.vertices.length - 1;
  17740. var n1 = new THREE.Vector3( 0, 1, 0 );
  17741. var n2 = new THREE.Vector3( 0, 1, 0 );
  17742. var n3 = new THREE.Vector3( 0, 1, 0 );
  17743. var uv1 = uvs[ 0 ][ x ].clone();
  17744. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  17745. var uv3 = new THREE.UV( uv2.u, 0 );
  17746. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17747. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17748. }
  17749. }
  17750. // bottom cap
  17751. if ( !openEnded && radiusBottom > 0 ) {
  17752. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  17753. for ( x = 0; x < segmentsX; x ++ ) {
  17754. var v1 = vertices[ y ][ x + 1 ];
  17755. var v2 = vertices[ y ][ x ];
  17756. var v3 = this.vertices.length - 1;
  17757. var n1 = new THREE.Vector3( 0, - 1, 0 );
  17758. var n2 = new THREE.Vector3( 0, - 1, 0 );
  17759. var n3 = new THREE.Vector3( 0, - 1, 0 );
  17760. var uv1 = uvs[ y ][ x + 1 ].clone();
  17761. var uv2 = uvs[ y ][ x ].clone();
  17762. var uv3 = new THREE.UV( uv2.u, 1 );
  17763. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17764. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17765. }
  17766. }
  17767. this.computeCentroids();
  17768. this.computeFaceNormals();
  17769. }
  17770. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17771. /**
  17772. * @author zz85 / http://www.lab4games.net/zz85/blog
  17773. *
  17774. * Creates extruded geometry from a path shape.
  17775. *
  17776. * parameters = {
  17777. *
  17778. * size: <float>, // size of the text
  17779. * height: <float>, // thickness to extrude text
  17780. * curveSegments: <int>, // number of points on the curves
  17781. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  17782. * amount: <int>, // Amount
  17783. *
  17784. * bevelEnabled: <bool>, // turn on bevel
  17785. * bevelThickness: <float>, // how deep into text bevel goes
  17786. * bevelSize: <float>, // how far from text outline is bevel
  17787. * bevelSegments: <int>, // number of bevel layers
  17788. *
  17789. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  17790. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  17791. *
  17792. * material: <int> // material index for front and back faces
  17793. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  17794. * uvGenerator: <Object> // object that provides UV generator functions
  17795. *
  17796. * }
  17797. **/
  17798. THREE.ExtrudeGeometry = function ( shapes, options ) {
  17799. if ( typeof( shapes ) === "undefined" ) {
  17800. shapes = [];
  17801. return;
  17802. }
  17803. THREE.Geometry.call( this );
  17804. shapes = shapes instanceof Array ? shapes : [ shapes ];
  17805. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  17806. this.addShapeList( shapes, options );
  17807. this.computeCentroids();
  17808. this.computeFaceNormals();
  17809. // can't really use automatic vertex normals
  17810. // as then front and back sides get smoothed too
  17811. // should do separate smoothing just for sides
  17812. //this.computeVertexNormals();
  17813. //console.log( "took", ( Date.now() - startTime ) );
  17814. };
  17815. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17816. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  17817. var sl = shapes.length;
  17818. for ( var s = 0; s < sl; s ++ ) {
  17819. var shape = shapes[ s ];
  17820. this.addShape( shape, options );
  17821. }
  17822. };
  17823. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  17824. var amount = options.amount !== undefined ? options.amount : 100;
  17825. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  17826. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  17827. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17828. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  17829. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17830. var steps = options.steps !== undefined ? options.steps : 1;
  17831. var extrudePath = options.extrudePath;
  17832. var extrudePts, extrudeByPath = false;
  17833. var material = options.material;
  17834. var extrudeMaterial = options.extrudeMaterial;
  17835. // Use default WorldUVGenerator if no UV generators are specified.
  17836. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  17837. var shapebb = this.shapebb;
  17838. //shapebb = shape.getBoundingBox();
  17839. var splineTube, binormal, normal, position2;
  17840. if ( extrudePath ) {
  17841. extrudePts = extrudePath.getSpacedPoints( steps );
  17842. extrudeByPath = true;
  17843. bevelEnabled = false; // bevels not supported for path extrusion
  17844. // SETUP TNB variables
  17845. // Reuse TNB from TubeGeomtry for now.
  17846. // TODO1 - have a .isClosed in spline?
  17847. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  17848. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17849. binormal = new THREE.Vector3();
  17850. normal = new THREE.Vector3();
  17851. position2 = new THREE.Vector3();
  17852. }
  17853. // Safeguards if bevels are not enabled
  17854. if ( ! bevelEnabled ) {
  17855. bevelSegments = 0;
  17856. bevelThickness = 0;
  17857. bevelSize = 0;
  17858. }
  17859. // Variables initalization
  17860. var ahole, h, hl; // looping of holes
  17861. var scope = this;
  17862. var bevelPoints = [];
  17863. var shapesOffset = this.vertices.length;
  17864. var shapePoints = shape.extractPoints();
  17865. var vertices = shapePoints.shape;
  17866. var holes = shapePoints.holes;
  17867. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  17868. if ( reverse ) {
  17869. vertices = vertices.reverse();
  17870. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17871. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17872. ahole = holes[ h ];
  17873. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  17874. holes[ h ] = ahole.reverse();
  17875. }
  17876. }
  17877. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  17878. }
  17879. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  17880. /* Vertices */
  17881. var contour = vertices; // vertices has all points but contour has only points of circumference
  17882. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17883. ahole = holes[ h ];
  17884. vertices = vertices.concat( ahole );
  17885. }
  17886. function scalePt2 ( pt, vec, size ) {
  17887. if ( !vec ) console.log( "die" );
  17888. return vec.clone().multiplyScalar( size ).addSelf( pt );
  17889. }
  17890. var b, bs, t, z,
  17891. vert, vlen = vertices.length,
  17892. face, flen = faces.length,
  17893. cont, clen = contour.length;
  17894. // Find directions for point movement
  17895. var RAD_TO_DEGREES = 180 / Math.PI;
  17896. function getBevelVec( pt_i, pt_j, pt_k ) {
  17897. // Algorithm 2
  17898. return getBevelVec2( pt_i, pt_j, pt_k );
  17899. }
  17900. function getBevelVec1( pt_i, pt_j, pt_k ) {
  17901. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  17902. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  17903. if ( anglea > angleb ) {
  17904. angleb += Math.PI * 2;
  17905. }
  17906. var anglec = ( anglea + angleb ) / 2;
  17907. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  17908. var x = - Math.cos( anglec );
  17909. var y = - Math.sin( anglec );
  17910. var vec = new THREE.Vector2( x, y ); //.normalize();
  17911. return vec;
  17912. }
  17913. function getBevelVec2( pt_i, pt_j, pt_k ) {
  17914. var a = THREE.ExtrudeGeometry.__v1,
  17915. b = THREE.ExtrudeGeometry.__v2,
  17916. v_hat = THREE.ExtrudeGeometry.__v3,
  17917. w_hat = THREE.ExtrudeGeometry.__v4,
  17918. p = THREE.ExtrudeGeometry.__v5,
  17919. q = THREE.ExtrudeGeometry.__v6,
  17920. v, w,
  17921. v_dot_w_hat, q_sub_p_dot_w_hat,
  17922. s, intersection;
  17923. // good reading for line-line intersection
  17924. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  17925. // define a as vector j->i
  17926. // define b as vectot k->i
  17927. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  17928. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  17929. // get unit vectors
  17930. v = a.normalize();
  17931. w = b.normalize();
  17932. // normals from pt i
  17933. v_hat.set( -v.y, v.x );
  17934. w_hat.set( w.y, -w.x );
  17935. // pts from i
  17936. p.copy( pt_i ).addSelf( v_hat );
  17937. q.copy( pt_i ).addSelf( w_hat );
  17938. if ( p.equals( q ) ) {
  17939. //console.log("Warning: lines are straight");
  17940. return w_hat.clone();
  17941. }
  17942. // Points from j, k. helps prevents points cross overover most of the time
  17943. p.copy( pt_j ).addSelf( v_hat );
  17944. q.copy( pt_k ).addSelf( w_hat );
  17945. v_dot_w_hat = v.dot( w_hat );
  17946. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  17947. // We should not reach these conditions
  17948. if ( v_dot_w_hat === 0 ) {
  17949. console.log( "Either infinite or no solutions!" );
  17950. if ( q_sub_p_dot_w_hat === 0 ) {
  17951. console.log( "Its finite solutions." );
  17952. } else {
  17953. console.log( "Too bad, no solutions." );
  17954. }
  17955. }
  17956. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  17957. if ( s < 0 ) {
  17958. // in case of emergecy, revert to algorithm 1.
  17959. return getBevelVec1( pt_i, pt_j, pt_k );
  17960. }
  17961. intersection = v.multiplyScalar( s ).addSelf( p );
  17962. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  17963. }
  17964. var contourMovements = [];
  17965. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  17966. if ( j === il ) j = 0;
  17967. if ( k === il ) k = 0;
  17968. // (j)---(i)---(k)
  17969. // console.log('i,j,k', i, j , k)
  17970. var pt_i = contour[ i ];
  17971. var pt_j = contour[ j ];
  17972. var pt_k = contour[ k ];
  17973. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  17974. }
  17975. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  17976. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17977. ahole = holes[ h ];
  17978. oneHoleMovements = [];
  17979. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  17980. if ( j === il ) j = 0;
  17981. if ( k === il ) k = 0;
  17982. // (j)---(i)---(k)
  17983. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  17984. }
  17985. holesMovements.push( oneHoleMovements );
  17986. verticesMovements = verticesMovements.concat( oneHoleMovements );
  17987. }
  17988. // Loop bevelSegments, 1 for the front, 1 for the back
  17989. for ( b = 0; b < bevelSegments; b ++ ) {
  17990. //for ( b = bevelSegments; b > 0; b -- ) {
  17991. t = b / bevelSegments;
  17992. z = bevelThickness * ( 1 - t );
  17993. //z = bevelThickness * t;
  17994. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  17995. //bs = bevelSize * t ; // linear
  17996. // contract shape
  17997. for ( i = 0, il = contour.length; i < il; i ++ ) {
  17998. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  17999. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18000. v( vert.x, vert.y, - z );
  18001. }
  18002. // expand holes
  18003. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18004. ahole = holes[ h ];
  18005. oneHoleMovements = holesMovements[ h ];
  18006. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18007. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18008. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18009. v( vert.x, vert.y, -z );
  18010. }
  18011. }
  18012. }
  18013. bs = bevelSize;
  18014. // Back facing vertices
  18015. for ( i = 0; i < vlen; i ++ ) {
  18016. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18017. if ( !extrudeByPath ) {
  18018. v( vert.x, vert.y, 0 );
  18019. } else {
  18020. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18021. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18022. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18023. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18024. v( position2.x, position2.y, position2.z );
  18025. }
  18026. }
  18027. // Add stepped vertices...
  18028. // Including front facing vertices
  18029. var s;
  18030. for ( s = 1; s <= steps; s ++ ) {
  18031. for ( i = 0; i < vlen; i ++ ) {
  18032. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18033. if ( !extrudeByPath ) {
  18034. v( vert.x, vert.y, amount / steps * s );
  18035. } else {
  18036. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18037. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18038. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18039. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18040. v( position2.x, position2.y, position2.z );
  18041. }
  18042. }
  18043. }
  18044. // Add bevel segments planes
  18045. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18046. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18047. t = b / bevelSegments;
  18048. z = bevelThickness * ( 1 - t );
  18049. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18050. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18051. // contract shape
  18052. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18053. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18054. v( vert.x, vert.y, amount + z );
  18055. }
  18056. // expand holes
  18057. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18058. ahole = holes[ h ];
  18059. oneHoleMovements = holesMovements[ h ];
  18060. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18061. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18062. if ( !extrudeByPath ) {
  18063. v( vert.x, vert.y, amount + z );
  18064. } else {
  18065. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18066. }
  18067. }
  18068. }
  18069. }
  18070. /* Faces */
  18071. // Top and bottom faces
  18072. buildLidFaces();
  18073. // Sides faces
  18074. buildSideFaces();
  18075. ///// Internal functions
  18076. function buildLidFaces() {
  18077. if ( bevelEnabled ) {
  18078. var layer = 0 ; // steps + 1
  18079. var offset = vlen * layer;
  18080. // Bottom faces
  18081. for ( i = 0; i < flen; i ++ ) {
  18082. face = faces[ i ];
  18083. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18084. }
  18085. layer = steps + bevelSegments * 2;
  18086. offset = vlen * layer;
  18087. // Top faces
  18088. for ( i = 0; i < flen; i ++ ) {
  18089. face = faces[ i ];
  18090. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18091. }
  18092. } else {
  18093. // Bottom faces
  18094. for ( i = 0; i < flen; i++ ) {
  18095. face = faces[ i ];
  18096. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18097. }
  18098. // Top faces
  18099. for ( i = 0; i < flen; i ++ ) {
  18100. face = faces[ i ];
  18101. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18102. }
  18103. }
  18104. }
  18105. // Create faces for the z-sides of the shape
  18106. function buildSideFaces() {
  18107. var layeroffset = 0;
  18108. sidewalls( contour, layeroffset );
  18109. layeroffset += contour.length;
  18110. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18111. ahole = holes[ h ];
  18112. sidewalls( ahole, layeroffset );
  18113. //, true
  18114. layeroffset += ahole.length;
  18115. }
  18116. }
  18117. function sidewalls( contour, layeroffset ) {
  18118. var j, k;
  18119. i = contour.length;
  18120. while ( --i >= 0 ) {
  18121. j = i;
  18122. k = i - 1;
  18123. if ( k < 0 ) k = contour.length - 1;
  18124. //console.log('b', i,j, i-1, k,vertices.length);
  18125. var s = 0, sl = steps + bevelSegments * 2;
  18126. for ( s = 0; s < sl; s ++ ) {
  18127. var slen1 = vlen * s;
  18128. var slen2 = vlen * ( s + 1 );
  18129. var a = layeroffset + j + slen1,
  18130. b = layeroffset + k + slen1,
  18131. c = layeroffset + k + slen2,
  18132. d = layeroffset + j + slen2;
  18133. f4( a, b, c, d, contour, s, sl, j, k );
  18134. }
  18135. }
  18136. }
  18137. function v( x, y, z ) {
  18138. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18139. }
  18140. function f3( a, b, c, isBottom ) {
  18141. a += shapesOffset;
  18142. b += shapesOffset;
  18143. c += shapesOffset;
  18144. // normal, color, material
  18145. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18146. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18147. scope.faceVertexUvs[ 0 ].push( uvs );
  18148. }
  18149. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18150. a += shapesOffset;
  18151. b += shapesOffset;
  18152. c += shapesOffset;
  18153. d += shapesOffset;
  18154. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18155. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18156. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18157. scope.faceVertexUvs[ 0 ].push( uvs );
  18158. }
  18159. };
  18160. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18161. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18162. var ax = geometry.vertices[ indexA ].x,
  18163. ay = geometry.vertices[ indexA ].y,
  18164. bx = geometry.vertices[ indexB ].x,
  18165. by = geometry.vertices[ indexB ].y,
  18166. cx = geometry.vertices[ indexC ].x,
  18167. cy = geometry.vertices[ indexC ].y;
  18168. return [
  18169. new THREE.UV( ax, ay ),
  18170. new THREE.UV( bx, by ),
  18171. new THREE.UV( cx, cy )
  18172. ];
  18173. },
  18174. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18175. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18176. },
  18177. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18178. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18179. contourIndex1, contourIndex2 ) {
  18180. var ax = geometry.vertices[ indexA ].x,
  18181. ay = geometry.vertices[ indexA ].y,
  18182. az = geometry.vertices[ indexA ].z,
  18183. bx = geometry.vertices[ indexB ].x,
  18184. by = geometry.vertices[ indexB ].y,
  18185. bz = geometry.vertices[ indexB ].z,
  18186. cx = geometry.vertices[ indexC ].x,
  18187. cy = geometry.vertices[ indexC ].y,
  18188. cz = geometry.vertices[ indexC ].z,
  18189. dx = geometry.vertices[ indexD ].x,
  18190. dy = geometry.vertices[ indexD ].y,
  18191. dz = geometry.vertices[ indexD ].z;
  18192. if ( Math.abs( ay - by ) < 0.01 ) {
  18193. return [
  18194. new THREE.UV( ax, 1 - az ),
  18195. new THREE.UV( bx, 1 - bz ),
  18196. new THREE.UV( cx, 1 - cz ),
  18197. new THREE.UV( dx, 1 - dz )
  18198. ];
  18199. } else {
  18200. return [
  18201. new THREE.UV( ay, 1 - az ),
  18202. new THREE.UV( by, 1 - bz ),
  18203. new THREE.UV( cy, 1 - cz ),
  18204. new THREE.UV( dy, 1 - dz )
  18205. ];
  18206. }
  18207. }
  18208. };
  18209. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18210. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18211. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18212. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18213. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18214. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18215. /**
  18216. * @author jonobr1 / http://jonobr1.com
  18217. *
  18218. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18219. * ExtrudeGeometry.
  18220. *
  18221. * parameters = {
  18222. *
  18223. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18224. *
  18225. * material: <int> // material index for front and back faces
  18226. * uvGenerator: <Object> // object that provides UV generator functions
  18227. *
  18228. * }
  18229. **/
  18230. THREE.ShapeGeometry = function ( shapes, options ) {
  18231. THREE.Geometry.call( this );
  18232. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18233. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18234. this.addShapeList( shapes, options );
  18235. this.computeCentroids();
  18236. this.computeFaceNormals();
  18237. };
  18238. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18239. /**
  18240. * Add an array of shapes to THREE.ShapeGeometry.
  18241. */
  18242. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18243. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18244. this.addShape( shapes[ i ], options );
  18245. }
  18246. return this;
  18247. };
  18248. /**
  18249. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18250. */
  18251. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18252. if ( options === undefined ) options = {};
  18253. var material = options.material;
  18254. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18255. var shapebb = this.shapebb;
  18256. //
  18257. var i, l, hole, s;
  18258. var shapesOffset = this.vertices.length;
  18259. var shapePoints = shape.extractPoints();
  18260. var vertices = shapePoints.shape;
  18261. var holes = shapePoints.holes;
  18262. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18263. if ( reverse ) {
  18264. vertices = vertices.reverse();
  18265. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18266. for ( i = 0, l = holes.length; i < l; i++ ) {
  18267. hole = holes[ i ];
  18268. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18269. holes[ i ] = hole.reverse();
  18270. }
  18271. }
  18272. reverse = false;
  18273. }
  18274. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18275. // Vertices
  18276. var contour = vertices;
  18277. for ( i = 0, l = holes.length; i < l; i++ ) {
  18278. hole = holes[ i ];
  18279. vertices = vertices.concat( hole );
  18280. }
  18281. //
  18282. var vert, vlen = vertices.length;
  18283. var face, flen = faces.length;
  18284. var cont, clen = contour.length;
  18285. for ( i = 0; i < vlen; i++ ) {
  18286. vert = vertices[ i ];
  18287. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18288. }
  18289. for ( i = 0; i < flen; i++ ) {
  18290. face = faces[ i ];
  18291. var a = face[ 0 ] + shapesOffset;
  18292. var b = face[ 1 ] + shapesOffset;
  18293. var c = face[ 2 ] + shapesOffset;
  18294. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18295. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18296. }
  18297. };
  18298. /**
  18299. * @author astrodud / http://astrodud.isgreat.org/
  18300. * @author zz85 / https://github.com/zz85
  18301. */
  18302. THREE.LatheGeometry = function ( points, steps, angle ) {
  18303. THREE.Geometry.call( this );
  18304. var _steps = steps || 12;
  18305. var _angle = angle || 2 * Math.PI;
  18306. var _newV = [];
  18307. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18308. for ( var j = 0; j < points.length; j ++ ) {
  18309. _newV[ j ] = points[ j ].clone();
  18310. this.vertices.push( _newV[ j ] );
  18311. }
  18312. var i, il = _steps + 1;
  18313. for ( i = 0; i < il; i ++ ) {
  18314. for ( var j = 0; j < _newV.length; j ++ ) {
  18315. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18316. this.vertices.push( _newV[ j ] );
  18317. }
  18318. }
  18319. for ( i = 0; i < _steps; i ++ ) {
  18320. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18321. var a = i * kl + k;
  18322. var b = ( ( i + 1 ) % il ) * kl + k;
  18323. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18324. var d = i * kl + ( k + 1 ) % kl;
  18325. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18326. this.faceVertexUvs[ 0 ].push( [
  18327. new THREE.UV( 1 - i / _steps, k / kl ),
  18328. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18329. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18330. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18331. ] );
  18332. }
  18333. }
  18334. this.computeCentroids();
  18335. this.computeFaceNormals();
  18336. this.computeVertexNormals();
  18337. };
  18338. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18339. /**
  18340. * @author mrdoob / http://mrdoob.com/
  18341. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18342. */
  18343. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18344. THREE.Geometry.call( this );
  18345. this.width = width;
  18346. this.height = height;
  18347. this.widthSegments = widthSegments || 1;
  18348. this.heightSegments = heightSegments || 1;
  18349. var ix, iz;
  18350. var width_half = width / 2;
  18351. var height_half = height / 2;
  18352. var gridX = this.widthSegments;
  18353. var gridZ = this.heightSegments;
  18354. var gridX1 = gridX + 1;
  18355. var gridZ1 = gridZ + 1;
  18356. var segment_width = this.width / gridX;
  18357. var segment_height = this.height / gridZ;
  18358. var normal = new THREE.Vector3( 0, 0, 1 );
  18359. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18360. for ( ix = 0; ix < gridX1; ix ++ ) {
  18361. var x = ix * segment_width - width_half;
  18362. var y = iz * segment_height - height_half;
  18363. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18364. }
  18365. }
  18366. for ( iz = 0; iz < gridZ; iz ++ ) {
  18367. for ( ix = 0; ix < gridX; ix ++ ) {
  18368. var a = ix + gridX1 * iz;
  18369. var b = ix + gridX1 * ( iz + 1 );
  18370. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18371. var d = ( ix + 1 ) + gridX1 * iz;
  18372. var face = new THREE.Face4( a, b, c, d );
  18373. face.normal.copy( normal );
  18374. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18375. this.faces.push( face );
  18376. this.faceVertexUvs[ 0 ].push( [
  18377. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18378. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18379. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18380. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18381. ] );
  18382. }
  18383. }
  18384. this.computeCentroids();
  18385. };
  18386. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18387. /**
  18388. * @author mrdoob / http://mrdoob.com/
  18389. */
  18390. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18391. THREE.Geometry.call( this );
  18392. this.radius = radius || 50;
  18393. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  18394. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  18395. phiStart = phiStart !== undefined ? phiStart : 0;
  18396. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18397. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18398. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18399. var x, y, vertices = [], uvs = [];
  18400. for ( y = 0; y <= this.heightSegments; y ++ ) {
  18401. var verticesRow = [];
  18402. var uvsRow = [];
  18403. for ( x = 0; x <= this.widthSegments; x ++ ) {
  18404. var u = x / this.widthSegments;
  18405. var v = y / this.heightSegments;
  18406. var vertex = new THREE.Vector3();
  18407. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18408. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  18409. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18410. this.vertices.push( vertex );
  18411. verticesRow.push( this.vertices.length - 1 );
  18412. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18413. }
  18414. vertices.push( verticesRow );
  18415. uvs.push( uvsRow );
  18416. }
  18417. for ( y = 0; y < this.heightSegments; y ++ ) {
  18418. for ( x = 0; x < this.widthSegments; x ++ ) {
  18419. var v1 = vertices[ y ][ x + 1 ];
  18420. var v2 = vertices[ y ][ x ];
  18421. var v3 = vertices[ y + 1 ][ x ];
  18422. var v4 = vertices[ y + 1 ][ x + 1 ];
  18423. var n1 = this.vertices[ v1 ].clone().normalize();
  18424. var n2 = this.vertices[ v2 ].clone().normalize();
  18425. var n3 = this.vertices[ v3 ].clone().normalize();
  18426. var n4 = this.vertices[ v4 ].clone().normalize();
  18427. var uv1 = uvs[ y ][ x + 1 ].clone();
  18428. var uv2 = uvs[ y ][ x ].clone();
  18429. var uv3 = uvs[ y + 1 ][ x ].clone();
  18430. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18431. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  18432. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18433. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18434. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  18435. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18436. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18437. } else {
  18438. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18439. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18440. }
  18441. }
  18442. }
  18443. this.computeCentroids();
  18444. this.computeFaceNormals();
  18445. this.boundingSphere = { radius: this.radius };
  18446. };
  18447. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18448. /**
  18449. * @author zz85 / http://www.lab4games.net/zz85/blog
  18450. * @author alteredq / http://alteredqualia.com/
  18451. *
  18452. * For creating 3D text geometry in three.js
  18453. *
  18454. * Text = 3D Text
  18455. *
  18456. * parameters = {
  18457. * size: <float>, // size of the text
  18458. * height: <float>, // thickness to extrude text
  18459. * curveSegments: <int>, // number of points on the curves
  18460. *
  18461. * font: <string>, // font name
  18462. * weight: <string>, // font weight (normal, bold)
  18463. * style: <string>, // font style (normal, italics)
  18464. *
  18465. * bevelEnabled: <bool>, // turn on bevel
  18466. * bevelThickness: <float>, // how deep into text bevel goes
  18467. * bevelSize: <float>, // how far from text outline is bevel
  18468. * }
  18469. *
  18470. */
  18471. /* Usage Examples
  18472. // TextGeometry wrapper
  18473. var text3d = new TextGeometry( text, options );
  18474. // Complete manner
  18475. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18476. var text3d = new ExtrudeGeometry( textShapes, options );
  18477. */
  18478. THREE.TextGeometry = function ( text, parameters ) {
  18479. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18480. // translate parameters to ExtrudeGeometry API
  18481. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18482. // defaults
  18483. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18484. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18485. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18486. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18487. };
  18488. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18489. /**
  18490. * @author oosmoxiecode
  18491. * @author mrdoob / http://mrdoob.com/
  18492. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18493. */
  18494. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  18495. THREE.Geometry.call( this );
  18496. var scope = this;
  18497. this.radius = radius || 100;
  18498. this.tube = tube || 40;
  18499. this.radialSegments = radialSegments || 8;
  18500. this.tubularSegments = tubularSegments || 6;
  18501. this.arc = arc || Math.PI * 2;
  18502. var center = new THREE.Vector3(), uvs = [], normals = [];
  18503. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  18504. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  18505. var u = i / this.tubularSegments * this.arc;
  18506. var v = j / this.radialSegments * Math.PI * 2;
  18507. center.x = this.radius * Math.cos( u );
  18508. center.y = this.radius * Math.sin( u );
  18509. var vertex = new THREE.Vector3();
  18510. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18511. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18512. vertex.z = this.tube * Math.sin( v );
  18513. this.vertices.push( vertex );
  18514. uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
  18515. normals.push( vertex.clone().subSelf( center ).normalize() );
  18516. }
  18517. }
  18518. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  18519. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  18520. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  18521. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  18522. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  18523. var d = ( this.tubularSegments + 1 ) * j + i;
  18524. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18525. face.normal.addSelf( normals[ a ] );
  18526. face.normal.addSelf( normals[ b ] );
  18527. face.normal.addSelf( normals[ c ] );
  18528. face.normal.addSelf( normals[ d ] );
  18529. face.normal.normalize();
  18530. this.faces.push( face );
  18531. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18532. }
  18533. }
  18534. this.computeCentroids();
  18535. };
  18536. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18537. /**
  18538. * @author oosmoxiecode
  18539. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18540. */
  18541. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  18542. THREE.Geometry.call( this );
  18543. var scope = this;
  18544. this.radius = radius || 200;
  18545. this.tube = tube || 40;
  18546. this.radialSegments = radialSegments || 64;
  18547. this.tubularSegments = tubularSegments || 8;
  18548. this.p = p || 2;
  18549. this.q = q || 3;
  18550. this.heightScale = heightScale || 1;
  18551. this.grid = new Array(this.radialSegments);
  18552. var tang = new THREE.Vector3();
  18553. var n = new THREE.Vector3();
  18554. var bitan = new THREE.Vector3();
  18555. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18556. this.grid[ i ] = new Array( this.tubularSegments );
  18557. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18558. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  18559. var v = j / this.tubularSegments * 2 * Math.PI;
  18560. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18561. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18562. var cx, cy;
  18563. tang.sub( p2, p1 );
  18564. n.add( p2, p1 );
  18565. bitan.cross( tang, n );
  18566. n.cross( bitan, tang );
  18567. bitan.normalize();
  18568. n.normalize();
  18569. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18570. cy = this.tube * Math.sin( v );
  18571. p1.x += cx * n.x + cy * bitan.x;
  18572. p1.y += cx * n.y + cy * bitan.y;
  18573. p1.z += cx * n.z + cy * bitan.z;
  18574. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18575. }
  18576. }
  18577. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18578. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18579. var ip = ( i + 1 ) % this.radialSegments;
  18580. var jp = ( j + 1 ) % this.tubularSegments;
  18581. var a = this.grid[ i ][ j ];
  18582. var b = this.grid[ ip ][ j ];
  18583. var c = this.grid[ ip ][ jp ];
  18584. var d = this.grid[ i ][ jp ];
  18585. var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
  18586. var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  18587. var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18588. var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18589. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18590. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18591. }
  18592. }
  18593. this.computeCentroids();
  18594. this.computeFaceNormals();
  18595. this.computeVertexNormals();
  18596. function vert( x, y, z ) {
  18597. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18598. }
  18599. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18600. var cu = Math.cos( u );
  18601. var cv = Math.cos( v );
  18602. var su = Math.sin( u );
  18603. var quOverP = in_q / in_p * u;
  18604. var cs = Math.cos( quOverP );
  18605. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18606. var ty = radius * ( 2 + cs ) * su * 0.5;
  18607. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18608. return new THREE.Vector3( tx, ty, tz );
  18609. }
  18610. };
  18611. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18612. /**
  18613. * @author WestLangley / https://github.com/WestLangley
  18614. * @author zz85 / https://github.com/zz85
  18615. * @author miningold / https://github.com/miningold
  18616. *
  18617. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18618. *
  18619. * Creates a tube which extrudes along a 3d spline
  18620. *
  18621. * Uses parallel transport frames as described in
  18622. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18623. */
  18624. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  18625. THREE.Geometry.call( this );
  18626. this.path = path;
  18627. this.segments = segments || 64;
  18628. this.radius = radius || 1;
  18629. this.radiusSegments = radiusSegments || 8;
  18630. this.closed = closed || false;
  18631. if ( debug ) this.debug = new THREE.Object3D();
  18632. this.grid = [];
  18633. var scope = this,
  18634. tangent,
  18635. normal,
  18636. binormal,
  18637. numpoints = this.segments + 1,
  18638. x, y, z,
  18639. tx, ty, tz,
  18640. u, v,
  18641. cx, cy,
  18642. pos, pos2 = new THREE.Vector3(),
  18643. i, j,
  18644. ip, jp,
  18645. a, b, c, d,
  18646. uva, uvb, uvc, uvd;
  18647. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  18648. tangents = frames.tangents,
  18649. normals = frames.normals,
  18650. binormals = frames.binormals;
  18651. // proxy internals
  18652. this.tangents = tangents;
  18653. this.normals = normals;
  18654. this.binormals = binormals;
  18655. function vert( x, y, z ) {
  18656. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18657. }
  18658. // consruct the grid
  18659. for ( i = 0; i < numpoints; i++ ) {
  18660. this.grid[ i ] = [];
  18661. u = i / ( numpoints - 1 );
  18662. pos = path.getPointAt( u );
  18663. tangent = tangents[ i ];
  18664. normal = normals[ i ];
  18665. binormal = binormals[ i ];
  18666. if ( this.debug ) {
  18667. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  18668. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  18669. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  18670. }
  18671. for ( j = 0; j < this.radiusSegments; j++ ) {
  18672. v = j / this.radiusSegments * 2 * Math.PI;
  18673. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18674. cy = this.radius * Math.sin( v );
  18675. pos2.copy( pos );
  18676. pos2.x += cx * normal.x + cy * binormal.x;
  18677. pos2.y += cx * normal.y + cy * binormal.y;
  18678. pos2.z += cx * normal.z + cy * binormal.z;
  18679. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18680. }
  18681. }
  18682. // construct the mesh
  18683. for ( i = 0; i < this.segments; i++ ) {
  18684. for ( j = 0; j < this.radiusSegments; j++ ) {
  18685. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  18686. jp = (j + 1) % this.radiusSegments;
  18687. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18688. b = this.grid[ ip ][ j ];
  18689. c = this.grid[ ip ][ jp ];
  18690. d = this.grid[ i ][ jp ];
  18691. uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
  18692. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
  18693. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  18694. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
  18695. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18696. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18697. }
  18698. }
  18699. this.computeCentroids();
  18700. this.computeFaceNormals();
  18701. this.computeVertexNormals();
  18702. };
  18703. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18704. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18705. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  18706. var
  18707. tangent = new THREE.Vector3(),
  18708. normal = new THREE.Vector3(),
  18709. binormal = new THREE.Vector3(),
  18710. tangents = [],
  18711. normals = [],
  18712. binormals = [],
  18713. vec = new THREE.Vector3(),
  18714. mat = new THREE.Matrix4(),
  18715. numpoints = segments + 1,
  18716. theta,
  18717. epsilon = 0.0001,
  18718. smallest,
  18719. tx, ty, tz,
  18720. i, u, v;
  18721. // expose internals
  18722. this.tangents = tangents;
  18723. this.normals = normals;
  18724. this.binormals = binormals;
  18725. // compute the tangent vectors for each segment on the path
  18726. for ( i = 0; i < numpoints; i++ ) {
  18727. u = i / ( numpoints - 1 );
  18728. tangents[ i ] = path.getTangentAt( u );
  18729. tangents[ i ].normalize();
  18730. }
  18731. initialNormal3();
  18732. function initialNormal1(lastBinormal) {
  18733. // fixed start binormal. Has dangers of 0 vectors
  18734. normals[ 0 ] = new THREE.Vector3();
  18735. binormals[ 0 ] = new THREE.Vector3();
  18736. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18737. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  18738. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18739. }
  18740. function initialNormal2() {
  18741. // This uses the Frenet-Serret formula for deriving binormal
  18742. var t2 = path.getTangentAt( epsilon );
  18743. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  18744. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  18745. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18746. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18747. }
  18748. function initialNormal3() {
  18749. // select an initial normal vector perpenicular to the first tangent vector,
  18750. // and in the direction of the smallest tangent xyz component
  18751. normals[ 0 ] = new THREE.Vector3();
  18752. binormals[ 0 ] = new THREE.Vector3();
  18753. smallest = Number.MAX_VALUE;
  18754. tx = Math.abs( tangents[ 0 ].x );
  18755. ty = Math.abs( tangents[ 0 ].y );
  18756. tz = Math.abs( tangents[ 0 ].z );
  18757. if ( tx <= smallest ) {
  18758. smallest = tx;
  18759. normal.set( 1, 0, 0 );
  18760. }
  18761. if ( ty <= smallest ) {
  18762. smallest = ty;
  18763. normal.set( 0, 1, 0 );
  18764. }
  18765. if ( tz <= smallest ) {
  18766. normal.set( 0, 0, 1 );
  18767. }
  18768. vec.cross( tangents[ 0 ], normal ).normalize();
  18769. normals[ 0 ].cross( tangents[ 0 ], vec );
  18770. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  18771. }
  18772. // compute the slowly-varying normal and binormal vectors for each segment on the path
  18773. for ( i = 1; i < numpoints; i++ ) {
  18774. normals[ i ] = normals[ i-1 ].clone();
  18775. binormals[ i ] = binormals[ i-1 ].clone();
  18776. vec.cross( tangents[ i-1 ], tangents[ i ] );
  18777. if ( vec.length() > epsilon ) {
  18778. vec.normalize();
  18779. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  18780. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  18781. }
  18782. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18783. }
  18784. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18785. if ( closed ) {
  18786. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  18787. theta /= ( numpoints - 1 );
  18788. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  18789. theta = -theta;
  18790. }
  18791. for ( i = 1; i < numpoints; i++ ) {
  18792. // twist a little...
  18793. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  18794. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18795. }
  18796. }
  18797. };
  18798. /**
  18799. * @author clockworkgeek / https://github.com/clockworkgeek
  18800. * @author timothypratley / https://github.com/timothypratley
  18801. */
  18802. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  18803. THREE.Geometry.call( this );
  18804. radius = radius || 1;
  18805. detail = detail || 0;
  18806. var that = this;
  18807. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  18808. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  18809. }
  18810. var midpoints = [], p = this.vertices;
  18811. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  18812. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  18813. }
  18814. this.mergeVertices();
  18815. // Apply radius
  18816. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  18817. this.vertices[ i ].multiplyScalar( radius );
  18818. }
  18819. // Project vector onto sphere's surface
  18820. function prepare( vector ) {
  18821. var vertex = vector.normalize().clone();
  18822. vertex.index = that.vertices.push( vertex ) - 1;
  18823. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  18824. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  18825. var v = inclination( vector ) / Math.PI + 0.5;
  18826. vertex.uv = new THREE.UV( u, 1 - v );
  18827. return vertex;
  18828. }
  18829. // Approximate a curved face with recursively sub-divided triangles.
  18830. function make( v1, v2, v3, detail ) {
  18831. if ( detail < 1 ) {
  18832. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  18833. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  18834. face.normal = face.centroid.clone().normalize();
  18835. that.faces.push( face );
  18836. var azi = azimuth( face.centroid );
  18837. that.faceVertexUvs[ 0 ].push( [
  18838. correctUV( v1.uv, v1, azi ),
  18839. correctUV( v2.uv, v2, azi ),
  18840. correctUV( v3.uv, v3, azi )
  18841. ] );
  18842. } else {
  18843. detail -= 1;
  18844. // split triangle into 4 smaller triangles
  18845. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  18846. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  18847. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  18848. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  18849. }
  18850. }
  18851. function midpoint( v1, v2 ) {
  18852. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  18853. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  18854. var mid = midpoints[ v1.index ][ v2.index ];
  18855. if ( mid === undefined ) {
  18856. // generate mean point and project to surface with prepare()
  18857. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  18858. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  18859. );
  18860. }
  18861. return mid;
  18862. }
  18863. // Angle around the Y axis, counter-clockwise when looking from above.
  18864. function azimuth( vector ) {
  18865. return Math.atan2( vector.z, -vector.x );
  18866. }
  18867. // Angle above the XZ plane.
  18868. function inclination( vector ) {
  18869. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18870. }
  18871. // Texture fixing helper. Spheres have some odd behaviours.
  18872. function correctUV( uv, vector, azimuth ) {
  18873. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  18874. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  18875. return uv;
  18876. }
  18877. this.computeCentroids();
  18878. this.boundingSphere = { radius: radius };
  18879. };
  18880. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18881. /**
  18882. * @author timothypratley / https://github.com/timothypratley
  18883. */
  18884. THREE.IcosahedronGeometry = function ( radius, detail ) {
  18885. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18886. var vertices = [
  18887. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  18888. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  18889. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  18890. ];
  18891. var faces = [
  18892. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  18893. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  18894. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  18895. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  18896. ];
  18897. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  18898. };
  18899. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18900. /**
  18901. * @author timothypratley / https://github.com/timothypratley
  18902. */
  18903. THREE.OctahedronGeometry = function ( radius, detail ) {
  18904. var vertices = [
  18905. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  18906. ];
  18907. var faces = [
  18908. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  18909. ];
  18910. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  18911. };
  18912. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18913. /**
  18914. * @author timothypratley / https://github.com/timothypratley
  18915. */
  18916. THREE.TetrahedronGeometry = function ( radius, detail ) {
  18917. var vertices = [
  18918. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  18919. ];
  18920. var faces = [
  18921. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  18922. ];
  18923. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  18924. };
  18925. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18926. /**
  18927. * @author zz85 / https://github.com/zz85
  18928. * Parametric Surfaces Geometry
  18929. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18930. *
  18931. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  18932. *
  18933. */
  18934. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  18935. THREE.Geometry.call( this );
  18936. var verts = this.vertices;
  18937. var faces = this.faces;
  18938. var uvs = this.faceVertexUvs[ 0 ];
  18939. useTris = (useTris === undefined) ? false : useTris;
  18940. var i, il, j, p;
  18941. var u, v;
  18942. var stackCount = stacks + 1;
  18943. var sliceCount = slices + 1;
  18944. for ( i = 0; i <= stacks; i ++ ) {
  18945. v = i / stacks;
  18946. for ( j = 0; j <= slices; j ++ ) {
  18947. u = j / slices;
  18948. p = func( u, v );
  18949. verts.push( p );
  18950. }
  18951. }
  18952. var a, b, c, d;
  18953. var uva, uvb, uvc, uvd;
  18954. for ( i = 0; i < stacks; i ++ ) {
  18955. for ( j = 0; j < slices; j ++ ) {
  18956. a = i * sliceCount + j;
  18957. b = i * sliceCount + j + 1;
  18958. c = (i + 1) * sliceCount + j;
  18959. d = (i + 1) * sliceCount + j + 1;
  18960. uva = new THREE.UV( j / slices, i / stacks );
  18961. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  18962. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  18963. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  18964. if ( useTris ) {
  18965. faces.push( new THREE.Face3( a, b, c ) );
  18966. faces.push( new THREE.Face3( b, d, c ) );
  18967. uvs.push( [ uva, uvb, uvc ] );
  18968. uvs.push( [ uvb, uvd, uvc ] );
  18969. } else {
  18970. faces.push( new THREE.Face4( a, b, d, c ) );
  18971. uvs.push( [ uva, uvb, uvd, uvc ] );
  18972. }
  18973. }
  18974. }
  18975. // console.log(this);
  18976. // magic bullet
  18977. // var diff = this.mergeVertices();
  18978. // console.log('removed ', diff, ' vertices by merging');
  18979. this.computeCentroids();
  18980. this.computeFaceNormals();
  18981. this.computeVertexNormals();
  18982. };
  18983. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18984. /**
  18985. * @author qiao / https://github.com/qiao
  18986. * @fileoverview This is a convex hull generator using the incremental method.
  18987. * The complexity is O(n^2) where n is the number of vertices.
  18988. * O(nlogn) algorithms do exist, but they are much more complicated.
  18989. *
  18990. * Benchmark:
  18991. *
  18992. * Platform: CPU: P7350 @2.00GHz Engine: V8
  18993. *
  18994. * Num Vertices Time(ms)
  18995. *
  18996. * 10 1
  18997. * 20 3
  18998. * 30 19
  18999. * 40 48
  19000. * 50 107
  19001. */
  19002. THREE.ConvexGeometry = function( vertices ) {
  19003. THREE.Geometry.call( this );
  19004. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19005. for ( var i = 3; i < vertices.length; i++ ) {
  19006. addPoint( i );
  19007. }
  19008. function addPoint( vertexId ) {
  19009. var vertex = vertices[ vertexId ].clone();
  19010. var mag = vertex.length();
  19011. vertex.x += mag * randomOffset();
  19012. vertex.y += mag * randomOffset();
  19013. vertex.z += mag * randomOffset();
  19014. var hole = [];
  19015. for ( var f = 0; f < faces.length; ) {
  19016. var face = faces[ f ];
  19017. // for each face, if the vertex can see it,
  19018. // then we try to add the face's edges into the hole.
  19019. if ( visible( face, vertex ) ) {
  19020. for ( var e = 0; e < 3; e++ ) {
  19021. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19022. var boundary = true;
  19023. // remove duplicated edges.
  19024. for ( var h = 0; h < hole.length; h++ ) {
  19025. if ( equalEdge( hole[ h ], edge ) ) {
  19026. hole[ h ] = hole[ hole.length - 1 ];
  19027. hole.pop();
  19028. boundary = false;
  19029. break;
  19030. }
  19031. }
  19032. if ( boundary ) {
  19033. hole.push( edge );
  19034. }
  19035. }
  19036. // remove faces[ f ]
  19037. faces[ f ] = faces[ faces.length - 1 ];
  19038. faces.pop();
  19039. } else { // not visible
  19040. f++;
  19041. }
  19042. }
  19043. // construct the new faces formed by the edges of the hole and the vertex
  19044. for ( var h = 0; h < hole.length; h++ ) {
  19045. faces.push( [
  19046. hole[ h ][ 0 ],
  19047. hole[ h ][ 1 ],
  19048. vertexId
  19049. ] );
  19050. }
  19051. }
  19052. /**
  19053. * Whether the face is visible from the vertex
  19054. */
  19055. function visible( face, vertex ) {
  19056. var va = vertices[ face[ 0 ] ];
  19057. var vb = vertices[ face[ 1 ] ];
  19058. var vc = vertices[ face[ 2 ] ];
  19059. var n = normal( va, vb, vc );
  19060. // distance from face to origin
  19061. var dist = n.dot( va );
  19062. return n.dot( vertex ) >= dist;
  19063. }
  19064. /**
  19065. * Face normal
  19066. */
  19067. function normal( va, vb, vc ) {
  19068. var cb = new THREE.Vector3();
  19069. var ab = new THREE.Vector3();
  19070. cb.sub( vc, vb );
  19071. ab.sub( va, vb );
  19072. cb.crossSelf( ab );
  19073. cb.normalize();
  19074. return cb;
  19075. }
  19076. /**
  19077. * Detect whether two edges are equal.
  19078. * Note that when constructing the convex hull, two same edges can only
  19079. * be of the negative direction.
  19080. */
  19081. function equalEdge( ea, eb ) {
  19082. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19083. }
  19084. /**
  19085. * Create a random offset between -1e-6 and 1e-6.
  19086. */
  19087. function randomOffset() {
  19088. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19089. }
  19090. /**
  19091. * XXX: Not sure if this is the correct approach. Need someone to review.
  19092. */
  19093. function vertexUv( vertex ) {
  19094. var mag = vertex.length();
  19095. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19096. }
  19097. // Push vertices into `this.vertices`, skipping those inside the hull
  19098. var id = 0;
  19099. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19100. for ( var i = 0; i < faces.length; i++ ) {
  19101. var face = faces[ i ];
  19102. for ( var j = 0; j < 3; j++ ) {
  19103. if ( newId[ face[ j ] ] === undefined ) {
  19104. newId[ face[ j ] ] = id++;
  19105. this.vertices.push( vertices[ face[ j ] ] );
  19106. }
  19107. face[ j ] = newId[ face[ j ] ];
  19108. }
  19109. }
  19110. // Convert faces into instances of THREE.Face3
  19111. for ( var i = 0; i < faces.length; i++ ) {
  19112. this.faces.push( new THREE.Face3(
  19113. faces[ i ][ 0 ],
  19114. faces[ i ][ 1 ],
  19115. faces[ i ][ 2 ]
  19116. ) );
  19117. }
  19118. // Compute UVs
  19119. for ( var i = 0; i < this.faces.length; i++ ) {
  19120. var face = this.faces[ i ];
  19121. this.faceVertexUvs[ 0 ].push( [
  19122. vertexUv( this.vertices[ face.a ] ),
  19123. vertexUv( this.vertices[ face.b ] ),
  19124. vertexUv( this.vertices[ face.c ])
  19125. ] );
  19126. }
  19127. this.computeCentroids();
  19128. this.computeFaceNormals();
  19129. this.computeVertexNormals();
  19130. };
  19131. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19132. /**
  19133. * @author sroucheray / http://sroucheray.org/
  19134. * @author mrdoob / http://mrdoob.com/
  19135. */
  19136. THREE.AxisHelper = function ( size ) {
  19137. var geometry = new THREE.Geometry();
  19138. geometry.vertices.push(
  19139. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19140. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19141. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19142. );
  19143. geometry.colors.push(
  19144. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19145. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19146. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19147. );
  19148. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19149. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19150. };
  19151. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19152. /**
  19153. * @author WestLangley / http://github.com/WestLangley
  19154. * @author zz85 / https://github.com/zz85
  19155. *
  19156. * Creates an arrow for visualizing directions
  19157. *
  19158. * Parameters:
  19159. * dir - Vector3
  19160. * origin - Vector3
  19161. * length - Number
  19162. * hex - color in hex value
  19163. */
  19164. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19165. THREE.Object3D.call( this );
  19166. if ( hex === undefined ) hex = 0xffff00;
  19167. if ( length === undefined ) length = 20;
  19168. var lineGeometry = new THREE.Geometry();
  19169. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19170. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19171. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19172. this.add( this.line );
  19173. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19174. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19175. this.cone.position.set( 0, 1, 0 );
  19176. this.add( this.cone );
  19177. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19178. this.setDirection( dir );
  19179. this.setLength( length );
  19180. };
  19181. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19182. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19183. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19184. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19185. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19186. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19187. };
  19188. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19189. this.scale.set( length, length, length );
  19190. };
  19191. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19192. this.line.material.color.setHex( hex );
  19193. this.cone.material.color.setHex( hex );
  19194. };
  19195. /**
  19196. * @author alteredq / http://alteredqualia.com/
  19197. *
  19198. * - shows frustum, line of sight and up of the camera
  19199. * - suitable for fast updates
  19200. * - based on frustum visualization in lightgl.js shadowmap example
  19201. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19202. */
  19203. THREE.CameraHelper = function ( camera ) {
  19204. THREE.Line.call( this );
  19205. var scope = this;
  19206. this.geometry = new THREE.Geometry();
  19207. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19208. this.type = THREE.LinePieces;
  19209. this.matrixWorld = camera.matrixWorld;
  19210. this.matrixAutoUpdate = false;
  19211. this.pointMap = {};
  19212. // colors
  19213. var hexFrustum = 0xffaa00;
  19214. var hexCone = 0xff0000;
  19215. var hexUp = 0x00aaff;
  19216. var hexTarget = 0xffffff;
  19217. var hexCross = 0x333333;
  19218. // near
  19219. addLine( "n1", "n2", hexFrustum );
  19220. addLine( "n2", "n4", hexFrustum );
  19221. addLine( "n4", "n3", hexFrustum );
  19222. addLine( "n3", "n1", hexFrustum );
  19223. // far
  19224. addLine( "f1", "f2", hexFrustum );
  19225. addLine( "f2", "f4", hexFrustum );
  19226. addLine( "f4", "f3", hexFrustum );
  19227. addLine( "f3", "f1", hexFrustum );
  19228. // sides
  19229. addLine( "n1", "f1", hexFrustum );
  19230. addLine( "n2", "f2", hexFrustum );
  19231. addLine( "n3", "f3", hexFrustum );
  19232. addLine( "n4", "f4", hexFrustum );
  19233. // cone
  19234. addLine( "p", "n1", hexCone );
  19235. addLine( "p", "n2", hexCone );
  19236. addLine( "p", "n3", hexCone );
  19237. addLine( "p", "n4", hexCone );
  19238. // up
  19239. addLine( "u1", "u2", hexUp );
  19240. addLine( "u2", "u3", hexUp );
  19241. addLine( "u3", "u1", hexUp );
  19242. // target
  19243. addLine( "c", "t", hexTarget );
  19244. addLine( "p", "c", hexCross );
  19245. // cross
  19246. addLine( "cn1", "cn2", hexCross );
  19247. addLine( "cn3", "cn4", hexCross );
  19248. addLine( "cf1", "cf2", hexCross );
  19249. addLine( "cf3", "cf4", hexCross );
  19250. this.camera = camera;
  19251. function addLine( a, b, hex ) {
  19252. addPoint( a, hex );
  19253. addPoint( b, hex );
  19254. }
  19255. function addPoint( id, hex ) {
  19256. scope.geometry.vertices.push( new THREE.Vector3() );
  19257. scope.geometry.colors.push( new THREE.Color( hex ) );
  19258. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19259. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19260. }
  19261. this.update( camera );
  19262. };
  19263. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19264. THREE.CameraHelper.prototype.update = function () {
  19265. var scope = this;
  19266. var w = 1, h = 1;
  19267. // we need just camera projection matrix
  19268. // world matrix must be identity
  19269. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19270. // center / target
  19271. setPoint( "c", 0, 0, -1 );
  19272. setPoint( "t", 0, 0, 1 );
  19273. // near
  19274. setPoint( "n1", -w, -h, -1 );
  19275. setPoint( "n2", w, -h, -1 );
  19276. setPoint( "n3", -w, h, -1 );
  19277. setPoint( "n4", w, h, -1 );
  19278. // far
  19279. setPoint( "f1", -w, -h, 1 );
  19280. setPoint( "f2", w, -h, 1 );
  19281. setPoint( "f3", -w, h, 1 );
  19282. setPoint( "f4", w, h, 1 );
  19283. // up
  19284. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19285. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19286. setPoint( "u3", 0, h * 2, -1 );
  19287. // cross
  19288. setPoint( "cf1", -w, 0, 1 );
  19289. setPoint( "cf2", w, 0, 1 );
  19290. setPoint( "cf3", 0, -h, 1 );
  19291. setPoint( "cf4", 0, h, 1 );
  19292. setPoint( "cn1", -w, 0, -1 );
  19293. setPoint( "cn2", w, 0, -1 );
  19294. setPoint( "cn3", 0, -h, -1 );
  19295. setPoint( "cn4", 0, h, -1 );
  19296. function setPoint( point, x, y, z ) {
  19297. THREE.CameraHelper.__v.set( x, y, z );
  19298. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19299. var points = scope.pointMap[ point ];
  19300. if ( points !== undefined ) {
  19301. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19302. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19303. }
  19304. }
  19305. }
  19306. this.geometry.verticesNeedUpdate = true;
  19307. };
  19308. THREE.CameraHelper.__projector = new THREE.Projector();
  19309. THREE.CameraHelper.__v = new THREE.Vector3();
  19310. THREE.CameraHelper.__c = new THREE.Camera();
  19311. /**
  19312. * @author alteredq / http://alteredqualia.com/
  19313. *
  19314. * - shows directional light color, intensity, position, orientation and target
  19315. */
  19316. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  19317. THREE.Object3D.call( this );
  19318. this.light = light;
  19319. // position
  19320. this.position = light.position;
  19321. // direction
  19322. this.direction = new THREE.Vector3();
  19323. this.direction.sub( light.target.position, light.position );
  19324. // color
  19325. this.color = light.color.clone();
  19326. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19327. this.color.r *= intensity;
  19328. this.color.g *= intensity;
  19329. this.color.b *= intensity;
  19330. var hexColor = this.color.getHex();
  19331. // light helper
  19332. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19333. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19334. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19335. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19336. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19337. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19338. this.lightArrow.cone.material.fog = false;
  19339. this.lightArrow.line.material.fog = false;
  19340. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19341. this.add( this.lightArrow );
  19342. this.add( this.lightSphere );
  19343. this.add( this.lightRays );
  19344. this.lightSphere.properties.isGizmo = true;
  19345. this.lightSphere.properties.gizmoSubject = light;
  19346. this.lightSphere.properties.gizmoRoot = this;
  19347. // light target helper
  19348. this.targetSphere = null;
  19349. if ( light.target.properties.targetInverse ) {
  19350. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19351. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19352. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19353. this.targetSphere.position = light.target.position;
  19354. this.targetSphere.properties.isGizmo = true;
  19355. this.targetSphere.properties.gizmoSubject = light.target;
  19356. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19357. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19358. var lineGeometry = new THREE.Geometry();
  19359. lineGeometry.vertices.push( this.position.clone() );
  19360. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19361. lineGeometry.computeLineDistances();
  19362. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19363. this.targetLine.properties.isGizmo = true;
  19364. }
  19365. //
  19366. this.properties.isGizmo = true;
  19367. }
  19368. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19369. THREE.DirectionalLightHelper.prototype.update = function () {
  19370. // update arrow orientation
  19371. // pointing from light to target
  19372. this.direction.sub( this.light.target.position, this.light.position );
  19373. this.lightArrow.setDirection( this.direction );
  19374. // update arrow, spheres, rays and line colors to light color * light intensity
  19375. this.color.copy( this.light.color );
  19376. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19377. this.color.r *= intensity;
  19378. this.color.g *= intensity;
  19379. this.color.b *= intensity;
  19380. this.lightArrow.setColor( this.color.getHex() );
  19381. this.lightSphere.material.color.copy( this.color );
  19382. this.lightRays.material.color.copy( this.color );
  19383. this.targetSphere.material.color.copy( this.color );
  19384. this.targetLine.material.color.copy( this.color );
  19385. // update target line vertices
  19386. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19387. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19388. this.targetLine.geometry.computeLineDistances();
  19389. this.targetLine.geometry.verticesNeedUpdate = true;
  19390. }
  19391. /**
  19392. * @author alteredq / http://alteredqualia.com/
  19393. *
  19394. * - shows hemisphere light intensity, sky and ground colors and directions
  19395. */
  19396. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  19397. THREE.Object3D.call( this );
  19398. this.light = light;
  19399. // position
  19400. this.position = light.position;
  19401. //
  19402. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19403. // sky color
  19404. this.color = light.color.clone();
  19405. this.color.r *= intensity;
  19406. this.color.g *= intensity;
  19407. this.color.b *= intensity;
  19408. var hexColor = this.color.getHex();
  19409. // ground color
  19410. this.groundColor = light.groundColor.clone();
  19411. this.groundColor.r *= intensity;
  19412. this.groundColor.g *= intensity;
  19413. this.groundColor.b *= intensity;
  19414. var hexColorGround = this.groundColor.getHex();
  19415. // double colored light bulb
  19416. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  19417. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  19418. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19419. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  19420. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  19421. bulbGeometry.faces[ i ].materialIndex = 0;
  19422. }
  19423. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  19424. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  19425. }
  19426. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  19427. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  19428. // arrows for sky and ground light directions
  19429. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  19430. this.lightArrow.rotation.x = Math.PI;
  19431. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  19432. var joint = new THREE.Object3D();
  19433. joint.rotation.x = -Math.PI * 0.5;
  19434. joint.add( this.lightSphere );
  19435. joint.add( this.lightArrow );
  19436. joint.add( this.lightArrowGround );
  19437. this.add( joint );
  19438. //
  19439. this.lightSphere.properties.isGizmo = true;
  19440. this.lightSphere.properties.gizmoSubject = light;
  19441. this.lightSphere.properties.gizmoRoot = this;
  19442. //
  19443. this.properties.isGizmo = true;
  19444. //
  19445. this.target = new THREE.Vector3();
  19446. this.lookAt( this.target );
  19447. }
  19448. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19449. THREE.HemisphereLightHelper.prototype.update = function () {
  19450. // update sphere sky and ground colors to light color * light intensity
  19451. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19452. this.color.copy( this.light.color );
  19453. this.groundColor.copy( this.light.groundColor );
  19454. this.color.r *= intensity;
  19455. this.color.g *= intensity;
  19456. this.color.b *= intensity;
  19457. this.groundColor.r *= intensity;
  19458. this.groundColor.g *= intensity;
  19459. this.groundColor.b *= intensity;
  19460. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  19461. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  19462. this.lightArrow.setColor( this.color.getHex() );
  19463. this.lightArrowGround.setColor( this.groundColor.getHex() );
  19464. this.lookAt( this.target );
  19465. }
  19466. /**
  19467. * @author alteredq / http://alteredqualia.com/
  19468. *
  19469. * - shows point light color, intensity, position and distance
  19470. */
  19471. THREE.PointLightHelper = function ( light, sphereSize ) {
  19472. THREE.Object3D.call( this );
  19473. this.light = light;
  19474. // position
  19475. this.position = light.position;
  19476. // color
  19477. this.color = light.color.clone();
  19478. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19479. this.color.r *= intensity;
  19480. this.color.g *= intensity;
  19481. this.color.b *= intensity;
  19482. var hexColor = this.color.getHex();
  19483. // light helper
  19484. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19485. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19486. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  19487. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19488. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19489. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  19490. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19491. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19492. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  19493. var d = light.distance;
  19494. if ( d === 0.0 ) {
  19495. this.lightDistance.visible = false;
  19496. } else {
  19497. this.lightDistance.scale.set( d, d, d );
  19498. }
  19499. this.add( this.lightSphere );
  19500. this.add( this.lightRays );
  19501. this.add( this.lightDistance );
  19502. //
  19503. this.lightSphere.properties.isGizmo = true;
  19504. this.lightSphere.properties.gizmoSubject = light;
  19505. this.lightSphere.properties.gizmoRoot = this;
  19506. //
  19507. this.properties.isGizmo = true;
  19508. }
  19509. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19510. THREE.PointLightHelper.prototype.update = function () {
  19511. // update sphere and rays colors to light color * light intensity
  19512. this.color.copy( this.light.color );
  19513. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19514. this.color.r *= intensity;
  19515. this.color.g *= intensity;
  19516. this.color.b *= intensity;
  19517. this.lightSphere.material.color.copy( this.color );
  19518. this.lightRays.material.color.copy( this.color );
  19519. this.lightDistance.material.color.copy( this.color );
  19520. //
  19521. var d = this.light.distance;
  19522. if ( d === 0.0 ) {
  19523. this.lightDistance.visible = false;
  19524. } else {
  19525. this.lightDistance.visible = true;
  19526. this.lightDistance.scale.set( d, d, d );
  19527. }
  19528. }
  19529. /**
  19530. * @author alteredq / http://alteredqualia.com/
  19531. *
  19532. * - shows spot light color, intensity, position, orientation, light cone and target
  19533. */
  19534. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  19535. THREE.Object3D.call( this );
  19536. this.light = light;
  19537. // position
  19538. this.position = light.position;
  19539. // direction
  19540. this.direction = new THREE.Vector3();
  19541. this.direction.sub( light.target.position, light.position );
  19542. // color
  19543. this.color = light.color.clone();
  19544. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19545. this.color.r *= intensity;
  19546. this.color.g *= intensity;
  19547. this.color.b *= intensity;
  19548. var hexColor = this.color.getHex();
  19549. // light helper
  19550. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19551. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19552. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  19553. var coneMatrix = new THREE.Matrix4();
  19554. coneMatrix.rotateX( -Math.PI/2 );
  19555. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  19556. coneGeometry.applyMatrix( coneMatrix );
  19557. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19558. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19559. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  19560. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19561. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19562. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  19563. var coneLength = light.distance ? light.distance : 10000;
  19564. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  19565. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19566. this.lightArrow.cone.material.fog = false;
  19567. this.lightArrow.line.material.fog = false;
  19568. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19569. this.gyroscope = new THREE.Gyroscope();
  19570. this.gyroscope.add( this.lightArrow );
  19571. this.gyroscope.add( this.lightSphere );
  19572. this.gyroscope.add( this.lightRays );
  19573. this.add( this.gyroscope );
  19574. this.add( this.lightCone );
  19575. this.lookAt( light.target.position );
  19576. this.lightSphere.properties.isGizmo = true;
  19577. this.lightSphere.properties.gizmoSubject = light;
  19578. this.lightSphere.properties.gizmoRoot = this;
  19579. // light target helper
  19580. this.targetSphere = null;
  19581. if ( light.target.properties.targetInverse ) {
  19582. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19583. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19584. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19585. this.targetSphere.position = light.target.position;
  19586. this.targetSphere.properties.isGizmo = true;
  19587. this.targetSphere.properties.gizmoSubject = light.target;
  19588. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19589. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19590. var lineGeometry = new THREE.Geometry();
  19591. lineGeometry.vertices.push( this.position.clone() );
  19592. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19593. lineGeometry.computeLineDistances();
  19594. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19595. this.targetLine.properties.isGizmo = true;
  19596. }
  19597. //
  19598. this.properties.isGizmo = true;
  19599. }
  19600. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19601. THREE.SpotLightHelper.prototype.update = function () {
  19602. // update arrow orientation
  19603. // pointing from light to target
  19604. this.direction.sub( this.light.target.position, this.light.position );
  19605. this.lightArrow.setDirection( this.direction );
  19606. // update light cone orientation and size
  19607. this.lookAt( this.light.target.position );
  19608. var coneLength = this.light.distance ? this.light.distance : 10000;
  19609. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  19610. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19611. // update arrow, spheres, rays and line colors to light color * light intensity
  19612. this.color.copy( this.light.color );
  19613. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19614. this.color.r *= intensity;
  19615. this.color.g *= intensity;
  19616. this.color.b *= intensity;
  19617. this.lightArrow.setColor( this.color.getHex() );
  19618. this.lightSphere.material.color.copy( this.color );
  19619. this.lightRays.material.color.copy( this.color );
  19620. this.lightCone.material.color.copy( this.color );
  19621. this.targetSphere.material.color.copy( this.color );
  19622. this.targetLine.material.color.copy( this.color );
  19623. // update target line vertices
  19624. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19625. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19626. this.targetLine.geometry.computeLineDistances();
  19627. this.targetLine.geometry.verticesNeedUpdate = true;
  19628. }
  19629. /*
  19630. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19631. *
  19632. * Subdivision Geometry Modifier
  19633. * using Catmull-Clark Subdivision Surfaces
  19634. * for creating smooth geometry meshes
  19635. *
  19636. * Note: a modifier modifies vertices and faces of geometry,
  19637. * so use geometry.clone() if original geometry needs to be retained
  19638. *
  19639. * Readings:
  19640. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19641. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19642. * http://xrt.wikidot.com/blog:31
  19643. * "Subdivision Surfaces in Character Animation"
  19644. *
  19645. * (on boundary edges)
  19646. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19647. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  19648. *
  19649. * Supports:
  19650. * Closed and Open geometries.
  19651. *
  19652. * TODO:
  19653. * crease vertex and "semi-sharp" features
  19654. * selective subdivision
  19655. */
  19656. THREE.SubdivisionModifier = function( subdivisions ) {
  19657. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19658. // Settings
  19659. this.useOldVertexColors = false;
  19660. this.supportUVs = true;
  19661. this.debug = false;
  19662. };
  19663. // Applies the "modify" pattern
  19664. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19665. var repeats = this.subdivisions;
  19666. while ( repeats-- > 0 ) {
  19667. this.smooth( geometry );
  19668. }
  19669. };
  19670. /// REFACTORING THIS OUT
  19671. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  19672. return Math.min( a, b ) + "_" + Math.max( a, b );
  19673. };
  19674. // Returns a hashmap - of { edge_key: face_index }
  19675. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  19676. var i, il, v1, v2, j, k,
  19677. face, faceIndices, faceIndex,
  19678. edge,
  19679. hash,
  19680. edgeFaceMap = {};
  19681. var orderedKey = THREE.GeometryUtils.orderedKey;
  19682. function mapEdgeHash( hash, i ) {
  19683. if ( edgeFaceMap[ hash ] === undefined ) {
  19684. edgeFaceMap[ hash ] = [];
  19685. }
  19686. edgeFaceMap[ hash ].push( i );
  19687. }
  19688. // construct vertex -> face map
  19689. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19690. face = geometry.faces[ i ];
  19691. if ( face instanceof THREE.Face3 ) {
  19692. hash = orderedKey( face.a, face.b );
  19693. mapEdgeHash( hash, i );
  19694. hash = orderedKey( face.b, face.c );
  19695. mapEdgeHash( hash, i );
  19696. hash = orderedKey( face.c, face.a );
  19697. mapEdgeHash( hash, i );
  19698. } else if ( face instanceof THREE.Face4 ) {
  19699. hash = orderedKey( face.a, face.b );
  19700. mapEdgeHash( hash, i );
  19701. hash = orderedKey( face.b, face.c );
  19702. mapEdgeHash( hash, i );
  19703. hash = orderedKey( face.c, face.d );
  19704. mapEdgeHash( hash, i );
  19705. hash = orderedKey( face.d, face.a );
  19706. mapEdgeHash( hash, i );
  19707. }
  19708. }
  19709. // extract faces
  19710. // var edges = [];
  19711. //
  19712. // var numOfEdges = 0;
  19713. // for (i in edgeFaceMap) {
  19714. // numOfEdges++;
  19715. //
  19716. // edge = edgeFaceMap[i];
  19717. // edges.push(edge);
  19718. //
  19719. // }
  19720. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19721. return edgeFaceMap;
  19722. }
  19723. /////////////////////////////
  19724. // Performs an iteration of Catmull-Clark Subdivision
  19725. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19726. //debug( 'running smooth' );
  19727. // New set of vertices, faces and uvs
  19728. var newVertices = [], newFaces = [], newUVs = [];
  19729. function v( x, y, z ) {
  19730. newVertices.push( new THREE.Vector3( x, y, z ) );
  19731. }
  19732. var scope = this;
  19733. var orderedKey = THREE.GeometryUtils.orderedKey;
  19734. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  19735. function assert() {
  19736. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  19737. }
  19738. function debug() {
  19739. if (scope.debug) console.log.apply(console, arguments);
  19740. }
  19741. function warn() {
  19742. if (console)
  19743. console.log.apply(console, arguments);
  19744. }
  19745. function f4( a, b, c, d, oldFace, orders, facei ) {
  19746. // TODO move vertex selection over here!
  19747. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19748. if (scope.useOldVertexColors) {
  19749. newFace.vertexColors = [];
  19750. var color, tmpColor, order;
  19751. for (var i=0;i<4;i++) {
  19752. order = orders[i];
  19753. color = new THREE.Color(),
  19754. color.setRGB(0,0,0);
  19755. for (var j=0, jl=0; j<order.length;j++) {
  19756. tmpColor = oldFace.vertexColors[order[j]-1];
  19757. color.r += tmpColor.r;
  19758. color.g += tmpColor.g;
  19759. color.b += tmpColor.b;
  19760. }
  19761. color.r /= order.length;
  19762. color.g /= order.length;
  19763. color.b /= order.length;
  19764. newFace.vertexColors[i] = color;
  19765. }
  19766. }
  19767. newFaces.push( newFace );
  19768. if (scope.supportUVs) {
  19769. var aUv = [
  19770. getUV(a, ''),
  19771. getUV(b, facei),
  19772. getUV(c, facei),
  19773. getUV(d, facei)
  19774. ];
  19775. if (!aUv[0]) debug('a :( ', a+':'+facei);
  19776. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  19777. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  19778. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  19779. else
  19780. newUVs.push( aUv );
  19781. }
  19782. }
  19783. var originalPoints = oldGeometry.vertices;
  19784. var originalFaces = oldGeometry.faces;
  19785. var originalVerticesLength = originalPoints.length;
  19786. var newPoints = originalPoints.concat(); // New set of vertices to work on
  19787. var facePoints = [], // these are new points on exisiting faces
  19788. edgePoints = {}; // these are new points on exisiting edges
  19789. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  19790. // TODO: handle this correctly.
  19791. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  19792. function debugCoreStuff() {
  19793. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  19794. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  19795. }
  19796. function getUV(vertexNo, oldFaceNo) {
  19797. var j,jl;
  19798. var key = vertexNo+':'+oldFaceNo;
  19799. var theUV = uvForVertices[key];
  19800. if (!theUV) {
  19801. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  19802. debug('face pt');
  19803. } else {
  19804. debug('edge pt');
  19805. }
  19806. warn('warning, UV not found for', key);
  19807. return null;
  19808. }
  19809. return theUV;
  19810. // Original faces -> Vertex Nos.
  19811. // new Facepoint -> Vertex Nos.
  19812. // edge Points
  19813. }
  19814. function addUV(vertexNo, oldFaceNo, value) {
  19815. var key = vertexNo+':'+oldFaceNo;
  19816. if (!(key in uvForVertices)) {
  19817. uvForVertices[key] = value;
  19818. } else {
  19819. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  19820. }
  19821. }
  19822. // Step 1
  19823. // For each face, add a face point
  19824. // Set each face point to be the centroid of all original points for the respective face.
  19825. // debug(oldGeometry);
  19826. var i, il, j, jl, face;
  19827. // For Uvs
  19828. var uvs = oldGeometry.faceVertexUvs[0];
  19829. var abcd = 'abcd', vertice;
  19830. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  19831. if (scope.supportUVs)
  19832. for (i=0, il = uvs.length; i<il; i++ ) {
  19833. for (j=0,jl=uvs[i].length;j<jl;j++) {
  19834. vertice = originalFaces[i][abcd.charAt(j)];
  19835. addUV(vertice, i, uvs[i][j]);
  19836. }
  19837. }
  19838. if (uvs.length == 0) scope.supportUVs = false;
  19839. // Additional UVs check, if we index original
  19840. var uvCount = 0;
  19841. for (var u in uvForVertices) {
  19842. uvCount++;
  19843. }
  19844. if (!uvCount) {
  19845. scope.supportUVs = false;
  19846. debug('no uvs');
  19847. }
  19848. var avgUv ;
  19849. for (i=0, il = originalFaces.length; i<il ;i++) {
  19850. face = originalFaces[ i ];
  19851. facePoints.push( face.centroid );
  19852. newPoints.push( face.centroid );
  19853. if (!scope.supportUVs) continue;
  19854. // Prepare subdivided uv
  19855. avgUv = new THREE.UV();
  19856. if ( face instanceof THREE.Face3 ) {
  19857. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  19858. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  19859. avgUv.u /= 3;
  19860. avgUv.v /= 3;
  19861. } else if ( face instanceof THREE.Face4 ) {
  19862. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  19863. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  19864. avgUv.u /= 4;
  19865. avgUv.v /= 4;
  19866. }
  19867. addUV(originalVerticesLength + i, '', avgUv);
  19868. }
  19869. // Step 2
  19870. // For each edge, add an edge point.
  19871. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  19872. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  19873. var edge, faceIndexA, faceIndexB, avg;
  19874. // debug('edgeFaceMap', edgeFaceMap);
  19875. var edgeCount = 0;
  19876. var edgeVertex, edgeVertexA, edgeVertexB;
  19877. ////
  19878. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  19879. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  19880. function addVertexEdgeMap(vertex, edge) {
  19881. if (vertexEdgeMap[vertex]===undefined) {
  19882. vertexEdgeMap[vertex] = [];
  19883. }
  19884. vertexEdgeMap[vertex].push(edge);
  19885. }
  19886. function addVertexFaceMap(vertex, face, edge) {
  19887. if (vertexFaceMap[vertex]===undefined) {
  19888. vertexFaceMap[vertex] = {};
  19889. }
  19890. vertexFaceMap[vertex][face] = edge;
  19891. // vertexFaceMap[vertex][face] = null;
  19892. }
  19893. // Prepares vertexEdgeMap and vertexFaceMap
  19894. for (i in edgeFaceMap) { // This is for every edge
  19895. edge = edgeFaceMap[i];
  19896. edgeVertex = i.split('_');
  19897. edgeVertexA = edgeVertex[0];
  19898. edgeVertexB = edgeVertex[1];
  19899. // Maps an edgeVertex to connecting edges
  19900. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  19901. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  19902. for (j=0,jl=edge.length;j<jl;j++) {
  19903. face = edge[j];
  19904. addVertexFaceMap(edgeVertexA, face, i);
  19905. addVertexFaceMap(edgeVertexB, face, i);
  19906. }
  19907. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  19908. // this thing is fishy right now.
  19909. if (edge.length < 2) {
  19910. // edge is "sharp";
  19911. sharpEdges[i] = true;
  19912. sharpVertices[edgeVertexA] = true;
  19913. sharpVertices[edgeVertexB] = true;
  19914. }
  19915. }
  19916. for (i in edgeFaceMap) {
  19917. edge = edgeFaceMap[i];
  19918. faceIndexA = edge[0]; // face index a
  19919. faceIndexB = edge[1]; // face index b
  19920. edgeVertex = i.split('_');
  19921. edgeVertexA = edgeVertex[0];
  19922. edgeVertexB = edgeVertex[1];
  19923. avg = new THREE.Vector3();
  19924. //debug(i, faceIndexB,facePoints[faceIndexB]);
  19925. assert(edge.length > 0, 'an edge without faces?!');
  19926. if (edge.length==1) {
  19927. avg.addSelf(originalPoints[edgeVertexA]);
  19928. avg.addSelf(originalPoints[edgeVertexB]);
  19929. avg.multiplyScalar(0.5);
  19930. sharpVertices[newPoints.length] = true;
  19931. } else {
  19932. avg.addSelf(facePoints[faceIndexA]);
  19933. avg.addSelf(facePoints[faceIndexB]);
  19934. avg.addSelf(originalPoints[edgeVertexA]);
  19935. avg.addSelf(originalPoints[edgeVertexB]);
  19936. avg.multiplyScalar(0.25);
  19937. }
  19938. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  19939. newPoints.push( avg );
  19940. edgeCount ++;
  19941. if (!scope.supportUVs) {
  19942. continue;
  19943. }
  19944. // Prepare subdivided uv
  19945. avgUv = new THREE.UV();
  19946. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  19947. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  19948. avgUv.u /= 2;
  19949. avgUv.v /= 2;
  19950. addUV(edgePoints[i], faceIndexA, avgUv);
  19951. if (edge.length>=2) {
  19952. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  19953. avgUv = new THREE.UV();
  19954. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  19955. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  19956. avgUv.u /= 2;
  19957. avgUv.v /= 2;
  19958. addUV(edgePoints[i], faceIndexB, avgUv);
  19959. }
  19960. }
  19961. debug('-- Step 2 done');
  19962. // Step 3
  19963. // For each face point, add an edge for every edge of the face,
  19964. // connecting the face point to each edge point for the face.
  19965. var facePt, currentVerticeIndex;
  19966. var hashAB, hashBC, hashCD, hashDA, hashCA;
  19967. var abc123 = ['123', '12', '2', '23'];
  19968. var bca123 = ['123', '23', '3', '31'];
  19969. var cab123 = ['123', '31', '1', '12'];
  19970. var abc1234 = ['1234', '12', '2', '23'];
  19971. var bcd1234 = ['1234', '23', '3', '34'];
  19972. var cda1234 = ['1234', '34', '4', '41'];
  19973. var dab1234 = ['1234', '41', '1', '12'];
  19974. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  19975. facePt = facePoints[i];
  19976. face = originalFaces[i];
  19977. currentVerticeIndex = originalVerticesLength+ i;
  19978. if ( face instanceof THREE.Face3 ) {
  19979. // create 3 face4s
  19980. hashAB = orderedKey( face.a, face.b );
  19981. hashBC = orderedKey( face.b, face.c );
  19982. hashCA = orderedKey( face.c, face.a );
  19983. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  19984. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  19985. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  19986. } else if ( face instanceof THREE.Face4 ) {
  19987. // create 4 face4s
  19988. hashAB = orderedKey( face.a, face.b );
  19989. hashBC = orderedKey( face.b, face.c );
  19990. hashCD = orderedKey( face.c, face.d );
  19991. hashDA = orderedKey( face.d, face.a );
  19992. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  19993. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  19994. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  19995. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  19996. } else {
  19997. debug('face should be a face!', face);
  19998. }
  19999. }
  20000. newVertices = newPoints;
  20001. // Step 4
  20002. // For each original point P,
  20003. // take the average F of all n face points for faces touching P,
  20004. // and take the average R of all n edge midpoints for edges touching P,
  20005. // where each edge midpoint is the average of its two endpoint vertices.
  20006. // Move each original point to the point
  20007. var F = new THREE.Vector3();
  20008. var R = new THREE.Vector3();
  20009. var n;
  20010. for (i=0, il = originalPoints.length; i<il; i++) {
  20011. // (F + 2R + (n-3)P) / n
  20012. if (vertexEdgeMap[i]===undefined) continue;
  20013. F.set(0,0,0);
  20014. R.set(0,0,0);
  20015. var newPos = new THREE.Vector3(0,0,0);
  20016. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  20017. for (j in vertexFaceMap[i]) {
  20018. F.addSelf(facePoints[j]);
  20019. f++;
  20020. }
  20021. var sharpEdgeCount = 0;
  20022. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  20023. // Are we on the border?
  20024. var boundary_case = f != n;
  20025. // if (boundary_case) {
  20026. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  20027. // }
  20028. for (j=0;j<n;j++) {
  20029. if (
  20030. sharpEdges[
  20031. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20032. ]) {
  20033. sharpEdgeCount++;
  20034. }
  20035. }
  20036. // if ( sharpEdgeCount==2 ) {
  20037. // continue;
  20038. // // Do not move vertex if there's 2 connecting sharp edges.
  20039. // }
  20040. /*
  20041. if (sharpEdgeCount>2) {
  20042. // TODO
  20043. }
  20044. */
  20045. F.divideScalar(f);
  20046. var boundary_edges = 0;
  20047. if (boundary_case) {
  20048. var bb_edge;
  20049. for (j=0; j<n;j++) {
  20050. edge = vertexEdgeMap[i][j];
  20051. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  20052. if (bb_edge) {
  20053. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20054. R.addSelf(midPt);
  20055. boundary_edges++;
  20056. }
  20057. }
  20058. R.divideScalar(4);
  20059. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  20060. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  20061. } else {
  20062. for (j=0; j<n;j++) {
  20063. edge = vertexEdgeMap[i][j];
  20064. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20065. R.addSelf(midPt);
  20066. }
  20067. R.divideScalar(n);
  20068. }
  20069. // Sum the formula
  20070. newPos.addSelf(originalPoints[i]);
  20071. if (boundary_case) {
  20072. newPos.divideScalar(2);
  20073. newPos.addSelf(R);
  20074. } else {
  20075. newPos.multiplyScalar(n - 3);
  20076. newPos.addSelf(F);
  20077. newPos.addSelf(R.multiplyScalar(2));
  20078. newPos.divideScalar(n);
  20079. }
  20080. newVertices[i] = newPos;
  20081. }
  20082. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20083. newGeometry.vertices = newVertices;
  20084. newGeometry.faces = newFaces;
  20085. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20086. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20087. newGeometry.computeCentroids();
  20088. newGeometry.computeFaceNormals();
  20089. newGeometry.computeVertexNormals();
  20090. };
  20091. /**
  20092. * @author alteredq / http://alteredqualia.com/
  20093. */
  20094. THREE.ImmediateRenderObject = function ( ) {
  20095. THREE.Object3D.call( this );
  20096. this.render = function ( renderCallback ) { };
  20097. };
  20098. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20099. /**
  20100. * @author mikael emtinger / http://gomo.se/
  20101. * @author alteredq / http://alteredqualia.com/
  20102. */
  20103. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20104. THREE.Object3D.call( this );
  20105. this.lensFlares = [];
  20106. this.positionScreen = new THREE.Vector3();
  20107. this.customUpdateCallback = undefined;
  20108. if( texture !== undefined ) {
  20109. this.add( texture, size, distance, blending, color );
  20110. }
  20111. };
  20112. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20113. /*
  20114. * Add: adds another flare
  20115. */
  20116. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20117. if( size === undefined ) size = -1;
  20118. if( distance === undefined ) distance = 0;
  20119. if( opacity === undefined ) opacity = 1;
  20120. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20121. if( blending === undefined ) blending = THREE.NormalBlending;
  20122. distance = Math.min( distance, Math.max( 0, distance ) );
  20123. this.lensFlares.push( { texture: texture, // THREE.Texture
  20124. size: size, // size in pixels (-1 = use texture.width)
  20125. distance: distance, // distance (0-1) from light source (0=at light source)
  20126. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20127. scale: 1, // scale
  20128. rotation: 1, // rotation
  20129. opacity: opacity, // opacity
  20130. color: color, // color
  20131. blending: blending } ); // blending
  20132. };
  20133. /*
  20134. * Update lens flares update positions on all flares based on the screen position
  20135. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20136. */
  20137. THREE.LensFlare.prototype.updateLensFlares = function () {
  20138. var f, fl = this.lensFlares.length;
  20139. var flare;
  20140. var vecX = -this.positionScreen.x * 2;
  20141. var vecY = -this.positionScreen.y * 2;
  20142. for( f = 0; f < fl; f ++ ) {
  20143. flare = this.lensFlares[ f ];
  20144. flare.x = this.positionScreen.x + vecX * flare.distance;
  20145. flare.y = this.positionScreen.y + vecY * flare.distance;
  20146. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20147. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20148. }
  20149. };
  20150. /**
  20151. * @author alteredq / http://alteredqualia.com/
  20152. */
  20153. THREE.MorphBlendMesh = function( geometry, material ) {
  20154. THREE.Mesh.call( this, geometry, material );
  20155. this.animationsMap = {};
  20156. this.animationsList = [];
  20157. // prepare default animation
  20158. // (all frames played together in 1 second)
  20159. var numFrames = this.geometry.morphTargets.length;
  20160. var name = "__default";
  20161. var startFrame = 0;
  20162. var endFrame = numFrames - 1;
  20163. var fps = numFrames / 1;
  20164. this.createAnimation( name, startFrame, endFrame, fps );
  20165. this.setAnimationWeight( name, 1 );
  20166. };
  20167. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20168. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20169. var animation = {
  20170. startFrame: start,
  20171. endFrame: end,
  20172. length: end - start + 1,
  20173. fps: fps,
  20174. duration: ( end - start ) / fps,
  20175. lastFrame: 0,
  20176. currentFrame: 0,
  20177. active: false,
  20178. time: 0,
  20179. direction: 1,
  20180. weight: 1,
  20181. directionBackwards: false,
  20182. mirroredLoop: false
  20183. };
  20184. this.animationsMap[ name ] = animation;
  20185. this.animationsList.push( animation );
  20186. };
  20187. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20188. var pattern = /([a-z]+)(\d+)/;
  20189. var firstAnimation, frameRanges = {};
  20190. var geometry = this.geometry;
  20191. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20192. var morph = geometry.morphTargets[ i ];
  20193. var chunks = morph.name.match( pattern );
  20194. if ( chunks && chunks.length > 1 ) {
  20195. var name = chunks[ 1 ];
  20196. var num = chunks[ 2 ];
  20197. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20198. var range = frameRanges[ name ];
  20199. if ( i < range.start ) range.start = i;
  20200. if ( i > range.end ) range.end = i;
  20201. if ( ! firstAnimation ) firstAnimation = name;
  20202. }
  20203. }
  20204. for ( var name in frameRanges ) {
  20205. var range = frameRanges[ name ];
  20206. this.createAnimation( name, range.start, range.end, fps );
  20207. }
  20208. this.firstAnimation = firstAnimation;
  20209. };
  20210. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20211. var animation = this.animationsMap[ name ];
  20212. if ( animation ) {
  20213. animation.direction = 1;
  20214. animation.directionBackwards = false;
  20215. }
  20216. };
  20217. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20218. var animation = this.animationsMap[ name ];
  20219. if ( animation ) {
  20220. animation.direction = -1;
  20221. animation.directionBackwards = true;
  20222. }
  20223. };
  20224. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20225. var animation = this.animationsMap[ name ];
  20226. if ( animation ) {
  20227. animation.fps = fps;
  20228. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20229. }
  20230. };
  20231. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20232. var animation = this.animationsMap[ name ];
  20233. if ( animation ) {
  20234. animation.duration = duration;
  20235. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20236. }
  20237. };
  20238. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20239. var animation = this.animationsMap[ name ];
  20240. if ( animation ) {
  20241. animation.weight = weight;
  20242. }
  20243. };
  20244. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20245. var animation = this.animationsMap[ name ];
  20246. if ( animation ) {
  20247. animation.time = time;
  20248. }
  20249. };
  20250. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20251. var time = 0;
  20252. var animation = this.animationsMap[ name ];
  20253. if ( animation ) {
  20254. time = animation.time;
  20255. }
  20256. return time;
  20257. };
  20258. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20259. var duration = -1;
  20260. var animation = this.animationsMap[ name ];
  20261. if ( animation ) {
  20262. duration = animation.duration;
  20263. }
  20264. return duration;
  20265. };
  20266. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20267. var animation = this.animationsMap[ name ];
  20268. if ( animation ) {
  20269. animation.time = 0;
  20270. animation.active = true;
  20271. } else {
  20272. console.warn( "animation[" + name + "] undefined" );
  20273. }
  20274. };
  20275. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20276. var animation = this.animationsMap[ name ];
  20277. if ( animation ) {
  20278. animation.active = false;
  20279. }
  20280. };
  20281. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20282. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20283. var animation = this.animationsList[ i ];
  20284. if ( ! animation.active ) continue;
  20285. var frameTime = animation.duration / animation.length;
  20286. animation.time += animation.direction * delta;
  20287. if ( animation.mirroredLoop ) {
  20288. if ( animation.time > animation.duration || animation.time < 0 ) {
  20289. animation.direction *= -1;
  20290. if ( animation.time > animation.duration ) {
  20291. animation.time = animation.duration;
  20292. animation.directionBackwards = true;
  20293. }
  20294. if ( animation.time < 0 ) {
  20295. animation.time = 0;
  20296. animation.directionBackwards = false;
  20297. }
  20298. }
  20299. } else {
  20300. animation.time = animation.time % animation.duration;
  20301. if ( animation.time < 0 ) animation.time += animation.duration;
  20302. }
  20303. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20304. var weight = animation.weight;
  20305. if ( keyframe !== animation.currentFrame ) {
  20306. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20307. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20308. this.morphTargetInfluences[ keyframe ] = 0;
  20309. animation.lastFrame = animation.currentFrame;
  20310. animation.currentFrame = keyframe;
  20311. }
  20312. var mix = ( animation.time % frameTime ) / frameTime;
  20313. if ( animation.directionBackwards ) mix = 1 - mix;
  20314. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20315. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20316. }
  20317. };
  20318. /**
  20319. * @author mikael emtinger / http://gomo.se/
  20320. * @author alteredq / http://alteredqualia.com/
  20321. */
  20322. THREE.LensFlarePlugin = function ( ) {
  20323. var _gl, _renderer, _lensFlare = {};
  20324. this.init = function ( renderer ) {
  20325. _gl = renderer.context;
  20326. _renderer = renderer;
  20327. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20328. _lensFlare.faces = new Uint16Array( 6 );
  20329. var i = 0;
  20330. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20331. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20332. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20333. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20334. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20335. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20336. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20337. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20338. i = 0;
  20339. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20340. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20341. // buffers
  20342. _lensFlare.vertexBuffer = _gl.createBuffer();
  20343. _lensFlare.elementBuffer = _gl.createBuffer();
  20344. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20345. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20346. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20347. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20348. // textures
  20349. _lensFlare.tempTexture = _gl.createTexture();
  20350. _lensFlare.occlusionTexture = _gl.createTexture();
  20351. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20352. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20353. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20354. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20355. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20356. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20357. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20358. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20359. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20360. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20361. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20362. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20363. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20364. _lensFlare.hasVertexTexture = false;
  20365. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20366. } else {
  20367. _lensFlare.hasVertexTexture = true;
  20368. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20369. }
  20370. _lensFlare.attributes = {};
  20371. _lensFlare.uniforms = {};
  20372. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20373. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20374. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20375. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20376. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20377. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20378. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20379. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20380. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20381. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20382. _lensFlare.attributesEnabled = false;
  20383. };
  20384. /*
  20385. * Render lens flares
  20386. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20387. * reads these back and calculates occlusion.
  20388. * Then _lensFlare.update_lensFlares() is called to re-position and
  20389. * update transparency of flares. Then they are rendered.
  20390. *
  20391. */
  20392. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20393. var flares = scene.__webglFlares,
  20394. nFlares = flares.length;
  20395. if ( ! nFlares ) return;
  20396. var tempPosition = new THREE.Vector3();
  20397. var invAspect = viewportHeight / viewportWidth,
  20398. halfViewportWidth = viewportWidth * 0.5,
  20399. halfViewportHeight = viewportHeight * 0.5;
  20400. var size = 16 / viewportHeight,
  20401. scale = new THREE.Vector2( size * invAspect, size );
  20402. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20403. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20404. var uniforms = _lensFlare.uniforms,
  20405. attributes = _lensFlare.attributes;
  20406. // set _lensFlare program and reset blending
  20407. _gl.useProgram( _lensFlare.program );
  20408. if ( ! _lensFlare.attributesEnabled ) {
  20409. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20410. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20411. _lensFlare.attributesEnabled = true;
  20412. }
  20413. // loop through all lens flares to update their occlusion and positions
  20414. // setup gl and common used attribs/unforms
  20415. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20416. _gl.uniform1i( uniforms.map, 1 );
  20417. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20418. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20419. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20420. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20421. _gl.disable( _gl.CULL_FACE );
  20422. _gl.depthMask( false );
  20423. var i, j, jl, flare, sprite;
  20424. for ( i = 0; i < nFlares; i ++ ) {
  20425. size = 16 / viewportHeight;
  20426. scale.set( size * invAspect, size );
  20427. // calc object screen position
  20428. flare = flares[ i ];
  20429. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20430. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20431. camera.projectionMatrix.multiplyVector3( tempPosition );
  20432. // setup arrays for gl programs
  20433. screenPosition.copy( tempPosition )
  20434. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20435. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20436. // screen cull
  20437. if ( _lensFlare.hasVertexTexture || (
  20438. screenPositionPixels.x > 0 &&
  20439. screenPositionPixels.x < viewportWidth &&
  20440. screenPositionPixels.y > 0 &&
  20441. screenPositionPixels.y < viewportHeight ) ) {
  20442. // save current RGB to temp texture
  20443. _gl.activeTexture( _gl.TEXTURE1 );
  20444. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20445. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20446. // render pink quad
  20447. _gl.uniform1i( uniforms.renderType, 0 );
  20448. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20449. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20450. _gl.disable( _gl.BLEND );
  20451. _gl.enable( _gl.DEPTH_TEST );
  20452. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20453. // copy result to occlusionMap
  20454. _gl.activeTexture( _gl.TEXTURE0 );
  20455. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20456. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20457. // restore graphics
  20458. _gl.uniform1i( uniforms.renderType, 1 );
  20459. _gl.disable( _gl.DEPTH_TEST );
  20460. _gl.activeTexture( _gl.TEXTURE1 );
  20461. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20462. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20463. // update object positions
  20464. flare.positionScreen.copy( screenPosition )
  20465. if ( flare.customUpdateCallback ) {
  20466. flare.customUpdateCallback( flare );
  20467. } else {
  20468. flare.updateLensFlares();
  20469. }
  20470. // render flares
  20471. _gl.uniform1i( uniforms.renderType, 2 );
  20472. _gl.enable( _gl.BLEND );
  20473. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20474. sprite = flare.lensFlares[ j ];
  20475. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20476. screenPosition.x = sprite.x;
  20477. screenPosition.y = sprite.y;
  20478. screenPosition.z = sprite.z;
  20479. size = sprite.size * sprite.scale / viewportHeight;
  20480. scale.x = size * invAspect;
  20481. scale.y = size;
  20482. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20483. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20484. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20485. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20486. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20487. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20488. _renderer.setTexture( sprite.texture, 1 );
  20489. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20490. }
  20491. }
  20492. }
  20493. }
  20494. // restore gl
  20495. _gl.enable( _gl.CULL_FACE );
  20496. _gl.enable( _gl.DEPTH_TEST );
  20497. _gl.depthMask( true );
  20498. };
  20499. function createProgram ( shader ) {
  20500. var program = _gl.createProgram();
  20501. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20502. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20503. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20504. _gl.shaderSource( vertexShader, shader.vertexShader );
  20505. _gl.compileShader( fragmentShader );
  20506. _gl.compileShader( vertexShader );
  20507. _gl.attachShader( program, fragmentShader );
  20508. _gl.attachShader( program, vertexShader );
  20509. _gl.linkProgram( program );
  20510. return program;
  20511. };
  20512. };/**
  20513. * @author alteredq / http://alteredqualia.com/
  20514. */
  20515. THREE.ShadowMapPlugin = function ( ) {
  20516. var _gl,
  20517. _renderer,
  20518. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20519. _frustum = new THREE.Frustum(),
  20520. _projScreenMatrix = new THREE.Matrix4(),
  20521. _min = new THREE.Vector3(),
  20522. _max = new THREE.Vector3();
  20523. this.init = function ( renderer ) {
  20524. _gl = renderer.context;
  20525. _renderer = renderer;
  20526. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20527. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20528. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20529. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20530. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20531. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20532. _depthMaterial._shadowPass = true;
  20533. _depthMaterialMorph._shadowPass = true;
  20534. _depthMaterialSkin._shadowPass = true;
  20535. _depthMaterialMorphSkin._shadowPass = true;
  20536. };
  20537. this.render = function ( scene, camera ) {
  20538. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20539. this.update( scene, camera );
  20540. };
  20541. this.update = function ( scene, camera ) {
  20542. var i, il, j, jl, n,
  20543. shadowMap, shadowMatrix, shadowCamera,
  20544. program, buffer, material,
  20545. webglObject, object, light,
  20546. renderList,
  20547. lights = [],
  20548. k = 0,
  20549. fog = null;
  20550. // set GL state for depth map
  20551. _gl.clearColor( 1, 1, 1, 1 );
  20552. _gl.disable( _gl.BLEND );
  20553. _gl.enable( _gl.CULL_FACE );
  20554. _gl.frontFace( _gl.CCW );
  20555. if ( _renderer.shadowMapCullFrontFaces ) {
  20556. _gl.cullFace( _gl.FRONT );
  20557. } else {
  20558. _gl.cullFace( _gl.BACK );
  20559. }
  20560. _renderer.setDepthTest( true );
  20561. // preprocess lights
  20562. // - skip lights that are not casting shadows
  20563. // - create virtual lights for cascaded shadow maps
  20564. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20565. light = scene.__lights[ i ];
  20566. if ( ! light.castShadow ) continue;
  20567. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20568. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20569. var virtualLight;
  20570. if ( ! light.shadowCascadeArray[ n ] ) {
  20571. virtualLight = createVirtualLight( light, n );
  20572. virtualLight.originalCamera = camera;
  20573. var gyro = new THREE.Gyroscope();
  20574. gyro.position = light.shadowCascadeOffset;
  20575. gyro.add( virtualLight );
  20576. gyro.add( virtualLight.target );
  20577. camera.add( gyro );
  20578. light.shadowCascadeArray[ n ] = virtualLight;
  20579. console.log( "Created virtualLight", virtualLight );
  20580. } else {
  20581. virtualLight = light.shadowCascadeArray[ n ];
  20582. }
  20583. updateVirtualLight( light, n );
  20584. lights[ k ] = virtualLight;
  20585. k ++;
  20586. }
  20587. } else {
  20588. lights[ k ] = light;
  20589. k ++;
  20590. }
  20591. }
  20592. // render depth map
  20593. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20594. light = lights[ i ];
  20595. if ( ! light.shadowMap ) {
  20596. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20597. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20598. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20599. light.shadowMatrix = new THREE.Matrix4();
  20600. }
  20601. if ( ! light.shadowCamera ) {
  20602. if ( light instanceof THREE.SpotLight ) {
  20603. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20604. } else if ( light instanceof THREE.DirectionalLight ) {
  20605. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20606. } else {
  20607. console.error( "Unsupported light type for shadow" );
  20608. continue;
  20609. }
  20610. scene.add( light.shadowCamera );
  20611. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20612. }
  20613. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20614. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20615. light.shadowCamera.add( light.cameraHelper );
  20616. }
  20617. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20618. updateShadowCamera( camera, light );
  20619. }
  20620. shadowMap = light.shadowMap;
  20621. shadowMatrix = light.shadowMatrix;
  20622. shadowCamera = light.shadowCamera;
  20623. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20624. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20625. shadowCamera.updateMatrixWorld();
  20626. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20627. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20628. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20629. // compute shadow matrix
  20630. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20631. 0.0, 0.5, 0.0, 0.5,
  20632. 0.0, 0.0, 0.5, 0.5,
  20633. 0.0, 0.0, 0.0, 1.0 );
  20634. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20635. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20636. // update camera matrices and frustum
  20637. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  20638. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  20639. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  20640. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  20641. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20642. _frustum.setFromMatrix( _projScreenMatrix );
  20643. // render shadow map
  20644. _renderer.setRenderTarget( shadowMap );
  20645. _renderer.clear();
  20646. // set object matrices & frustum culling
  20647. renderList = scene.__webglObjects;
  20648. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20649. webglObject = renderList[ j ];
  20650. object = webglObject.object;
  20651. webglObject.render = false;
  20652. if ( object.visible && object.castShadow ) {
  20653. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20654. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20655. webglObject.render = true;
  20656. }
  20657. }
  20658. }
  20659. // render regular objects
  20660. var objectMaterial, useMorphing, useSkinning;
  20661. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20662. webglObject = renderList[ j ];
  20663. if ( webglObject.render ) {
  20664. object = webglObject.object;
  20665. buffer = webglObject.buffer;
  20666. // culling is overriden globally for all objects
  20667. // while rendering depth map
  20668. // need to deal with MeshFaceMaterial somehow
  20669. // in that case just use the first of material.materials for now
  20670. // (proper solution would require to break objects by materials
  20671. // similarly to regular rendering and then set corresponding
  20672. // depth materials per each chunk instead of just once per object)
  20673. objectMaterial = getObjectMaterial( object );
  20674. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20675. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20676. if ( object.customDepthMaterial ) {
  20677. material = object.customDepthMaterial;
  20678. } else if ( useSkinning ) {
  20679. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20680. } else if ( useMorphing ) {
  20681. material = _depthMaterialMorph;
  20682. } else {
  20683. material = _depthMaterial;
  20684. }
  20685. if ( buffer instanceof THREE.BufferGeometry ) {
  20686. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20687. } else {
  20688. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20689. }
  20690. }
  20691. }
  20692. // set matrices and render immediate objects
  20693. renderList = scene.__webglObjectsImmediate;
  20694. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20695. webglObject = renderList[ j ];
  20696. object = webglObject.object;
  20697. if ( object.visible && object.castShadow ) {
  20698. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20699. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20700. }
  20701. }
  20702. }
  20703. // restore GL state
  20704. var clearColor = _renderer.getClearColor(),
  20705. clearAlpha = _renderer.getClearAlpha();
  20706. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20707. _gl.enable( _gl.BLEND );
  20708. if ( _renderer.shadowMapCullFrontFaces ) {
  20709. _gl.cullFace( _gl.BACK );
  20710. }
  20711. };
  20712. function createVirtualLight( light, cascade ) {
  20713. var virtualLight = new THREE.DirectionalLight();
  20714. virtualLight.isVirtual = true;
  20715. virtualLight.onlyShadow = true;
  20716. virtualLight.castShadow = true;
  20717. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20718. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20719. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20720. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20721. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20722. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20723. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20724. virtualLight.shadowDarkness = light.shadowDarkness;
  20725. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20726. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20727. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20728. virtualLight.pointsWorld = [];
  20729. virtualLight.pointsFrustum = [];
  20730. var pointsWorld = virtualLight.pointsWorld,
  20731. pointsFrustum = virtualLight.pointsFrustum;
  20732. for ( var i = 0; i < 8; i ++ ) {
  20733. pointsWorld[ i ] = new THREE.Vector3();
  20734. pointsFrustum[ i ] = new THREE.Vector3();
  20735. }
  20736. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20737. var farZ = light.shadowCascadeFarZ[ cascade ];
  20738. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20739. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20740. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20741. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20742. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20743. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20744. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20745. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20746. return virtualLight;
  20747. }
  20748. // Synchronize virtual light with the original light
  20749. function updateVirtualLight( light, cascade ) {
  20750. var virtualLight = light.shadowCascadeArray[ cascade ];
  20751. virtualLight.position.copy( light.position );
  20752. virtualLight.target.position.copy( light.target.position );
  20753. virtualLight.lookAt( virtualLight.target );
  20754. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20755. virtualLight.shadowDarkness = light.shadowDarkness;
  20756. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20757. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20758. var farZ = light.shadowCascadeFarZ[ cascade ];
  20759. var pointsFrustum = virtualLight.pointsFrustum;
  20760. pointsFrustum[ 0 ].z = nearZ;
  20761. pointsFrustum[ 1 ].z = nearZ;
  20762. pointsFrustum[ 2 ].z = nearZ;
  20763. pointsFrustum[ 3 ].z = nearZ;
  20764. pointsFrustum[ 4 ].z = farZ;
  20765. pointsFrustum[ 5 ].z = farZ;
  20766. pointsFrustum[ 6 ].z = farZ;
  20767. pointsFrustum[ 7 ].z = farZ;
  20768. }
  20769. // Fit shadow camera's ortho frustum to camera frustum
  20770. function updateShadowCamera( camera, light ) {
  20771. var shadowCamera = light.shadowCamera,
  20772. pointsFrustum = light.pointsFrustum,
  20773. pointsWorld = light.pointsWorld;
  20774. _min.set( Infinity, Infinity, Infinity );
  20775. _max.set( -Infinity, -Infinity, -Infinity );
  20776. for ( var i = 0; i < 8; i ++ ) {
  20777. var p = pointsWorld[ i ];
  20778. p.copy( pointsFrustum[ i ] );
  20779. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20780. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  20781. if ( p.x < _min.x ) _min.x = p.x;
  20782. if ( p.x > _max.x ) _max.x = p.x;
  20783. if ( p.y < _min.y ) _min.y = p.y;
  20784. if ( p.y > _max.y ) _max.y = p.y;
  20785. if ( p.z < _min.z ) _min.z = p.z;
  20786. if ( p.z > _max.z ) _max.z = p.z;
  20787. }
  20788. shadowCamera.left = _min.x;
  20789. shadowCamera.right = _max.x;
  20790. shadowCamera.top = _max.y;
  20791. shadowCamera.bottom = _min.y;
  20792. // can't really fit near/far
  20793. //shadowCamera.near = _min.z;
  20794. //shadowCamera.far = _max.z;
  20795. shadowCamera.updateProjectionMatrix();
  20796. }
  20797. // For the moment just ignore objects that have multiple materials with different animation methods
  20798. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  20799. function getObjectMaterial( object ) {
  20800. return object.material instanceof THREE.MeshFaceMaterial
  20801. ? object.material.materials[ 0 ]
  20802. : object.material;
  20803. };
  20804. };
  20805. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20806. /**
  20807. * @author mikael emtinger / http://gomo.se/
  20808. * @author alteredq / http://alteredqualia.com/
  20809. */
  20810. THREE.SpritePlugin = function ( ) {
  20811. var _gl, _renderer, _sprite = {};
  20812. this.init = function ( renderer ) {
  20813. _gl = renderer.context;
  20814. _renderer = renderer;
  20815. _sprite.vertices = new Float32Array( 8 + 8 );
  20816. _sprite.faces = new Uint16Array( 6 );
  20817. var i = 0;
  20818. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20819. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20820. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  20821. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  20822. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  20823. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  20824. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  20825. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  20826. i = 0;
  20827. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  20828. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  20829. _sprite.vertexBuffer = _gl.createBuffer();
  20830. _sprite.elementBuffer = _gl.createBuffer();
  20831. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20832. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  20833. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20834. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  20835. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  20836. _sprite.attributes = {};
  20837. _sprite.uniforms = {};
  20838. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  20839. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  20840. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  20841. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  20842. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  20843. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  20844. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  20845. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  20846. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  20847. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  20848. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  20849. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  20850. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  20851. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  20852. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  20853. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  20854. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  20855. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  20856. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  20857. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  20858. _sprite.attributesEnabled = false;
  20859. };
  20860. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20861. var sprites = scene.__webglSprites,
  20862. nSprites = sprites.length;
  20863. if ( ! nSprites ) return;
  20864. var attributes = _sprite.attributes,
  20865. uniforms = _sprite.uniforms;
  20866. var invAspect = viewportHeight / viewportWidth;
  20867. var halfViewportWidth = viewportWidth * 0.5,
  20868. halfViewportHeight = viewportHeight * 0.5;
  20869. var mergeWith3D = true;
  20870. // setup gl
  20871. _gl.useProgram( _sprite.program );
  20872. if ( ! _sprite.attributesEnabled ) {
  20873. _gl.enableVertexAttribArray( attributes.position );
  20874. _gl.enableVertexAttribArray( attributes.uv );
  20875. _sprite.attributesEnabled = true;
  20876. }
  20877. _gl.disable( _gl.CULL_FACE );
  20878. _gl.enable( _gl.BLEND );
  20879. _gl.depthMask( true );
  20880. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20881. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20882. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20883. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20884. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  20885. _gl.activeTexture( _gl.TEXTURE0 );
  20886. _gl.uniform1i( uniforms.map, 0 );
  20887. var oldFogType = 0;
  20888. var sceneFogType = 0;
  20889. var fog = scene.fog;
  20890. if ( fog ) {
  20891. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  20892. if ( fog instanceof THREE.Fog ) {
  20893. _gl.uniform1f( uniforms.fogNear, fog.near );
  20894. _gl.uniform1f( uniforms.fogFar, fog.far );
  20895. _gl.uniform1i( uniforms.fogType, 1 );
  20896. oldFogType = 1;
  20897. sceneFogType = 1;
  20898. } else if ( fog instanceof THREE.FogExp2 ) {
  20899. _gl.uniform1f( uniforms.fogDensity, fog.density );
  20900. _gl.uniform1i( uniforms.fogType, 2 );
  20901. oldFogType = 2;
  20902. sceneFogType = 2;
  20903. }
  20904. } else {
  20905. _gl.uniform1i( uniforms.fogType, 0 );
  20906. oldFogType = 0;
  20907. sceneFogType = 0;
  20908. }
  20909. // update positions and sort
  20910. var i, sprite, screenPosition, size, fogType, scale = [];
  20911. for( i = 0; i < nSprites; i ++ ) {
  20912. sprite = sprites[ i ];
  20913. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20914. if ( ! sprite.useScreenCoordinates ) {
  20915. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  20916. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  20917. } else {
  20918. sprite.z = - sprite.position.z;
  20919. }
  20920. }
  20921. sprites.sort( painterSortStable );
  20922. // render all sprites
  20923. for( i = 0; i < nSprites; i ++ ) {
  20924. sprite = sprites[ i ];
  20925. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20926. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  20927. if ( sprite.useScreenCoordinates ) {
  20928. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  20929. _gl.uniform3f(
  20930. uniforms.screenPosition,
  20931. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  20932. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  20933. Math.max( 0, Math.min( 1, sprite.position.z ) )
  20934. );
  20935. } else {
  20936. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  20937. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  20938. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  20939. }
  20940. if ( scene.fog && sprite.fog ) {
  20941. fogType = sceneFogType;
  20942. } else {
  20943. fogType = 0;
  20944. }
  20945. if ( oldFogType !== fogType ) {
  20946. _gl.uniform1i( uniforms.fogType, fogType );
  20947. oldFogType = fogType;
  20948. }
  20949. size = 1 / ( sprite.scaleByViewport ? viewportHeight : 1 );
  20950. scale[ 0 ] = size * invAspect * sprite.scale.x;
  20951. scale[ 1 ] = size * sprite.scale.y;
  20952. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  20953. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  20954. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  20955. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20956. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20957. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20958. _gl.uniform2fv( uniforms.scale, scale );
  20959. if ( sprite.mergeWith3D && !mergeWith3D ) {
  20960. _gl.enable( _gl.DEPTH_TEST );
  20961. mergeWith3D = true;
  20962. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  20963. _gl.disable( _gl.DEPTH_TEST );
  20964. mergeWith3D = false;
  20965. }
  20966. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20967. _renderer.setTexture( sprite.map, 0 );
  20968. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20969. }
  20970. }
  20971. // restore gl
  20972. _gl.enable( _gl.CULL_FACE );
  20973. _gl.enable( _gl.DEPTH_TEST );
  20974. _gl.depthMask( true );
  20975. };
  20976. function createProgram ( shader ) {
  20977. var program = _gl.createProgram();
  20978. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20979. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20980. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20981. _gl.shaderSource( vertexShader, shader.vertexShader );
  20982. _gl.compileShader( fragmentShader );
  20983. _gl.compileShader( vertexShader );
  20984. _gl.attachShader( program, fragmentShader );
  20985. _gl.attachShader( program, vertexShader );
  20986. _gl.linkProgram( program );
  20987. return program;
  20988. };
  20989. function painterSortStable ( a, b ) {
  20990. if ( a.z !== b.z ) {
  20991. return b.z - a.z;
  20992. } else {
  20993. return b.id - a.id;
  20994. }
  20995. };
  20996. };/**
  20997. * @author alteredq / http://alteredqualia.com/
  20998. */
  20999. THREE.DepthPassPlugin = function ( ) {
  21000. this.enabled = false;
  21001. this.renderTarget = null;
  21002. var _gl,
  21003. _renderer,
  21004. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21005. _frustum = new THREE.Frustum(),
  21006. _projScreenMatrix = new THREE.Matrix4();
  21007. this.init = function ( renderer ) {
  21008. _gl = renderer.context;
  21009. _renderer = renderer;
  21010. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21011. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21012. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21013. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21014. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21015. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21016. _depthMaterial._shadowPass = true;
  21017. _depthMaterialMorph._shadowPass = true;
  21018. _depthMaterialSkin._shadowPass = true;
  21019. _depthMaterialMorphSkin._shadowPass = true;
  21020. };
  21021. this.render = function ( scene, camera ) {
  21022. if ( ! this.enabled ) return;
  21023. this.update( scene, camera );
  21024. };
  21025. this.update = function ( scene, camera ) {
  21026. var i, il, j, jl, n,
  21027. program, buffer, material,
  21028. webglObject, object, light,
  21029. renderList,
  21030. fog = null;
  21031. // set GL state for depth map
  21032. _gl.clearColor( 1, 1, 1, 1 );
  21033. _gl.disable( _gl.BLEND );
  21034. _renderer.setDepthTest( true );
  21035. // update scene
  21036. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21037. // update camera matrices and frustum
  21038. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  21039. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  21040. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21041. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  21042. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  21043. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21044. _frustum.setFromMatrix( _projScreenMatrix );
  21045. // render depth map
  21046. _renderer.setRenderTarget( this.renderTarget );
  21047. _renderer.clear();
  21048. // set object matrices & frustum culling
  21049. renderList = scene.__webglObjects;
  21050. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21051. webglObject = renderList[ j ];
  21052. object = webglObject.object;
  21053. webglObject.render = false;
  21054. if ( object.visible ) {
  21055. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21056. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21057. webglObject.render = true;
  21058. }
  21059. }
  21060. }
  21061. // render regular objects
  21062. var objectMaterial, useMorphing, useSkinning;
  21063. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21064. webglObject = renderList[ j ];
  21065. if ( webglObject.render ) {
  21066. object = webglObject.object;
  21067. buffer = webglObject.buffer;
  21068. // todo: create proper depth material for particles
  21069. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21070. objectMaterial = getObjectMaterial( object );
  21071. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21072. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21073. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21074. if ( object.customDepthMaterial ) {
  21075. material = object.customDepthMaterial;
  21076. } else if ( useSkinning ) {
  21077. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21078. } else if ( useMorphing ) {
  21079. material = _depthMaterialMorph;
  21080. } else {
  21081. material = _depthMaterial;
  21082. }
  21083. if ( buffer instanceof THREE.BufferGeometry ) {
  21084. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21085. } else {
  21086. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21087. }
  21088. }
  21089. }
  21090. // set matrices and render immediate objects
  21091. renderList = scene.__webglObjectsImmediate;
  21092. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21093. webglObject = renderList[ j ];
  21094. object = webglObject.object;
  21095. if ( object.visible ) {
  21096. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21097. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21098. }
  21099. }
  21100. // restore GL state
  21101. var clearColor = _renderer.getClearColor(),
  21102. clearAlpha = _renderer.getClearAlpha();
  21103. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21104. _gl.enable( _gl.BLEND );
  21105. };
  21106. // For the moment just ignore objects that have multiple materials with different animation methods
  21107. // Only the first material will be taken into account for deciding which depth material to use
  21108. function getObjectMaterial( object ) {
  21109. return object.material instanceof THREE.MeshFaceMaterial
  21110. ? object.material.materials[ 0 ]
  21111. : object.material;
  21112. };
  21113. };
  21114. /**
  21115. * @author mikael emtinger / http://gomo.se/
  21116. *
  21117. */
  21118. THREE.ShaderFlares = {
  21119. 'lensFlareVertexTexture': {
  21120. vertexShader: [
  21121. "uniform vec3 screenPosition;",
  21122. "uniform vec2 scale;",
  21123. "uniform float rotation;",
  21124. "uniform int renderType;",
  21125. "uniform sampler2D occlusionMap;",
  21126. "attribute vec2 position;",
  21127. "attribute vec2 uv;",
  21128. "varying vec2 vUV;",
  21129. "varying float vVisibility;",
  21130. "void main() {",
  21131. "vUV = uv;",
  21132. "vec2 pos = position;",
  21133. "if( renderType == 2 ) {",
  21134. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21135. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21136. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21137. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21138. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21139. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21140. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21141. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21142. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21143. "vVisibility = ( visibility.r / 9.0 ) *",
  21144. "( 1.0 - visibility.g / 9.0 ) *",
  21145. "( visibility.b / 9.0 ) *",
  21146. "( 1.0 - visibility.a / 9.0 );",
  21147. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21148. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21149. "}",
  21150. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21151. "}"
  21152. ].join( "\n" ),
  21153. fragmentShader: [
  21154. "precision mediump float;",
  21155. "uniform sampler2D map;",
  21156. "uniform float opacity;",
  21157. "uniform int renderType;",
  21158. "uniform vec3 color;",
  21159. "varying vec2 vUV;",
  21160. "varying float vVisibility;",
  21161. "void main() {",
  21162. // pink square
  21163. "if( renderType == 0 ) {",
  21164. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21165. // restore
  21166. "} else if( renderType == 1 ) {",
  21167. "gl_FragColor = texture2D( map, vUV );",
  21168. // flare
  21169. "} else {",
  21170. "vec4 texture = texture2D( map, vUV );",
  21171. "texture.a *= opacity * vVisibility;",
  21172. "gl_FragColor = texture;",
  21173. "gl_FragColor.rgb *= color;",
  21174. "}",
  21175. "}"
  21176. ].join( "\n" )
  21177. },
  21178. 'lensFlare': {
  21179. vertexShader: [
  21180. "uniform vec3 screenPosition;",
  21181. "uniform vec2 scale;",
  21182. "uniform float rotation;",
  21183. "uniform int renderType;",
  21184. "attribute vec2 position;",
  21185. "attribute vec2 uv;",
  21186. "varying vec2 vUV;",
  21187. "void main() {",
  21188. "vUV = uv;",
  21189. "vec2 pos = position;",
  21190. "if( renderType == 2 ) {",
  21191. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21192. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21193. "}",
  21194. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21195. "}"
  21196. ].join( "\n" ),
  21197. fragmentShader: [
  21198. "precision mediump float;",
  21199. "uniform sampler2D map;",
  21200. "uniform sampler2D occlusionMap;",
  21201. "uniform float opacity;",
  21202. "uniform int renderType;",
  21203. "uniform vec3 color;",
  21204. "varying vec2 vUV;",
  21205. "void main() {",
  21206. // pink square
  21207. "if( renderType == 0 ) {",
  21208. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21209. // restore
  21210. "} else if( renderType == 1 ) {",
  21211. "gl_FragColor = texture2D( map, vUV );",
  21212. // flare
  21213. "} else {",
  21214. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21215. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21216. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21217. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21218. "visibility = ( 1.0 - visibility / 4.0 );",
  21219. "vec4 texture = texture2D( map, vUV );",
  21220. "texture.a *= opacity * visibility;",
  21221. "gl_FragColor = texture;",
  21222. "gl_FragColor.rgb *= color;",
  21223. "}",
  21224. "}"
  21225. ].join( "\n" )
  21226. }
  21227. };
  21228. /**
  21229. * @author mikael emtinger / http://gomo.se/
  21230. * @author alteredq / http://alteredqualia.com/
  21231. *
  21232. */
  21233. THREE.ShaderSprite = {
  21234. 'sprite': {
  21235. vertexShader: [
  21236. "uniform int useScreenCoordinates;",
  21237. "uniform int affectedByDistance;",
  21238. "uniform vec3 screenPosition;",
  21239. "uniform mat4 modelViewMatrix;",
  21240. "uniform mat4 projectionMatrix;",
  21241. "uniform float rotation;",
  21242. "uniform vec2 scale;",
  21243. "uniform vec2 alignment;",
  21244. "uniform vec2 uvOffset;",
  21245. "uniform vec2 uvScale;",
  21246. "attribute vec2 position;",
  21247. "attribute vec2 uv;",
  21248. "varying vec2 vUV;",
  21249. "void main() {",
  21250. "vUV = uvOffset + uv * uvScale;",
  21251. "vec2 alignedPosition = position + alignment;",
  21252. "vec2 rotatedPosition;",
  21253. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21254. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21255. "vec4 finalPosition;",
  21256. "if( useScreenCoordinates != 0 ) {",
  21257. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21258. "} else {",
  21259. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21260. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  21261. "}",
  21262. "gl_Position = finalPosition;",
  21263. "}"
  21264. ].join( "\n" ),
  21265. fragmentShader: [
  21266. "precision mediump float;",
  21267. "uniform vec3 color;",
  21268. "uniform sampler2D map;",
  21269. "uniform float opacity;",
  21270. "uniform int fogType;",
  21271. "uniform vec3 fogColor;",
  21272. "uniform float fogDensity;",
  21273. "uniform float fogNear;",
  21274. "uniform float fogFar;",
  21275. "varying vec2 vUV;",
  21276. "void main() {",
  21277. "vec4 texture = texture2D( map, vUV );",
  21278. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21279. "if ( fogType > 0 ) {",
  21280. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21281. "float fogFactor = 0.0;",
  21282. "if ( fogType == 1 ) {",
  21283. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21284. "} else {",
  21285. "const float LOG2 = 1.442695;",
  21286. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21287. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21288. "}",
  21289. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21290. "}",
  21291. "}"
  21292. ].join( "\n" )
  21293. }
  21294. };
粤ICP备19079148号